Translate everything to typescript

This commit is contained in:
Schluffe committed 2026-10-09 14:17:36 +02:00
1 parent c3ca3e1752
commit e9818aaeda
27 files changed
+901 -552

No files matched your search

+103 -31
View File
@@ -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();
}
+11
View File
@@ -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);
}
+67 -28
View File
@@ -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();