diff --git a/src/lib/codes.ts b/src/lib/codes.ts new file mode 100644 index 0000000..ed9b3a6 --- /dev/null +++ b/src/lib/codes.ts @@ -0,0 +1,102 @@ +import { parseHello, type IdentityHello } from './identity.ts'; +import { asError, isRecord } from './validation.ts'; +import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts'; + +// Connection codes: "HC1." + base64url(deflate-raw(JSON)). The same text works +// pasted or as a link fragment, which browsers never send to the app host. +// Codes carry connection details, not secrets; fingerprints authenticate peers. +export const CODE_PREFIX = 'HC1.'; +export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH; +const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024; +const INVALID = 'Invalid connection code. Paste the complete code or link.'; + +export interface Signal { + type: 'offer' | 'answer'; + // Chosen by the offerer and echoed by the answer, which addresses that offer. + ref: string; + sdp: string; + identity?: IdentityHello; +} +export interface DecodeOptions extends Pick { type?: Signal['type']; ref?: string } + +function toBase64Url(bytes: Uint8Array) { + let binary = ''; + for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} +function fromBase64Url(text: string) { + if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new Error(INVALID); + return Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), char => char.charCodeAt(0)); +} +async function deflate(text: string) { + const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw')); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} +// Stops reading once the output exceeds the limit, so a small hostile code +// cannot expand without bound. +async function inflate(bytes: Uint8Array) { + const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw')).getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.byteLength; + if (length > MAX_PAYLOAD) { void reader.cancel().catch(() => {}); throw new Error('Connection code is too large.'); } + chunks.push(value); + } + const output = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.byteLength; } + return output; +} + +export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); } + +// Accepts a bare code or a full link and returns the code text. +export function codeFromText(text: string) { + return text.slice(text.lastIndexOf('#') + 1).replace(/\s+/g, ''); +} + +export function codeLink(code: string, base: string) { + const url = new URL(base); + url.hash = code; + return url.href; +} + +export async function encodeCode({ type, ref, sdp, identity }: Signal) { + const payload = identity ? { version: 4, type, ref, sdp, identity: parseHello(identity) } : { version: 3, type, ref, sdp }; + const code = CODE_PREFIX + toBase64Url(await deflate(JSON.stringify(payload))); + if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.'); + return code; +} + +export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise { + if (typeof text !== 'string' || text.length > MAX_CODE_LENGTH * 2) throw new Error('Connection code is too large.'); + const code = codeFromText(text); + if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.'); + if (!code.startsWith(CODE_PREFIX)) { + let legacy = false; + try { legacy = isRecord(JSON.parse(atob(code))); } catch { /* not an old code either */ } + throw new Error(legacy ? 'Both people need the current HellCon version.' : INVALID); + } + let data: unknown; + try { + data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await inflate(fromBase64Url(code.slice(CODE_PREFIX.length))))); + } catch (err) { + if (asError(err).message === 'Connection code is too large.') throw err; + throw new Error(INVALID); + } + if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.'); + if ((data.type !== 'offer' && data.type !== 'answer') || typeof data.ref !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(data.ref) || typeof data.sdp !== 'string') { + throw new Error(INVALID); + } + if (data.version === 3 && data.identity !== undefined) throw new Error(INVALID); + const identity = data.version === 4 ? parseHello(data.identity) : undefined; + validateDescription(data.sdp, options); + if (type && data.type !== type) { + throw new Error(type === 'answer' ? 'This is a connection code, not an answer. Paste the answer your peer created.' : 'This is an answer, not a connection code. Paste the code the sender created.'); + } + if (ref !== undefined && data.ref !== ref) throw new Error('This answer belongs to a different connection code. Ask your peer to answer your current code.'); + return { type: data.type, ref: data.ref, sdp: data.sdp, ...(identity ? { identity } : {}) }; +} diff --git a/tests/codes.test.ts b/tests/codes.test.ts new file mode 100644 index 0000000..77547c2 --- /dev/null +++ b/tests/codes.test.ts @@ -0,0 +1,79 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { CODE_PREFIX, MAX_CODE_LENGTH, codeFromText, codeLink, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts'; +const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':'); +const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`; +const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) }; +const ref = createRef(); +const offer: Signal = { type: 'offer', ref, sdp }; +const base64url = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url'); +async function deflate(data: Uint8Array | string) { + return new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer()); +} +const raw = async (payload: unknown) => CODE_PREFIX + base64url(await deflate(JSON.stringify(payload))); + +test('codes round-trip both types, with and without identity', async () => { + assert.match(ref, /^[A-Za-z0-9_-]{22}$/); + assert.notEqual(createRef(), ref); + for (const signal of [offer, { ...offer, type: 'answer' as const }, { ...offer, identity }]) { + const code = await encodeCode(signal); + assert.ok(code.startsWith(CODE_PREFIX)); + assert.match(code.slice(CODE_PREFIX.length), /^[A-Za-z0-9_-]+$/); + assert.deepEqual(await decodeCode(code), signal); + } +}); + +test('links, wrapped text and bare codes decode the same', async () => { + const code = await encodeCode(offer); + const link = codeLink(code, 'https://example.com/apps/hellcon/?x=1#old'); + assert.equal(link, `https://example.com/apps/hellcon/?x=1#${code}`); + assert.equal(codeFromText(link), code); + assert.deepEqual(await decodeCode(link), offer); + assert.deepEqual(await decodeCode(` ${code.slice(0, 20)}\n${code.slice(20)} `), offer); + assert.deepEqual(await decodeCode('#' + code), offer); +}); + +test('expected type and ref are enforced', async () => { + const answer = await encodeCode({ ...offer, type: 'answer' }); + await assert.rejects(decodeCode(await encodeCode(offer), { type: 'answer' }), /not an answer/); + await assert.rejects(decodeCode(answer, { type: 'offer' }), /not a connection code/); + await assert.rejects(decodeCode(answer, { type: 'answer', ref: createRef() }), /different connection code/); + assert.equal((await decodeCode(answer, { type: 'answer', ref })).type, 'answer'); +}); + +test('descriptions are validated, including relay opt-in', async () => { + const relayed = await encodeCode({ ...offer, sdp: sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n' }); + await assert.rejects(decodeCode(relayed), /explicitly enable TURN/); + assert.equal((await decodeCode(relayed, { allowTurn: true })).type, 'offer'); + await assert.rejects(encodeCode({ ...offer, identity: { key: '04', nonce: '' } }), /device identity/); + await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp: 'v=0' })), /data channel/); +}); + +test('malformed, old and unexpected payloads are rejected', async () => { + for (const text of ['', 'bad!', CODE_PREFIX, `${CODE_PREFIX}a`, `${CODE_PREFIX}not+base64`, `${CODE_PREFIX}AAAA`, CODE_PREFIX + base64url(new Uint8Array([0xff, 0xfe]))]) { + await assert.rejects(decodeCode(text), /Invalid connection code/, text); + } + await assert.rejects(decodeCode(btoa(JSON.stringify({ version: 4, sdp }))), /current HellCon version/); + await assert.rejects(decodeCode(await raw({ version: 2, type: 'offer', ref, sdp })), /current HellCon version/); + await assert.rejects(decodeCode(await raw([1])), /current HellCon version/); + await assert.rejects(decodeCode(await raw({ version: 3, type: 'pranswer', ref, sdp })), /Invalid connection code/); + await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref: 'short', sdp })), /Invalid connection code/); + await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp, identity })), /Invalid connection code/); + await assert.rejects(decodeCode(await raw({ version: 4, type: 'offer', ref, sdp })), /device identity/); + await assert.rejects(decodeCode(CODE_PREFIX + base64url(await deflate(new Uint8Array([0x7b, 0xff, 0x7d])))), /Invalid connection code/); + await assert.rejects(decodeCode(42), /too large/); +}); + +test('oversized codes and decompression bombs are rejected', async () => { + await assert.rejects(decodeCode(CODE_PREFIX + 'A'.repeat(MAX_CODE_LENGTH)), /too large/); + await assert.rejects(decodeCode('x'.repeat(MAX_CODE_LENGTH * 2 + 1)), /too large/); + // 32 MiB of zeros deflate to about 32 KiB, which fits the code length limit. + const bomb = CODE_PREFIX + base64url(await deflate(new Uint8Array(32 * 1024 * 1024))); + assert.ok(bomb.length < MAX_CODE_LENGTH); + const started = Date.now(); + await assert.rejects(decodeCode(bomb), /too large/); + assert.ok(Date.now() - started < 2000); + // Base64 text of random bytes stays incompressible enough to exceed the limit. + await assert.rejects(encodeCode({ ...offer, sdp: sdp + 'a=x:' + randomBytes(60000).toString('base64') }), /too large/); +});