Translate everything to typescript
This commit is contained in:
1 parent
c3ca3e1752
commit
e9818aaeda
27 files changed
+901
-552
No files matched your search
@@ -0,0 +1,199 @@
|
||||
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;
|
||||
export const MAX_SIGNAL_LENGTH = 64 * 1024;
|
||||
export const STUN_PROVIDERS = [
|
||||
{ id: 'google', label: 'Google', url: 'stun:stun.l.google.com:19302' },
|
||||
{ id: 'cloudflare', label: 'Cloudflare', url: 'stun:stun.cloudflare.com:3478' },
|
||||
{ id: 'none', label: 'None (direct connections only)', url: null },
|
||||
];
|
||||
|
||||
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 });
|
||||
}
|
||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||
if (allowTurn) {
|
||||
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||
}
|
||||
iceServers.push({ urls: turnUrl, username, credential });
|
||||
}
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
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 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 (!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);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options: IceOptions) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
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?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const aborted = () => finish(new Error('Connection cancelled.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || pc.connectionState === 'closed') aborted();
|
||||
else if (pc.iceGatheringState === 'complete') finish();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
pc.addEventListener('connectionstatechange', check);
|
||||
signal?.addEventListener('abort', aborted, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Connection gathering timed out. Check the server settings and try again.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
const lines = sdp.split(/\r?\n/);
|
||||
const media = lines.filter(line => line.startsWith('m='));
|
||||
if (media.length !== 1 || !/^m=application \d+ (?:UDP\/DTLS\/SCTP|DTLS\/SCTP) (?:webrtc-datachannel|\d+)$/.test(media[0])) {
|
||||
throw new Error('Only a single file data channel is supported.');
|
||||
}
|
||||
// Deliberately reject ambiguous fingerprints rather than guessing SDP scope.
|
||||
const fingerprints = lines.filter(line => line.startsWith('a=fingerprint:'));
|
||||
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
|
||||
throw new Error('A single full SHA-256 fingerprint is required.');
|
||||
}
|
||||
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
|
||||
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
|
||||
}
|
||||
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
|
||||
}
|
||||
|
||||
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: 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: 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: 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 || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
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: 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: RTCPeerConnection, text: string, options?: SignalOptions) {
|
||||
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
|
||||
}
|
||||
|
||||
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);
|
||||
dc.removeEventListener('close', check);
|
||||
dc.removeEventListener('error', failed);
|
||||
signal?.removeEventListener('abort', failed);
|
||||
};
|
||||
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();
|
||||
else if (dc.bufferedAmount <= MAX_BUFFERED / 2) finish();
|
||||
};
|
||||
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
dc.addEventListener('bufferedamountlow', check);
|
||||
dc.addEventListener('close', check);
|
||||
dc.addEventListener('error', failed);
|
||||
signal?.addEventListener('abort', failed, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Transfer stalled.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user