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; close(): Promise; abort(): Promise; } export interface TransferChannel extends BufferedChannel { binaryType: BinaryType; onopen: ((event: Event) => void) | null; onmessage: ((event: MessageEvent) => 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; const CONTROL_LIMIT = 2048; const WINDOW = MAX_BUFFERED; 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) || typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 || typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) { throw new Error('Invalid file metadata. File size must be a nonnegative safe integer.'); } return { name: meta.name, size: meta.size, mime: meta.mime }; } // One ordered, reliable channel; bounded receive queue and acknowledged send window. export class Transfer { readonly dc: TransferChannel; readonly file: File | null; readonly onState: NonNullable; readonly onMeta: NonNullable; readonly onProgress: NonNullable; readonly onComplete: NonNullable; readonly onError: NonNullable; 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; readonly controller: AbortController; private timer: ReturnType | 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; this.readySent = false; this.closed = false; this.received = this.sent = this.acked = this.queued = this.messages = 0; this.chunks = []; this.queue = Promise.resolve(); this.controller = new AbortController(); dc.binaryType = 'arraybuffer'; dc.onopen = () => this.guard(() => this.ready()); dc.onmessage = e => this.enqueue(e.data); 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. if (this.state === 'done') this.close(); else this.fail(new Error(message)); }; dc.onclose = () => transportEnded('Connection closed before receipt was confirmed.'); dc.onerror = () => transportEnded('Data channel failed.'); this.touch(5 * 60 * 1000); } 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: () => void) { try { fn(); } catch (err) { this.fail(err); } } control(type: ControlType, data: Partial & { 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.'); this.dc.send(text); } verify() { if (this.closed || this.verified) return; this.verified = true; this.guard(() => this.ready()); } ready() { if (!this.verified || this.dc.readyState !== 'open' || this.closed) return; if (!this.readySent) { this.control('ready'); this.readySent = true; } 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.metadata); this.touch(5 * 60 * 1000); } } enqueue(data: unknown) { if (this.closed) return; const binary = data instanceof ArrayBuffer; const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity; if (size > (binary ? CHUNK_SIZE : CONTROL_LIMIT) || this.queued + size > WINDOW * 2 || this.messages >= 128) { this.fail(new Error('Peer exceeded message or buffering limits.')); return; } this.queued += size; this.messages++; this.queue = this.queue.then(async () => { if (!this.closed) await this.message(data); }).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; }); } async message(data: unknown) { if (data instanceof ArrayBuffer) { 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.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.metadata.size); this.touch(); return; } 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.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 (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.metadata.size) throw new Error('Incomplete file.'); this.setState('saving'); if (this.writable) await this.writable.close(); if (this.closed) return; // Treat downloads as opaque files, regardless of the sender's MIME claim. const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' }); this.chunks = []; this.control('complete', { bytes: this.received }); this.setState('done'); clearTimeout(this.timer); 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.metadata }); this.close(); return; } throw new Error('Unexpected transfer message.'); } accept(writable: FileDestination | null = null) { if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.'); 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() { 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(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 file.slice(offset, offset + CHUNK_SIZE).arrayBuffer(); if (this.closed) return; this.sent += buffer.byteLength; this.dc.send(buffer); } if (this.closed) return; this.setState('awaiting-receipt'); this.control('end'); this.touch(); } fail(err: unknown) { if (this.closed) return; 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 = []; 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(); } }