Files
HellCon/src/lib/webrtc.ts
T
SchluffeandClaude Opus 5.5 a5935a8324 Remove shareable invitation links
Codes are exchanged by copy and paste again. The URL fragment intake,
the invitation dialog, the BroadcastChannel answer relay and the Share
link / Copy link controls are gone, along with their tests, browser
check scenarios and design doc. Code fields no longer accept links.

The compressed HC1 codes with typed offers/answers and echoed refs stay.
An optional signaling backend is the intended way to simplify the
exchange instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:47:07 +02:00

183 lines
8.8 KiB
TypeScript

import { 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: 'pagequit' | '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.ts encodes the validated descriptions for exchange.
export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024;
export const MAX_SIGNAL_LENGTH = 64 * 1024;
export const STUN_PROVIDERS = [
{ id: 'pagequit', label: 'PageQuit', url: 'stun:stun.pagequit.net:3478' },
{ 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),
};
}
// Each step validates the description it produces or applies.
export async function createOffer(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 pc.localDescription.sdp;
}
export async function createAnswer(pc: RTCPeerConnection, offer: string, options: SignalOptions = {}) {
validateDescription(offer, options);
await pc.setRemoteDescription({ type: 'offer', sdp: offer });
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 pc.localDescription.sdp;
}
export function acceptAnswer(pc: RTCPeerConnection, answer: string, options?: SignalOptions) {
validateDescription(answer, options);
return pc.setRemoteDescription({ type: 'answer', sdp: answer });
}
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();
});
}