Translate everything to typescript
This commit is contained in:
1 parent
c3ca3e1752
commit
e9818aaeda
27 files changed
+901
-552
No files matched your search
+2
-2
@@ -1,9 +1,9 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import SendPanel from './components/SendPanel.vue';
|
||||
import ReceivePanel from './components/ReceivePanel.vue';
|
||||
|
||||
const mode = ref('send');
|
||||
const mode = ref<'send' | 'receive'>('send');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup>
|
||||
import { STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
const settings = defineModel({ required: true });
|
||||
defineProps({ disabled: Boolean });
|
||||
<script setup lang="ts">
|
||||
import type { NetworkSettings } from '../lib/webrtc.ts';
|
||||
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
const settings = defineModel<NetworkSettings>({ required: true });
|
||||
defineProps<{ disabled?: boolean }>();
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
</script>
|
||||
<template><TransferPanel /></template>
|
||||
@@ -1,4 +1,4 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
</script>
|
||||
<template><TransferPanel sending /></template>
|
||||
@@ -1,29 +1,42 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import { asError } from '../lib/validation.ts';
|
||||
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
|
||||
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
|
||||
|
||||
const props = defineProps({ sending: Boolean });
|
||||
const file = ref(null);
|
||||
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
pc: RTCPeerConnection;
|
||||
options: IceOptions;
|
||||
file: File | null;
|
||||
controller: AbortController;
|
||||
transfer: Transfer | null;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const props = defineProps<{ sending?: boolean }>();
|
||||
const file = ref<File | null>(null);
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref('idle');
|
||||
const step = ref<Step>('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref(null);
|
||||
const fps = ref<Fingerprints | null>(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref(null);
|
||||
const incoming = ref<FileMetadata | null>(null);
|
||||
const downloadUrl = ref('');
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||
const settings = ref({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
let active = null;
|
||||
let copyTimer;
|
||||
let active: Session | null = null;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
|
||||
const status = computed(() => ({
|
||||
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
|
||||
@@ -63,22 +76,23 @@ function reset(keepNetwork = false) {
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; step.value = 'idle';
|
||||
}
|
||||
function fail(session, err) {
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
dispose(); revokeDownload();
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
settings.value.allowTurn = false;
|
||||
error.value = err.message || 'Connection failed.'; step.value = 'closed';
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
function pickFiles(event) {
|
||||
const selected = event.target?.files?.[0] ?? event.dataTransfer?.files?.[0];
|
||||
function pickFiles(event: Event) {
|
||||
const selected = event.target instanceof HTMLInputElement ? event.target.files?.[0]
|
||||
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined;
|
||||
if (!selected) return;
|
||||
reset();
|
||||
if (selected.size > FILE_LIMIT) { file.value = null; error.value = 'The maximum file size is 64 GiB.'; return; }
|
||||
file.value = selected;
|
||||
}
|
||||
function attach(session, channel) {
|
||||
function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
@@ -113,7 +127,7 @@ function start() {
|
||||
};
|
||||
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
active = session;
|
||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||
pc.ondatachannel = event => attach(session, event.channel);
|
||||
@@ -129,7 +143,7 @@ function start() {
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session;
|
||||
let session: Session | undefined;
|
||||
try {
|
||||
if (props.sending) {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
@@ -148,7 +162,7 @@ async function createCode() {
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = err.message; step.value = 'closed'; }
|
||||
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
@@ -165,7 +179,7 @@ async function useAnswer() {
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${err.message || 'Invalid answer.'} Correct the answer and connect again; your offer is still valid.`;
|
||||
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
@@ -179,13 +193,14 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(toDisk) {
|
||||
async function acceptFile(toDisk: boolean) {
|
||||
const session = active;
|
||||
if (!session?.transfer || choosing.value || step.value !== 'choose-storage') return;
|
||||
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable;
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (toDisk) {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
@@ -194,7 +209,7 @@ async function acceptFile(toDisk) {
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
if (active === session && err.name !== 'AbortError') error.value = err.message || 'Could not open the destination file.';
|
||||
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
|
||||
} finally { if (active === session) choosing.value = false; }
|
||||
}
|
||||
async function copy() {
|
||||
@@ -206,11 +221,14 @@ async function copy() {
|
||||
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
|
||||
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
|
||||
}
|
||||
function formatBytes(bytes) {
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(3, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB'][index]}`;
|
||||
}
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
@@ -233,7 +251,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
|
||||
<template v-if="outputCode">
|
||||
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="$event.target.select()" />
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
</template>
|
||||
<template v-if="sending && outputCode">
|
||||
@@ -258,7 +276,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
|
||||
</div>
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_ICE_ENDPOINT?: string;
|
||||
readonly VITE_STUN_URL?: string;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
|
||||
}
|
||||
@@ -1,14 +1,45 @@
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.js';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
import type { BufferedChannel } from './webrtc.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.ts';
|
||||
|
||||
export interface FileMetadata { name: string; size: number; mime: string }
|
||||
export type TransferState = 'verification' | 'waiting-accept' | 'choose-storage' | 'sending' |
|
||||
'receiving' | 'saving' | 'awaiting-receipt' | 'done' | 'closed';
|
||||
export interface TransferResult { blob?: Blob | null; meta: FileMetadata }
|
||||
export interface FileDestination {
|
||||
write(data: ArrayBuffer): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
abort(): Promise<void>;
|
||||
}
|
||||
export interface TransferChannel extends BufferedChannel {
|
||||
binaryType: BinaryType;
|
||||
onopen: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent<unknown>) => void) | null;
|
||||
onclose: ((event: Event) => void) | null;
|
||||
onerror: ((event: RTCErrorEvent) => void) | null;
|
||||
send(data: string | ArrayBuffer): void;
|
||||
close(): void;
|
||||
}
|
||||
export interface TransferOptions {
|
||||
file?: File | null;
|
||||
onState?: (state: TransferState) => void;
|
||||
onMeta?: (meta: FileMetadata) => void;
|
||||
onProgress?: (bytes: number, size: number) => void;
|
||||
onComplete?: (result: TransferResult) => void;
|
||||
onError?: (error: Error) => void;
|
||||
timeout?: number;
|
||||
}
|
||||
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
|
||||
|
||||
export const MEMORY_LIMIT = 64 * 1024 * 1024;
|
||||
export const FILE_LIMIT = 64 * 1024 * 1024 * 1024;
|
||||
const CONTROL_LIMIT = 2048;
|
||||
const WINDOW = MAX_BUFFERED;
|
||||
|
||||
export function validateMetadata(meta) {
|
||||
if (!meta || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
export function validateMetadata(meta: unknown): FileMetadata {
|
||||
if (!isRecord(meta) || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
|
||||
!Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
|
||||
typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
|
||||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
|
||||
throw new Error('Invalid file metadata or file exceeds the 64 GiB limit.');
|
||||
}
|
||||
@@ -17,8 +48,45 @@ export function validateMetadata(meta) {
|
||||
|
||||
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
|
||||
export class Transfer {
|
||||
constructor(dc, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 } = {}) {
|
||||
Object.assign(this, { dc, file, onState, onMeta, onProgress, onComplete, onError, timeout });
|
||||
readonly dc: TransferChannel;
|
||||
readonly file: File | null;
|
||||
readonly onState: NonNullable<TransferOptions['onState']>;
|
||||
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
|
||||
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
|
||||
readonly onComplete: NonNullable<TransferOptions['onComplete']>;
|
||||
readonly onError: NonNullable<TransferOptions['onError']>;
|
||||
readonly timeout: number;
|
||||
state: TransferState;
|
||||
verified: boolean;
|
||||
peerReady: boolean;
|
||||
readySent: boolean;
|
||||
closed: boolean;
|
||||
received: number;
|
||||
sent: number;
|
||||
acked: number;
|
||||
queued: number;
|
||||
messages: number;
|
||||
chunks: ArrayBuffer[];
|
||||
queue: Promise<void>;
|
||||
readonly controller: AbortController;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private meta: FileMetadata | null = null;
|
||||
private writable: FileDestination | null = null;
|
||||
private wake: (() => void) | null = null;
|
||||
|
||||
private get metadata(): FileMetadata {
|
||||
if (!this.meta) throw new Error('Missing file metadata.');
|
||||
return this.meta;
|
||||
}
|
||||
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 }: TransferOptions = {}) {
|
||||
this.dc = dc;
|
||||
this.file = file;
|
||||
this.onState = onState;
|
||||
this.onMeta = onMeta;
|
||||
this.onProgress = onProgress;
|
||||
this.onComplete = onComplete;
|
||||
this.onError = onError;
|
||||
this.timeout = timeout;
|
||||
this.state = 'verification';
|
||||
this.verified = false;
|
||||
this.peerReady = false;
|
||||
@@ -31,7 +99,7 @@ export class Transfer {
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.guard(() => this.ready());
|
||||
dc.onmessage = e => this.enqueue(e.data);
|
||||
const transportEnded = message => {
|
||||
const transportEnded = (message: string) => {
|
||||
// Firefox can report an SCTP error when the sender closes its peer
|
||||
// connection after receiving our completion ACK. The saved file remains
|
||||
// valid; a transport shutdown must not revoke a completed download.
|
||||
@@ -42,13 +110,13 @@ export class Transfer {
|
||||
dc.onerror = () => transportEnded('Data channel failed.');
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
setState(state) { this.state = state; this.onState(state); }
|
||||
setState(state: TransferState) { this.state = state; this.onState(state); }
|
||||
touch(ms = this.timeout) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
|
||||
}
|
||||
guard(fn) { try { fn(); } catch (err) { this.fail(err); } }
|
||||
control(type, data = {}) {
|
||||
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
|
||||
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number } = {}) {
|
||||
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
|
||||
const text = JSON.stringify({ v: 2, type, ...data });
|
||||
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
|
||||
@@ -65,11 +133,11 @@ export class Transfer {
|
||||
if (this.file && this.peerReady && this.state === 'verification') {
|
||||
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
|
||||
this.setState('waiting-accept');
|
||||
this.control('meta', this.meta);
|
||||
this.control('meta', this.metadata);
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
enqueue(data) {
|
||||
enqueue(data: unknown) {
|
||||
if (this.closed) return;
|
||||
const binary = data instanceof ArrayBuffer;
|
||||
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
|
||||
@@ -81,42 +149,43 @@ export class Transfer {
|
||||
if (!this.closed) await this.message(data);
|
||||
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
|
||||
}
|
||||
async message(data) {
|
||||
async message(data: unknown) {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.meta.size) throw new Error('Unexpected or excess file data.');
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.metadata.size) throw new Error('Unexpected or excess file data.');
|
||||
// Bound per-chunk overhead as well as payload bytes: millions of tiny
|
||||
// ArrayBuffers would otherwise defeat the in-memory size limit.
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.meta.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.metadata.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (this.writable) await this.writable.write(data);
|
||||
else this.chunks.push(data);
|
||||
if (this.closed) return;
|
||||
this.received += data.byteLength;
|
||||
this.control('ack', { bytes: this.received });
|
||||
this.onProgress(this.received, this.meta.size);
|
||||
this.onProgress(this.received, this.metadata.size);
|
||||
this.touch();
|
||||
return;
|
||||
}
|
||||
const msg = JSON.parse(data);
|
||||
if (!msg || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
|
||||
if (typeof data !== 'string') throw new Error('Unsupported transfer message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
|
||||
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'meta' && !this.file && this.state === 'verification') {
|
||||
this.meta = validateMetadata(msg);
|
||||
this.setState('choose-storage'); this.onMeta(this.meta); this.touch(5 * 60 * 1000); return;
|
||||
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
|
||||
}
|
||||
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
|
||||
this.setState('sending'); this.touch();
|
||||
void this.sendFile().catch(err => this.fail(err)); return;
|
||||
}
|
||||
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
|
||||
if (!Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
if (typeof msg.bytes !== 'number' || !Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
|
||||
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
|
||||
}
|
||||
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
|
||||
if (this.received !== this.meta.size) throw new Error('Incomplete file.');
|
||||
if (this.received !== this.metadata.size) throw new Error('Incomplete file.');
|
||||
this.setState('saving');
|
||||
if (this.writable) await this.writable.close();
|
||||
if (this.closed) return;
|
||||
@@ -125,27 +194,29 @@ export class Transfer {
|
||||
this.chunks = [];
|
||||
this.control('complete', { bytes: this.received });
|
||||
this.setState('done'); clearTimeout(this.timer);
|
||||
this.onComplete({ blob, meta: this.meta }); return;
|
||||
this.onComplete({ blob, meta: this.metadata }); return;
|
||||
}
|
||||
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.meta }); this.close(); return;
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata }); this.close(); return;
|
||||
}
|
||||
throw new Error('Unexpected transfer message.');
|
||||
}
|
||||
accept(writable = null) {
|
||||
accept(writable: FileDestination | null = null) {
|
||||
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
|
||||
if (!writable && this.meta.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
|
||||
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
|
||||
this.writable = writable;
|
||||
this.setState('receiving'); this.touch();
|
||||
this.guard(() => this.control('accept'));
|
||||
}
|
||||
async sendFile() {
|
||||
for (let offset = 0; offset < this.file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise(resolve => { this.wake = resolve; });
|
||||
const file = this.file;
|
||||
if (!file) throw new Error('No file selected.');
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise<void>(resolve => { this.wake = resolve; });
|
||||
this.wake = null;
|
||||
if (this.closed) return;
|
||||
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
|
||||
const buffer = await this.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
const buffer = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
if (this.closed) return;
|
||||
this.sent += buffer.byteLength;
|
||||
this.dc.send(buffer);
|
||||
@@ -153,15 +224,16 @@ export class Transfer {
|
||||
if (this.closed) return;
|
||||
this.setState('awaiting-receipt'); this.control('end'); this.touch();
|
||||
}
|
||||
fail(err) {
|
||||
fail(err: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.setState('closed'); this.onError(err);
|
||||
this.close(); this.setState('closed'); this.onError(asError(err));
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
|
||||
this.chunks = [];
|
||||
if (this.writable && this.state !== 'done') Promise.resolve().then(() => this.writable.abort()).catch(() => {});
|
||||
const writable = this.writable;
|
||||
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
|
||||
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
|
||||
this.dc.close();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
|
||||
}
|
||||
|
||||
export function asError(value: unknown, fallback = 'Connection failed.'): Error {
|
||||
return value instanceof Error ? value : new Error(fallback);
|
||||
}
|
||||
@@ -1,3 +1,31 @@
|
||||
import { asError, isRecord, isStringArray } from './validation.ts';
|
||||
|
||||
export interface IceOptions {
|
||||
stunUrl?: string | null;
|
||||
allowTurn?: boolean;
|
||||
managedTurn?: boolean;
|
||||
turnUrl?: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
export interface NetworkSettings {
|
||||
stunChoice: 'google' | 'cloudflare' | 'none' | 'custom';
|
||||
customStun: string;
|
||||
allowTurn: boolean;
|
||||
managedTurn: boolean;
|
||||
turnUrl: string;
|
||||
username: string;
|
||||
credential: string;
|
||||
}
|
||||
|
||||
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
|
||||
export interface Fingerprints { local: string; remote: string }
|
||||
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
|
||||
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
|
||||
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
|
||||
|
||||
// Manual signaling. Codes are encoded connection details, not encrypted secrets.
|
||||
export const CHUNK_SIZE = 16 * 1024;
|
||||
export const MAX_BUFFERED = 1024 * 1024;
|
||||
@@ -8,8 +36,8 @@ export const STUN_PROVIDERS = [
|
||||
{ id: 'none', label: 'None (direct connections only)', url: null },
|
||||
];
|
||||
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' } = {}) {
|
||||
const iceServers = [];
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' }: IceOptions = {}): { iceServers: RTCIceServer[] } {
|
||||
const iceServers: RTCIceServer[] = [];
|
||||
if (stunUrl) {
|
||||
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
|
||||
iceServers.push({ urls: stunUrl });
|
||||
@@ -25,35 +53,43 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
export async function fetchTurnOptions(options, endpoint, { signal, fetchImpl = fetch } = {}) {
|
||||
export async function fetchTurnOptions(options: IceOptions, endpoint: string, { signal, fetchImpl = fetch }: { signal?: AbortSignal; fetchImpl?: CredentialFetch } = {}): Promise<IceOptions> {
|
||||
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||
const { expiresAt, iceServers } = await response.json();
|
||||
const turn = iceServers?.find(server => {
|
||||
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length && urls.every(url => /^turns?:/i.test(url));
|
||||
const data: unknown = await response.json();
|
||||
if (!isRecord(data) || typeof data.expiresAt !== 'number' || !Number.isFinite(data.expiresAt) ||
|
||||
data.expiresAt <= Date.now() / 1000 + 30 || !Array.isArray(data.iceServers)) {
|
||||
throw new Error('Missing or expired TURN credentials.');
|
||||
}
|
||||
const turn: unknown = data.iceServers.find((server: unknown) => {
|
||||
if (!isRecord(server)) return false;
|
||||
const urls: unknown[] = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length > 0 && urls.every(url => typeof url === 'string' && /^turns?:/i.test(url));
|
||||
});
|
||||
if (!turn || !Number.isFinite(expiresAt) || expiresAt <= Date.now() / 1000 + 30) throw new Error('Missing or expired TURN credentials.');
|
||||
if (!isRecord(turn) || typeof turn.username !== 'string' || typeof turn.credential !== 'string' ||
|
||||
!(typeof turn.urls === 'string' || isStringArray(turn.urls))) {
|
||||
throw new Error('Missing or invalid TURN credentials.');
|
||||
}
|
||||
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||
iceConfiguration(result); // Validate before passing server-supplied data to WebRTC.
|
||||
iceConfiguration(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options) {
|
||||
export function createPeerConnection(options: IceOptions) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
export function waitForIceComplete(pc, { signal, timeout = 30000 } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer;
|
||||
export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
pc.removeEventListener('icegatheringstatechange', check);
|
||||
pc.removeEventListener('connectionstatechange', check);
|
||||
signal?.removeEventListener('abort', aborted);
|
||||
};
|
||||
const finish = (err) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const aborted = () => finish(new Error('Connection cancelled.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || pc.connectionState === 'closed') aborted();
|
||||
@@ -67,7 +103,7 @@ export function waitForIceComplete(pc, { signal, timeout = 30000 } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
export function validateDescription(sdp, { allowTurn = false } = {}) {
|
||||
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
|
||||
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
|
||||
throw new Error('Invalid connection description.');
|
||||
}
|
||||
@@ -87,55 +123,58 @@ export function validateDescription(sdp, { allowTurn = false } = {}) {
|
||||
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
|
||||
}
|
||||
|
||||
export function getFingerprints(pc, options) {
|
||||
export function getFingerprints(pc: { localDescription: { sdp: string } | null; remoteDescription: { sdp: string } | null }, options?: Pick<IceOptions, 'allowTurn'>): Fingerprints {
|
||||
return {
|
||||
local: validateDescription(pc.localDescription?.sdp, options),
|
||||
remote: validateDescription(pc.remoteDescription?.sdp, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function encodeSignal(sdp) {
|
||||
export function encodeSignal(sdp: string) {
|
||||
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, '');
|
||||
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
||||
return code;
|
||||
}
|
||||
|
||||
export function decodeSignal(text, options) {
|
||||
export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTurn'>): string {
|
||||
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
|
||||
try {
|
||||
const clean = text.trim().replace(/\s+/g, '');
|
||||
const data = JSON.parse(atob(clean));
|
||||
if (data?.version !== 2) throw new Error('Both people need the current HellCon version.');
|
||||
const data: unknown = JSON.parse(atob(clean));
|
||||
if (!isRecord(data) || data.version !== 2) throw new Error('Both people need the current HellCon version.');
|
||||
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
|
||||
validateDescription(data.sdp, options);
|
||||
return data.sdp;
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError || err.name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
||||
if (err instanceof SyntaxError || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOfferCode(pc, options = {}) {
|
||||
export async function createOfferCode(pc: RTCPeerConnection, options: SignalOptions = {}) {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
}
|
||||
|
||||
export async function createAnswerCode(pc, text, options = {}) {
|
||||
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) {
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) });
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
}
|
||||
|
||||
export function acceptAnswerCode(pc, text, options) {
|
||||
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) {
|
||||
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
|
||||
}
|
||||
|
||||
export function waitForBufferDrain(dc, { signal, timeout = 60000 } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer;
|
||||
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
dc.removeEventListener('bufferedamountlow', check);
|
||||
@@ -143,7 +182,7 @@ export function waitForBufferDrain(dc, { signal, timeout = 60000 } = {}) {
|
||||
dc.removeEventListener('error', failed);
|
||||
signal?.removeEventListener('abort', failed);
|
||||
};
|
||||
const finish = err => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const failed = () => finish(new Error('Transfer interrupted.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || dc.readyState !== 'open') failed();
|
||||
File renamed without changes.
Reference in new issue
Block a user