Use compressed connection codes in the transfer panel

Offers and answers now go through the HC1 codec: the sender creates a
ref per session and the answer must echo it, so pasting an offer as the
answer or an answer for another code is rejected with a specific message
while the live offer stays usable. Pasted input may be a full link.

webrtc.ts drops its Base64 JSON signaling and exchanges validated SDP
only; identity hellos travel in the code envelope. Tests, the browser
check, compare-ice and the docs follow the new format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-19 22:35:44 +02:00
1 parent da2999ed5d
commit 8bd37ac8b1
10 files changed
+68 -89

No files matched your search

+6
View File
@@ -32,6 +32,12 @@
longer read. longer read.
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers - Upgrade connection/session framing to v3 with per-file identifiers. Both peers
must update; v2 codes are rejected before connection setup. must update; v2 codes are rejected before connection setup.
- Connection codes are compressed to roughly half their length (`HC1.` plus
Base64url of deflated JSON). Each code states whether it is an offer or an
answer and carries a reference shared by both, so a pasted offer in the
answer field, or an answer to a different code, is rejected with a clear
message while the live offer stays valid. Codes may be pasted as part of a
link. Earlier 0.0.5 drafts' codes are rejected.
- New device identity private keys are non-extractable. - New device identity private keys are non-extractable.
- Replace the receive-storage choice with a single **Accept file** button that - Replace the receive-storage choice with a single **Accept file** button that
treats every file size the same: stream to Downloads where supported, else treats every file size the same: stream to Downloads where supported, else
+6 -5
View File
@@ -92,8 +92,9 @@ Keep both tabs open. Switching browser tabs or apps does not explicitly cancel
the session, although browsers and mobile operating systems can suspend pages. the session, although browsers and mobile operating systems can suspend pages.
Pending verification/acceptance expires after five minutes; stalled transfers Pending verification/acceptance expires after five minutes; stalled transfers
expire after one minute. Idle verified sessions stay open. Lost connections need expire after one minute. Idle verified sessions stay open. Lost connections need
fresh codes. File transfers use protocol **v3**; pre-v3 connection codes are fresh codes. File transfers use protocol **v3**; codes from older builds are
rejected before connecting. rejected before connecting. Pasting the wrong kind of code (an offer as answer,
or an answer for a different code) is reported without discarding a live offer.
If an answer is rejected as invalid, correct the pasted answer and click Connect If an answer is rejected as invalid, correct the pasted answer and click Connect
again; the sender keeps its existing offer while it is still awaiting an answer. again; the sender keeps its existing offer while it is still awaiting an answer.
@@ -160,9 +161,9 @@ avoids contacting a configured STUN provider; direct connectivity depends on
addresses, routing, browser policy and firewalls, not simply whether peers share addresses, routing, browser policy and firewalls, not simply whether peers share
one network. A VPN is not automatically a guarantee against address disclosure. one network. A VPN is not automatically a guarantee against address disclosure.
Connection codes are **Base64-encoded, not encrypted**. They contain SDP, Connection codes are **compressed and Base64url-encoded, not encrypted**
including candidate addresses, temporary ICE credentials and certificate (`HC1.` followed by deflated JSON). They contain SDP, including candidate
fingerprints. Peers and anyone who sees these codes (including the messaging addresses, temporary ICE credentials and certificate fingerprints. Peers and anyone who sees these codes (including the messaging
service used to exchange them) may learn connection details. Local addresses may service used to exchange them) may learn connection details. Local addresses may
be obscured by the browser, but this app does not provide anonymity. Treat codes be obscured by the browser, but this app does not provide anonymity. Treat codes
as private session information; do not publish them. as private session information; do not publish them.
+4 -3
View File
@@ -7,9 +7,10 @@ independent cryptographic audit.
## Authentication transcript ## Authentication transcript
A device has an ECDSA P-256 key pair. An identity-enabled connection code uses A device has an ECDSA P-256 key pair. An identity-enabled connection code
signaling envelope version 4 with a public key (65-byte uncompressed point, (see `src/lib/codes.ts` for the `HC1.` encoding) uses signaling envelope
lowercase hex) and a fresh 32-byte cryptographically random nonce. Both local version 4 with a public key (65-byte uncompressed point, lowercase hex) and a
fresh 32-byte cryptographically random nonce. Both local
and remote SDP fingerprints continue to be validated as full SHA-256 values. and remote SDP fingerprints continue to be validated as full SHA-256 values.
Temporary codes use version 3. Old builds reject version 4 before connecting. Temporary codes use version 3. Old builds reject version 4 before connecting.
Current builds accept both; if either participant uses a temporary identity, Current builds accept both; if either participant uses a temporary identity,
+6 -4
View File
@@ -1,6 +1,7 @@
// Dependency-free Chromium integration check. Run after `bun run build`. // Dependency-free Chromium integration check. Run after `bun run build`.
import { Readable, Writable } from 'node:stream'; import { Readable, Writable } from 'node:stream';
import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts'; import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts';
import { CODE_PREFIX, decodeCode } from '../src/lib/codes.ts';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import { createServer } from 'node:http'; import { createServer } from 'node:http';
@@ -144,6 +145,7 @@ async function connect(sender: string, receiver: string, size: number, changedId
if (turn) { await enableTurn(sender); await enableTurn(receiver); } if (turn) { await enableTurn(sender); await enableTurn(receiver); }
await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code')); await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.ok(offer.startsWith(CODE_PREFIX));
await input(receiver, '#offer-input', 'invalid-code!'); await input(receiver, '#offer-input', 'invalid-code!');
await click(receiver, 'Accept & create answer'); await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('[role=alert]')); await wait(receiver, () => !!document.querySelector('[role=alert]'));
@@ -152,8 +154,8 @@ async function connect(sender: string, receiver: string, size: number, changedId
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer'); await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
await wait(receiver, () => !!document.querySelector('#output-code')); await wait(receiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect'); await input(sender, '#answer-input', offer); await click(sender, 'Connect');
await wait(sender, () => !!document.querySelector('[role=alert]')); await wait(sender, () => document.querySelector('[role=alert]')?.textContent?.includes('not an answer'));
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer); assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer);
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false); assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false);
await input(sender, '#answer-input', answer); await click(sender, 'Connect'); await input(sender, '#answer-input', answer); await click(sender, 'Connect');
@@ -517,7 +519,7 @@ try {
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin')); await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code')); await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(JSON.parse(atob(offer)).version, 4); assert.ok((await decodeCode(offer)).identity);
await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer'); await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer');
await wait(identityReceiver, () => !!document.querySelector('#output-code')); await wait(identityReceiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
@@ -621,7 +623,7 @@ try {
await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code'); await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code');
await wait(denied, () => !!document.querySelector('#output-code')); await wait(denied, () => !!document.querySelector('#output-code'));
const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value); const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(JSON.parse(atob(temporary)).version, 3); assert.equal((await decodeCode(temporary)).identity, undefined);
await click(denied, 'Cancel connection'); await click(denied, 'Cancel connection');
console.log('PASS: denied identity storage still allows temporary v3 connection setup.'); console.log('PASS: denied identity storage still allows temporary v3 connection setup.');
+4 -4
View File
@@ -40,8 +40,8 @@ async function run(mode) {
dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); }; dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); };
b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; }; b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; };
try { try {
const offer = await api.createOfferCode(a); // The original helpers exchange encoded codes; current helpers exchange SDP.
let sdp = api.decodeSignal(offer); let sdp = mode === 'original' ? api.decodeSignal(await api.createOfferCode(a)) : await api.createOffer(a);
// Deliberately unusable advertised ports: only sender-initiated checks // Deliberately unusable advertised ports: only sender-initiated checks
// after the answer can discover the real sender. No host firewall changes. // after the answer can discover the real sender. No host firewall changes.
if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{ if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{
@@ -49,11 +49,11 @@ async function run(mode) {
const fields=l.split(' '); fields[5]='9'; return fields.join(' '); const fields=l.split(' '); fields[5]='9'; return fields.join(' ');
}).join('\r\n'); }).join('\r\n');
log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates')); log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates'));
const answer = await api.createAnswerCode(b, api.encodeSignal(sdp)); const answer = mode === 'original' ? await api.createAnswerCode(b, api.encodeSignal(sdp)) : await api.createAnswer(b, sdp);
log('answer ready'); log('answer ready');
await new Promise(r=>setTimeout(r,20000)); await new Promise(r=>setTimeout(r,20000));
log('apply answer'); log('apply answer');
await api.acceptAnswerCode(a,answer); await (mode === 'original' ? api.acceptAnswerCode(a,answer) : api.acceptAnswer(a,answer));
await new Promise(r=>setTimeout(r,12000)); await new Promise(r=>setTimeout(r,12000));
return {mode,received,events}; return {mode,received,events};
} catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; } } catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; }
+17 -9
View File
@@ -6,7 +6,8 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';
import DeviceSettings from './DeviceSettings.vue'; import DeviceSettings from './DeviceSettings.vue';
import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts'; import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts';
import NetworkSettings from './NetworkSettings.vue'; import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, decodeSignal, signalIdentity, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts'; import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.ts';
import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts'; import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts'; import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts'; import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
@@ -25,6 +26,8 @@ interface Session {
identityContext?: IdentityContext; identityContext?: IdentityContext;
identity?: IdentityState['identity']; identity?: IdentityState['identity'];
expected?: string; expected?: string;
// Shared by this session's offer and answer codes.
ref?: string;
timer?: ReturnType<typeof setTimeout>; timer?: ReturnType<typeof setTimeout>;
} }
@@ -289,10 +292,14 @@ async function createCode() {
if (active !== session) return; if (active !== session) return;
session.pc.setConfiguration(iceConfiguration(configured)); session.pc.setConfiguration(iceConfiguration(configured));
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null; managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
if (!props.sending) { decodeSignal(pasted, session.options); session.remoteHello = signalIdentity(pasted); } const offer = props.sending ? null : await decodeCode(pasted, { type: 'offer', allowTurn: session.options.allowTurn });
const options = { ...session.options, signal: session.controller.signal, identity: session.localHello }; if (active !== session) return;
session.ref = offer ? offer.ref : createRef(); session.remoteHello = offer?.identity;
const options = { ...session.options, signal: session.controller.signal };
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3')); if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options); const sdp = offer ? await createAnswer(session.pc, offer.sdp, options) : await createOffer(session.pc, options);
if (active !== session) return;
const code = await encodeCode({ type: props.sending ? 'offer' : 'answer', ref: session.ref, sdp, identity: session.localHello });
if (active !== session) return; if (active !== session) return;
outputCode.value = code; outputCode.value = code;
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready'); session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
@@ -311,9 +318,10 @@ async function useAnswer() {
error.value = ''; error.value = '';
step.value = 'verification'; step.value = 'verification';
try { try {
decodeSignal(inputCode.value, session.options); const answer = await decodeCode(inputCode.value, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
session.remoteHello = signalIdentity(inputCode.value); if (active !== session) return;
await acceptAnswerCode(session.pc, inputCode.value, session.options); session.remoteHello = answer.identity;
await acceptAnswer(session.pc, answer.sdp, session.options);
if (active !== session) return; if (active !== session) return;
session.diagnostics.record('answer applied'); session.diagnostics.record('answer applied');
session.diagnostics.descriptions(); session.diagnostics.descriptions();
@@ -439,7 +447,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p> <p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
<template v-if="!sending"> <template v-if="!sending">
<label class="step" for="offer-input">Paste the sender’s connection code</label> <label class="step" for="offer-input">Paste the sender’s connection code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="busy" /> <textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template> </template>
<button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button> <button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode"> <template v-if="outputCode">
@@ -449,7 +457,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
</template> </template>
<template v-if="sending && outputCode"> <template v-if="sending && outputCode">
<label class="step" for="answer-input">Paste the receiver’s answer</label> <label class="step" for="answer-input">Paste the receiver’s answer</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_SIGNAL_LENGTH" :disabled="step !== 'offer-ready'" /> <textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button> <button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</template> </template>
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p> <p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
+3 -1
View File
@@ -7,6 +7,8 @@ import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrt
// Codes carry connection details, not secrets; fingerprints authenticate peers. // Codes carry connection details, not secrets; fingerprints authenticate peers.
export const CODE_PREFIX = 'HC1.'; export const CODE_PREFIX = 'HC1.';
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH; export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH;
// Pasted text may be a full link around the code.
export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024; const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024;
const INVALID = 'Invalid connection code. Paste the complete code or link.'; const INVALID = 'Invalid connection code. Paste the complete code or link.';
@@ -72,7 +74,7 @@ export async function encodeCode({ type, ref, sdp, identity }: Signal) {
} }
export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise<Signal> { 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.'); if (typeof text !== 'string' || text.length > MAX_INPUT_LENGTH) throw new Error('Connection code is too large.');
const code = codeFromText(text); const code = codeFromText(text);
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.'); if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
if (!code.startsWith(CODE_PREFIX)) { if (!code.startsWith(CODE_PREFIX)) {
+13 -38
View File
@@ -1,5 +1,4 @@
import { parseHello, type IdentityHello } from './identity.ts'; import { isRecord, isStringArray } from './validation.ts';
import { asError, isRecord, isStringArray } from './validation.ts';
export interface IceOptions { export interface IceOptions {
stunUrl?: string | null; stunUrl?: string | null;
@@ -21,13 +20,13 @@ export interface NetworkSettings {
} }
export interface WaitOptions { signal?: AbortSignal; timeout?: number } export interface WaitOptions { signal?: AbortSignal; timeout?: number }
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'> & { identity?: IdentityHello }; type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
export interface Fingerprints { local: string; remote: string } export interface Fingerprints { local: string; remote: string }
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>; export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>; export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>; type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
// Manual signaling. Codes are encoded connection details, not encrypted secrets. // Manual signaling; codes.ts encodes the validated descriptions for exchange.
export const CHUNK_SIZE = 16 * 1024; export const CHUNK_SIZE = 16 * 1024;
export const MAX_BUFFERED = 1024 * 1024; export const MAX_BUFFERED = 1024 * 1024;
export const MAX_SIGNAL_LENGTH = 64 * 1024; export const MAX_SIGNAL_LENGTH = 64 * 1024;
@@ -132,47 +131,28 @@ export function getFingerprints(pc: { localDescription: { sdp: string } | null;
}; };
} }
export function encodeSignal(sdp: string, identity?: IdentityHello) { // Each step validates the description it produces or applies.
const code = btoa(JSON.stringify(identity ? { version: 4, sdp, identity: parseHello(identity) } : { version: 3, sdp })).replace(/=+$/, ''); export async function createOffer(pc: RTCPeerConnection, options: SignalOptions = {}) {
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) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
if (data.version === 4) parseHello(data.identity);
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 pc.setLocalDescription(await pc.createOffer());
await waitForIceComplete(pc, options); await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.'); if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options); validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp, options.identity); return pc.localDescription.sdp;
} }
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) { export async function createAnswer(pc: RTCPeerConnection, offer: string, options: SignalOptions = {}) {
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) }); validateDescription(offer, options);
await pc.setRemoteDescription({ type: 'offer', sdp: offer });
await pc.setLocalDescription(await pc.createAnswer()); await pc.setLocalDescription(await pc.createAnswer());
await waitForIceComplete(pc, options); await waitForIceComplete(pc, options);
if (!pc.localDescription) throw new Error('Missing local connection description.'); if (!pc.localDescription) throw new Error('Missing local connection description.');
validateDescription(pc.localDescription.sdp, options); validateDescription(pc.localDescription.sdp, options);
return encodeSignal(pc.localDescription.sdp, options.identity); return pc.localDescription.sdp;
} }
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) { export function acceptAnswer(pc: RTCPeerConnection, answer: string, options?: SignalOptions) {
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) }); validateDescription(answer, options);
return pc.setRemoteDescription({ type: 'answer', sdp: answer });
} }
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) { export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
@@ -200,8 +180,3 @@ export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 6000
check(); check();
}); });
} }
export function signalIdentity(text: string): IdentityHello | undefined {
const data = JSON.parse(atob(text.trim().replace(/\s+/g, '')));
return data.version === 4 ? parseHello(data.identity) : undefined;
}
+2 -2
View File
@@ -1,7 +1,7 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto'; import { randomBytes } from 'node:crypto';
import { CODE_PREFIX, MAX_CODE_LENGTH, codeFromText, codeLink, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts'; import { CODE_PREFIX, MAX_CODE_LENGTH, MAX_INPUT_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 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 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 identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
@@ -67,7 +67,7 @@ test('malformed, old and unexpected payloads are rejected', async () => {
test('oversized codes and decompression bombs are rejected', async () => { 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(CODE_PREFIX + 'A'.repeat(MAX_CODE_LENGTH)), /too large/);
await assert.rejects(decodeCode('x'.repeat(MAX_CODE_LENGTH * 2 + 1)), /too large/); await assert.rejects(decodeCode('x'.repeat(MAX_INPUT_LENGTH + 1)), /too large/);
// 32 MiB of zeros deflate to about 32 KiB, which fits the code length limit. // 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))); const bomb = CODE_PREFIX + base64url(await deflate(new Uint8Array(32 * 1024 * 1024)));
assert.ok(bomb.length < MAX_CODE_LENGTH); assert.ok(bomb.length < MAX_CODE_LENGTH);
+7 -23
View File
@@ -1,6 +1,6 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { iceConfiguration, validateDescription, getFingerprints, signalIdentity, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts'; import { iceConfiguration, validateDescription, getFingerprints, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts';
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':'); 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 sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
@@ -15,8 +15,8 @@ test('TURN is absent by default and dormant credentials cannot enable it', () =>
test('remote relay candidates require local explicit opt-in', () => { test('remote relay candidates require local explicit opt-in', () => {
const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n'; const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n';
assert.throws(() => decodeSignal(encodeSignal(relayed)), /explicitly enable TURN/); assert.throws(() => validateDescription(relayed), /explicitly enable TURN/);
assert.equal(decodeSignal(encodeSignal(relayed), { allowTurn: true }), relayed); assert.equal(validateDescription(relayed, { allowTurn: true }), validateDescription(sdp));
}); });
test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => { test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
@@ -28,12 +28,10 @@ test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n')); assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n'));
}); });
test('signals round-trip but reject legacy, malformed and oversized codes', () => { test('descriptions are bounded and printable', () => {
assert.equal(decodeSignal(encodeSignal(sdp)), sdp); assert.throws(() => validateDescription(sdp + 'a'.repeat(MAX_SIGNAL_LENGTH)), /Invalid connection description/);
assert.throws(() => decodeSignal(btoa(sdp))); assert.throws(() => validateDescription(sdp + 'a=x:\u00e9\r\n'), /Invalid connection description/);
assert.throws(() => decodeSignal('bad!')); assert.throws(() => validateDescription(42), /Invalid connection description/);
assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1)));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 2, sdp }))));
}); });
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; } class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }
@@ -62,17 +60,3 @@ test('buffer wait resolves when already drained and rejects close or cancellatio
const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort(); const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort();
await assert.rejects(cancelled, /interrupted/); await assert.rejects(cancelled, /interrupted/);
}); });
test('identity signaling is versioned, bounded, and optional for temporary sessions', () => {
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
const code = encodeSignal(sdp, identity);
assert.equal(JSON.parse(atob(code)).version, 4);
assert.equal(decodeSignal(code), sdp);
assert.deepEqual(signalIdentity(code), identity);
assert.equal(signalIdentity(encodeSignal(sdp)), undefined);
assert.equal(JSON.parse(atob(encodeSignal(sdp))).version, 3);
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp, identity: { ...identity, nonce: 'bad' } }))));
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 5, sdp, identity }))));
});