Add compressed connection code codec

Codes become "HC1." plus base64url of deflate-raw JSON with an
offer/answer type and a ref the answer echoes. Decoding accepts bare
codes or full links, validates identity and description, enforces the
expected type and ref, and bounds both input and decompressed output.
Not wired into the app yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-19 22:29:20 +02:00
1 parent 4cf2ff5211
commit da2999ed5d
2 files changed
+181

No files matched your search

+102
View File
@@ -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<IceOptions, 'allowTurn'> { 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<ArrayBuffer>) {
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<Signal> {
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 } : {}) };
}