Let the code prove tracker connections instead of the user

Both sides derive an HMAC key from the code, next to the swarm ID, and sign
their role and both DTLS fingerprints as they see them. An interposer or a
peer that found the swarm without the code can't, so its connection ends and
the next peer gets its turn, as does one that proves nothing within 10 s.
Tracker transfers need no comparing and no clicks anymore, the manual
exchange keeps its fingerprint check. The swarm ID changes once more, old and
new clients don't find each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-25 13:05:58 +01:00
1 parent 707248f36b
commit c6145b8919
4 files changed
+193 -89

No files matched your search

+14 -6
View File
@@ -6,10 +6,10 @@ size limit: the file goes directly to the other person and is never stored on a
## How to send a file
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
an 8 character code. Tell it to the receiver, it works for 6 minutes.
an 8 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
get the file, so give it to nobody else.
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
3. **Both:** compare the security check (see below) and click **Codes match**.
4. **Receiver:** you now see the file's name and size. Click **Download** to save it.
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
tab was doing.
@@ -20,12 +20,20 @@ If you'd rather not use a tracker, open **Manual** on both sides. The sender cre
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
**Connect**. The offer and answer contain your network addresses, so only share them with the person
you're sending to.
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
## The security check
Once connected, both sides see two short codes: **You** and **Peer**. Compare them with the other
person over a channel you already trust, ideally a call or in person:
Before anything is transferred, both sides make sure they are connected directly to each other and
not to someone who placed themselves in between.
With the code this happens by itself: each side proves to the other that it knows the code, tied
to the encryption keys of this very connection. Someone in between, or anyone else who doesn't
know the code, can't do that, and HellCon drops the connection and waits for the right one.
The manual exchange has no code, so there you compare yourselves. Once connected, both sides see two
short codes: **You** and **Peer**. Compare them with the other person over a channel you already
trust, ideally a call or in person:
- your **You** must be their **Peer**, and
- your **Peer** must be their **You**.
-5
View File
@@ -57,11 +57,6 @@
## Ideas
- Let the code confirm the connection instead of the user: both sides derive a second key from the
code and send an HMAC over both DTLS fingerprints. An interposer without the code can't forge it,
so the manual comparison and a careless confirm would no longer matter. Changes the protocol and
the check UI, WebCrypto is enough.
- Resume interrupted transfers: the receiver already reports how much the download manager has
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
finished or failed download though, so a resume would have to start a new one.
+91 -53
View File
@@ -1,4 +1,4 @@
import { createHash, pbkdf2Sync, randomBytes } from 'node:crypto';
import { createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
import { createSocket, type Socket } from 'node:dgram';
import { createReadStream } from 'node:fs';
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
@@ -28,9 +28,10 @@ const SIZE = 5_000_000;
const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test cancels or disconnects.
const RUNNING_SIZE = 100_000_000;
// WINDOW, CHUNK_SIZE and ICE_TIMEOUT in src/core.ts.
// WINDOW, CHUNK_SIZE, ICE_TIMEOUT and PROOF_TIMEOUT in src/core.ts.
const WINDOW = 8 * 2 ** 20;
const ICE_TIMEOUT = 5000;
const PROOF_TIMEOUT = 10_000;
// Enough for a transfer whose receiver holds back its reads to pause at the window.
const HELD_SIZE = 3 * WINDOW;
// What the fake STUN server reports as public address, reserved for documentation.
@@ -301,10 +302,12 @@ async function withLogs(sender: Page, receiver: Page, fn: () => Promise<void>) {
}
}
// Connects and verifies that both sides show the same security check, swapped.
// Connects and verifies that both sides show the same security check, swapped. Over a tracker the
// code proves the connection, nobody sees one.
async function connect(mode: string, sender: Page, receiver: Page, source: string) {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
if (mode === 'tracker') return proven(sender, receiver);
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, {
@@ -324,14 +327,24 @@ const downloadStarts = (receiver: Page) =>
.waitForEvent('download', { timeout: test.info().timeout })
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
// Connects, confirms the security check on both sides and starts the download.
// Both sides passed the security check of tracker signaling, without showing one.
async function proven(sender: Page, receiver: Page) {
for (const page of [sender, receiver]) {
await expect(page.locator('#log')).toContainText('security check passed', { timeout: 45_000 });
await expect(page.locator('#check-local')).toHaveCount(0);
}
}
// Connects, confirms the security check on both sides unless the code proved it, and starts the download.
async function start(mode: string, sender: Page, receiver: Page, source: string) {
await connect(mode, sender, receiver, source);
const started = downloadStarts(receiver);
await sender.click('#confirm');
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#confirm');
if (mode !== 'tracker') {
await sender.click('#confirm');
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#confirm');
}
// Offered, but nothing is sent before the user asks for it.
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
@@ -697,10 +710,8 @@ for (const name of Object.keys(BROWSERS)) {
await receiver.fill('#receive-code', code);
await receiver.click('#receive');
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
await proven(sender, receiver);
const started = downloadStarts(receiver);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source));
@@ -717,7 +728,7 @@ for (const name of Object.keys(BROWSERS)) {
await withLogs(sender, receiver, async () => {
await sender.setInputFiles('input[type=file]', source);
await MODES.tracker!(sender, receiver);
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
await proven(sender, receiver);
await Promise.all([sender, receiver].map((page) => page.clock.fastForward('06:00')));
for (const page of [sender, receiver]) {
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
@@ -725,8 +736,6 @@ for (const name of Object.keys(BROWSERS)) {
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
const started = downloadStarts(receiver);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source));
@@ -881,26 +890,33 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
test(`live check: ${name} sender shares on after a mismatch`, async () => {
// A peer that found the swarm without the code takes the sender's turn first: here one that
// announces another code on the sender's info_hash. Neither side can prove anything to the other.
test(`live check: ${name} sender shares on after a peer without the code`, async () => {
const [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
const source = await payload(randomBytes(SIZE));
await withLogs(sender, receiver, async () => {
await connect('tracker', sender, intruder, source);
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
await receiver.click('#receive');
await expect(receiver.locator('#log')).toContainText('looking on');
await sender.click('#reject');
await sender.setInputFiles('input[type=file]', source);
await sender.click('#share');
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
const code = (await sender.locator('#send-code').textContent())!;
await intrude(intruder, swarm(code));
await intruder.fill('#receive-code', 'notthecode');
await intruder.click('#receive');
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 45_000 });
// Whoever verifies first closes the connection, the other side may only see the peer leave.
await expect
.poll(async () => `${await log(sender)}${await log(intruder)}`)
.toContain('security check failed, the peer does not know the code');
for (const page of [sender, intruder]) await expect(page.locator('#check-local')).toHaveCount(0);
await intruder.context().close();
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
expect(await log(sender)).not.toContain('offered');
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
await expect(sender.locator('#check-local')).toHaveText((await receiver.locator('#check-remote').textContent())!);
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
await receiver.fill('#receive-code', code);
await receiver.click('#receive');
await proven(sender, receiver);
const started = downloadStarts(receiver);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source));
@@ -908,34 +924,22 @@ for (const name of Object.keys(BROWSERS)) {
});
});
test(`live check: ${name} both sides go on after the receiver rejected`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]);
await sender.clock.install();
const source = await payload(randomBytes(SIZE));
await withLogs(sender, receiver, async () => {
await connect('tracker', sender, receiver, source);
const first = await receiver.locator('#check-local').textContent();
// Retrying still has to work for a side that already confirmed.
await sender.click('#confirm');
await receiver.click('#reject');
await expect(receiver.locator('#log')).toContainText('looking again');
// The sender notices the receiver left, Chromium only once the connection counts as failed.
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
await expect(receiver.locator('#check-local')).toHaveText(
new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`),
{
timeout: 45_000,
},
);
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
const started = downloadStarts(receiver);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source));
await expect(sender.locator('#log')).toContainText('delivered');
await sender.setInputFiles('input[type=file]', source);
await MODES.tracker!(sender, receiver);
// The sender's proof still reaches the receiver.
await expect(receiver.locator('#log')).toContainText('security check passed', { timeout: 45_000 });
await expect(sender.locator('#log')).toContainText('waiting for the security check');
await sender.clock.fastForward(PROOF_TIMEOUT);
await expect(sender.locator('#log')).toContainText('the peer proved no code');
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
expect(await log(sender)).not.toContain('offered');
await expect(sender.locator('#send-error')).toHaveCount(0);
});
});
@@ -957,6 +961,40 @@ for (const name of Object.keys(BROWSERS)) {
});
}
// Makes the page a tracker intruder: it announces its offers on the info_hash hash instead of its own,
// on TRACKER only and just the first offer. A later one could still take the sender's turn after the
// test closed the page.
async function intrude(page: Page, hash: string) {
let offered = false;
await page.routeWebSocket(/^wss:/, (ws) => {
if (!ws.url().startsWith(TRACKER)) return ws.close();
const server = ws.connectToServer();
ws.onMessage((data) => {
const msg = JSON.parse(String(data));
if (msg.offers && offered) return;
offered ||= !!msg.offers;
server.send(JSON.stringify({ ...msg, info_hash: hash }));
});
});
}
// Init script: the page never sends a proof of the code, everything else as usual. It runs in the
// hidden frames too, only the app's own window counts.
function withholdProof() {
if (window !== window.top) return;
const send = RTCDataChannel.prototype.send as (this: RTCDataChannel, data: unknown) => void;
RTCDataChannel.prototype.send = function (this: RTCDataChannel, data: unknown) {
if (typeof data === 'string' && data.includes('"proof"')) return;
send.call(this, data);
};
}
// The code's info_hash, derived like secrets in src/core.ts.
const swarm = (code: string) =>
Buffer.from(hkdfSync('sha256', pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'), '', 'swarm', 20)).toString(
'latin1',
);
// What a broken or hostile receiver could announce for the code: an offer no browser can parse.
async function announceGarbage(code: string) {
const ws = new WebSocket(TRACKER);
@@ -968,7 +1006,7 @@ async function announceGarbage(code: string) {
ws.send(
JSON.stringify({
action: 'announce',
info_hash: binary(pbkdf2Sync(code, 'hellcon', 600_000, 20, 'sha256')),
info_hash: swarm(code),
peer_id: binary(randomBytes(20)),
numwant: 1,
uploaded: 0,
+88 -25
View File
@@ -35,6 +35,9 @@ export const TRACKER_WAIT = 6 * 60_000;
const MIN_INTERVAL = 30_000;
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
const PBKDF2_ITERATIONS = 600_000;
// A tracker peer that connects but proves no code gives up its turn after this. Signing takes
// milliseconds, a peer that knows the code is never near it.
const PROOF_TIMEOUT = 10_000;
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
const MAX_NAME = 1024;
@@ -50,7 +53,8 @@ export type Events = {
log: (message: string) => void;
// Something the user has to act on, the session can't go on by itself. Not logged separately.
error: (message: string) => void;
// Called on both sides once connected, and without a check when it ended undecided.
// Called on both sides once connected by the manual exchange, and without a check when it ended
// undecided. Tracker signaling has the code to prove the connection, nobody has to compare anything.
check: (check?: Check) => void;
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
// the transfer starts.
@@ -143,19 +147,28 @@ function randomCode() {
return code;
}
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code. Whoever sees
// the swarms, a tracker or anyone scraping one, can test a guessed code against all of them at once.
// PBKDF2 makes every guess cost what a share pays once (~50 ms), so a GPU gets through a vanishing
// part of the 62⁸ codes within TRACKER_WAIT. The salt is fixed, both sides only know the code.
async function infoHash(code: string) {
// The code is all both sides share. It gives the tracker swarm, identified by a 20 byte info_hash,
// and the key that proves the connection, see prove. Whoever sees the swarms, a tracker or anyone
// scraping one, can test a guessed code against all of them at once. PBKDF2 makes every guess cost
// what a share pays once (~50 ms), so a GPU gets through a vanishing part of the 62⁸ codes within
// TRACKER_WAIT. The salt is fixed, both sides only know the code. HKDF splits the result, the public
// info_hash tells nothing about the key.
async function secrets(code: string) {
const text = new TextEncoder();
const key = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', hash: 'SHA-256', salt: text.encode('hellcon'), iterations: PBKDF2_ITERATIONS },
key,
160,
password,
256,
);
return String.fromCharCode(...new Uint8Array(bits));
const master = await crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']);
const expand = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: text.encode(info) });
const hash = await crypto.subtle.deriveBits(expand('swarm'), master, 160);
const key = await crypto.subtle.deriveKey(expand('proof'), master, { name: 'HMAC', hash: 'SHA-256' }, false, [
'sign',
'verify',
]);
return { hash: String.fromCharCode(...new Uint8Array(hash)), key };
}
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
@@ -206,11 +219,58 @@ function securityCheck(pc: RTCPeerConnection) {
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
}
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
// needs both confirmations, a rejected check, a peer that left or end closes the connection and calls
// next: tracker signaling goes on with another peer. Without next, as in the manual exchange, the
// session is over and the reason is an error. From start on, sendFile and receiveFile handle a loss.
// Every fingerprint the SDP names, in full: one added beside the real one changes the result too.
// Browsers may move them between session and media level, so each counts once.
const fingerprints = (sdp: string) =>
[...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort();
// The security check of tracker signaling, resolves once the peer proved the code. Each side signs its
// role, its SDP type, and the fingerprints of both certificates as it sees them. The peer checks that
// against its own view. An interposer has its own certificate towards each side and can't sign for it
// without the code, neither can a peer that found the swarm some other way. One that sends no proof
// within PROOF_TIMEOUT or a wrong one ends the connection.
function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
const local = pc.localDescription!;
const remote = pc.remoteDescription!;
const statement = (type: string, own: string, peer: string) =>
new TextEncoder().encode(JSON.stringify([type, fingerprints(own), fingerprints(peer)]));
const send = async () => {
const proof = await crypto.subtle.sign('HMAC', key, statement(local.type, local.sdp, remote.sdp));
if (channel.readyState !== 'open') return;
channel.send(JSON.stringify({ proof: btoa(String.fromCharCode(...new Uint8Array(proof))) }));
};
if (channel.readyState === 'open') void send();
else channel.addEventListener('open', () => void send(), { once: true });
return new Promise<void>((resolve) => {
const timeout = setTimeout(() => end('the peer proved no code'), PROOF_TIMEOUT);
const check = async (event: MessageEvent) => {
const proof = parse(event.data)?.proof;
if (typeof proof !== 'string') return;
// Registered before sendFile and receiveFile, which must not see it: Chromium can verify before
// the next listener runs, the receiver would take the proof for the sender's offer then.
event.stopImmediatePropagation();
channel.removeEventListener('message', check);
clearTimeout(timeout);
// atob throws on what isn't base64.
let valid = false;
try {
const signature = Uint8Array.from(atob(proof), (char) => char.charCodeAt(0));
valid = await crypto.subtle.verify('HMAC', key, signature, statement(remote.type, remote.sdp, local.sdp));
} catch {}
if (valid) resolve();
else end('security check failed, the peer does not know the code');
};
channel.addEventListener('message', check);
});
}
// checked resolves once the security check passed: by the user confirming the codes, or with a key
// once the peer proved the code. Both sides wait for it: the sender sends nothing to a man in the
// middle, the receiver accepts no file from one. Until the transfer starts, which needs both sides to
// pass, a failed check, a peer that left or end closes the connection and calls next: tracker
// signaling goes on with another peer. Without next, as in the manual exchange, the session is over
// and the reason is an error. From start on, sendFile and receiveFile handle a loss.
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
function connected(
@@ -219,6 +279,7 @@ function connected(
via: string,
events: Events,
next?: () => void,
key?: CryptoKey,
): Handshake {
events.log(`connected via ${via}`);
events.log('waiting for the security check');
@@ -238,9 +299,11 @@ function connected(
if (pc.connectionState === 'failed') end('peer left before the transfer');
});
return {
checked: new Promise((resolve) =>
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
),
checked: key
? prove(pc, channel, key, end).then(() => events.log('security check passed'))
: new Promise((resolve) =>
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
),
start: () => (done = true),
end,
};
@@ -663,14 +726,14 @@ function noTracker(trackers: (Tracker | undefined)[]) {
}
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
// the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be
// answered or never connects. Once the download started the share is used up, the trackers go. After
// time. Until a receiver proved the code, the next one gets its turn: a peer that found the swarm
// without it doesn't end the share. Neither does an offer that can't be answered, never connects or
// proves nothing. Once the download started the share is used up, the trackers go. After
// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn.
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
events = live(events, signal);
const code = randomCode();
const hash = await infoHash(code);
const { hash, key } = await secrets(code);
const peerId = randomBinary(20);
const trackers: Tracker[] = [];
let busy = false;
@@ -726,7 +789,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
if (settled) return;
settled = true;
clearTimeout(timeout);
const handshake = connected(pc, channel, url, events, next);
const handshake = connected(pc, channel, url, events, next, key);
const start = () => {
handshake.start();
shared = true;
@@ -789,7 +852,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
events = live(events, signal);
await downloadsReady();
const hash = await infoHash(code.trim());
const { hash, key } = await secrets(code.trim());
if (signal.aborted) return;
const peerId = randomBinary(20);
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
@@ -843,7 +906,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
clearTimeout(timeout);
if (isConnected || started) return pc.close();
isConnected = true;
const handshake = connected(pc, channel, url, events, next);
const handshake = connected(pc, channel, url, events, next, key);
const start = () => {
handshake.start();
started = true;