Seal tracker signaling with the code

The SDP relayed by the trackers is now encrypted with AES-GCM under a key derived from the code,
next to the swarm ID and the proof key. Trackers and peers that found the swarm without the code
no longer learn either side's addresses, and an offer or answer that doesn't decrypt is dropped
before any peer connection exists, so it can't take the sender's turn. The proof stays as a
second layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-25 13:52:32 +01:00
1 parent 338d4d2532
commit bb69569b51
3 files changed
+240 -72

No files matched your search

+172 -45
View File
@@ -1,4 +1,4 @@
import { createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
import { createCipheriv, createDecipheriv, 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';
@@ -191,15 +191,16 @@ function trackPeers() {
};
}
// The page's peer connections that aren't closed. The app's own check of the STUN servers closes its own.
const openPeers = (page: Page) =>
page.evaluate(
() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
);
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
async function expectClosed(page: Page) {
const peers = () =>
page.evaluate(
() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed')
.length,
);
await expect.poll(peers).toBe(0);
await expect.poll(() => openPeers(page)).toBe(0);
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
}
@@ -637,9 +638,10 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// The proofs are genuine, made with the right key, only the fingerprints they cover give the man in
// the middle away. Whoever verifies first ends its connection, the other side may never get the
// proof then, but neither passes.
// Sealing keeps a man in the middle without the code out (see the next test), the proofs hold even
// against one that opens and seals the signaling. They are genuine, made with the right key, only
// the fingerprints they cover give the man in the middle away. Whoever verifies first ends its
// connection, the other side may never get the proof then, but neither passes.
test(`check: ${name} both sides reject a man in the middle that relays the proofs`, async () => {
const [sender, receiver, middle] = await Promise.all([open(name), open(name), open(name, { init: middleman })]);
const [toSender, toReceiver] = await Promise.all([announces(sender), announces(receiver)]);
@@ -648,9 +650,10 @@ for (const name of Object.keys(BROWSERS)) {
for (const page of [sender, receiver]) await page.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
const code = (await sender.locator('#send-code').textContent())!;
await receiver.fill('#receive-code', code);
await receiver.click('#receive');
await interpose(middle, toSender, toReceiver);
await interpose(middle, code, toSender, toReceiver);
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 15_000 });
await expect(receiver.locator('#log')).toContainText('looking again', { timeout: 15_000 });
@@ -674,7 +677,7 @@ for (const name of Object.keys(BROWSERS)) {
await sender.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
await interpose(middle, toSender);
await interpose(middle, (await sender.locator('#send-code').textContent())!, toSender);
await expect(sender.locator('#log')).toContainText('security check failed, the peer does not know the code', {
timeout: 15_000,
@@ -685,6 +688,48 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// A tracker sees all signaling, without the code it can read none of it nor get anything answered:
// not a well-formed SDP of its own, not the receiver's sealed offer passed off as an answer.
test(`check: ${name} a man in the middle without the code learns no address and connects nobody`, async () => {
const [sender, receiver, middle] = await Promise.all([open(name), open(name), open(name, { init: middleman })]);
const [toSender, toReceiver] = await Promise.all([announces(sender), announces(receiver)]);
const binary = () => randomBytes(20).toString('latin1');
await withLogs(sender, receiver, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
await receiver.click('#receive');
const { msg, ws } = await first(toReceiver, (msg) => msg.offers);
const [{ offer, offer_id }] = msg.offers;
expect(offer.sdp).not.toContain('a=fingerprint');
expect(offer.sdp).not.toContain('candidate');
type Hosting = { middle: Middle };
const own = await middle.evaluate(() => (window as unknown as Hosting).middle.offer(true));
const answer = await middle.evaluate((sdp) => (window as unknown as Hosting).middle.answer(sdp), own);
for (const sdp of [answer, offer.sdp]) {
const reply = {
action: 'announce',
info_hash: msg.info_hash,
peer_id: binary(),
offer_id,
answer: { type: 'answer', sdp },
};
ws.send(JSON.stringify(reply));
}
const started = await first(toSender, (msg) => msg.event === 'started');
const forged = { action: 'announce', info_hash: started.msg.info_hash, peer_id: binary(), offer_id: binary() };
started.ws.send(JSON.stringify({ ...forged, offer: { type: 'offer', sdp: own } }));
await expect.poll(async () => (await log(receiver))!.match(/answer without the code/g)?.length ?? 0).toBe(2);
await expect(sender.locator('#log')).toContainText('offer without the code');
expect(await log(receiver)).not.toContain('answer via');
expect(toSender.some(({ msg }) => msg.answer)).toBe(false);
expect(await openPeers(sender)).toBe(0);
});
});
test(`protocol: ${name} receiver refuses an offer that isn't a file`, async () => {
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
const source = await payload(randomBytes(SIZE));
@@ -818,7 +863,7 @@ for (const name of Object.keys(BROWSERS)) {
});
// Anyone with the code can send offers no browser can parse, as many as they like. The share lets
// go of each one's connection and keeps using the tracker.
// go of each one's connection and keeps using the tracker. Without the code they get no connection.
test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
const sender = await open(name, { init: countAbortListeners });
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
@@ -829,13 +874,17 @@ for (const name of Object.keys(BROWSERS)) {
await withLogs(sender, sender, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
const code = (await sender.locator('#send-code').textContent())!;
await expect.poll(() => trackers.sockets.length).toBe(2);
for (let offers = 1; offers <= 25; offers++) {
trackers.sockets[0]!.send(garbageOffer());
trackers.sockets[0]!.send(garbageOffer(code));
await expect.poll(unusable).toBe(offers);
// Once it accepted the announcement, a failure only concerns that one message.
if (offers === 1) trackers.sockets[0]!.send(JSON.stringify({ 'failure reason': 'slow down' }));
}
for (let offers = 0; offers < 5; offers++) trackers.sockets[1]!.send(garbageOffer());
await expect.poll(async () => (await log(sender))!.match(/offer without the code/g)?.length ?? 0).toBe(5);
expect(await unusable()).toBe(25);
await expect(sender.locator('#log')).toContainText(': slow down');
await expect(sender.locator('#log')).not.toContainText('rejected by');
await expect(sender.locator('#send-error')).toHaveCount(0);
@@ -938,8 +987,37 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// 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.
// Opening an offer takes a moment, the share may expire meanwhile. Expired is expired, that offer
// gets no turn either.
test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => {
const sender = await open(name, { init: holdDecrypts });
await sender.clock.install();
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
const decrypts = () =>
sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts);
await withLogs(sender, sender, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
const code = (await sender.locator('#send-code').textContent())!;
await expect.poll(() => trackers.sockets.length).toBe(2);
trackers.sockets[0]!.send(garbageOffer(code));
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
await sender.clock.fastForward('06:00');
await expect(sender.locator('#send-error')).toHaveText(
'nobody received the file within 6 minutes, share it again',
);
await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts());
// The handler goes on right after the decryption, before anything else the page does.
await expect.poll(decrypts).toEqual({ held: 0, done: 1 });
expect(await log(sender)).not.toContain('offer via');
await expectClosed(sender);
});
});
// A peer that found the swarm without the code, here one that announces another code on the
// sender's info_hash. Its offer isn't sealed with the code, the sender doesn't even answer it.
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));
@@ -952,14 +1030,10 @@ for (const name of Object.keys(BROWSERS)) {
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 expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 });
await intruder.context().close();
expect(await log(sender)).not.toContain('offered');
expect(await log(sender)).not.toContain('connected');
expect(await openPeers(sender)).toBe(0);
await receiver.fill('#receive-code', code);
await receiver.click('#receive');
@@ -1110,13 +1184,16 @@ async function announces(page: Page) {
return announced;
}
// The first announcement that matches, once there is one.
async function first(announced: Announce[], match: (msg: Announce['msg']) => unknown) {
await expect.poll(() => announced.some(({ msg }) => match(msg))).toBe(true);
return announced.find(({ msg }) => match(msg))!;
}
// Puts the middleman page between the sender and the receiver on their mocked trackers, as a tracker
// could. Without a receiver it reflects, see middleman.
async function interpose(middle: Page, toSender: Announce[], toReceiver?: Announce[]) {
const first = async (announced: Announce[], match: (msg: Announce['msg']) => unknown) => {
await expect.poll(() => announced.some(({ msg }) => match(msg))).toBe(true);
return announced.find(({ msg }) => match(msg))!;
};
// that knows the code could: it opens and seals the signaling, only the proofs can give it away.
// Without a receiver it reflects, see middleman.
async function interpose(middle: Page, code: string, toSender: Announce[], toReceiver?: Announce[]) {
const binary = () => randomBytes(20).toString('latin1');
const peerId = binary();
type Hosting = { middle: Middle };
@@ -1124,25 +1201,49 @@ async function interpose(middle: Page, toSender: Announce[], toReceiver?: Announ
if (toReceiver) {
const { msg, ws } = await first(toReceiver, (msg) => msg.offers);
const [{ offer, offer_id }] = msg.offers;
const sdp = await middle.evaluate((sdp) => (window as unknown as Hosting).middle.answer(sdp), offer.sdp);
const answer = { type: 'answer', sdp };
const sdp = await middle.evaluate(
(sdp) => (window as unknown as Hosting).middle.answer(sdp),
unseal(code, 'offer', offer.sdp),
);
const answer = { type: 'answer', sdp: seal(code, 'answer', sdp) };
ws.send(JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id, answer }));
}
const { msg, ws } = await first(toSender, (msg) => msg.event === 'started');
const sdp = await middle.evaluate((reflect) => (window as unknown as Hosting).middle.offer(reflect), !toReceiver);
const offer = { type: 'offer', sdp };
const offer = { type: 'offer', sdp: seal(code, 'offer', sdp) };
ws.send(JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id: binary(), offer }));
const { msg: reply } = await first(toSender, (msg) => msg.answer);
await middle.evaluate((sdp) => (window as unknown as Hosting).middle.accept(sdp), reply.answer.sdp);
await middle.evaluate(
(sdp) => (window as unknown as Hosting).middle.accept(sdp),
unseal(code, 'answer', reply.answer.sdp),
);
}
// 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 secrets in src/core.ts derives from the code for info, PBKDF2 once per code.
const masters = new Map<string, Buffer>();
function secret(code: string, info: string, length: number) {
if (!masters.has(code)) masters.set(code, pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'));
return Buffer.from(hkdfSync('sha256', masters.get(code)!, '', info, length));
}
// What a broken or hostile receiver could announce for the code: an offer no browser can parse.
// The code's info_hash.
const swarm = (code: string) => secret(code, 'swarm', 20).toString('latin1');
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code.
function seal(code: string, type: 'offer' | 'answer', sdp: string) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', secret(code, 'signaling', 32), iv).setAAD(Buffer.from(type));
return Buffer.concat([iv, cipher.update(sdp), cipher.final(), cipher.getAuthTag()]).toString('base64');
}
function unseal(code: string, type: 'offer' | 'answer', sealed: string) {
const bytes = Buffer.from(sealed, 'base64');
const decipher = createDecipheriv('aes-256-gcm', secret(code, 'signaling', 32), bytes.subarray(0, 12));
decipher.setAAD(Buffer.from(type)).setAuthTag(bytes.subarray(-16));
return Buffer.concat([decipher.update(bytes.subarray(12, -16)), decipher.final()]).toString();
}
// What a broken or hostile receiver could announce with the code: an offer no browser can parse.
async function announceGarbage(code: string) {
const ws = new WebSocket(TRACKER);
await new Promise((resolve, reject) => {
@@ -1160,7 +1261,7 @@ async function announceGarbage(code: string) {
downloaded: 0,
left: 1,
event: 'started',
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: 'garbage' } }],
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: seal(code, 'offer', 'garbage') } }],
}),
);
return ws;
@@ -1180,13 +1281,13 @@ async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>, ws
return trackers;
}
// What a tracker relays from a receiver: an offer no browser can parse.
const garbageOffer = () =>
// What a tracker relays from a receiver: an offer no browser can parse, sealed with code if given.
const garbageOffer = (code?: string) =>
JSON.stringify({
action: 'announce',
peer_id: randomBytes(20).toString('latin1'),
offer_id: randomBytes(20).toString('latin1'),
offer: { type: 'offer', sdp: 'garbage' },
offer: { type: 'offer', sdp: code ? seal(code, 'offer', 'garbage') : 'garbage' },
});
// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal
@@ -1208,6 +1309,32 @@ function countAbortListeners() {
(window as unknown as { abortListeners: () => number }).abortListeners = () => listeners.size;
}
// Init script: holds every decryption back until window.releaseDecrypts(), as if it took that long.
// window.decrypts counts those held and those done. It runs in the hidden frames too, only the app's
// own window counts.
function holdDecrypts() {
if (window !== window.top) return;
const decrypts = { held: 0, done: 0 };
const waiting: (() => void)[] = [];
const decrypt = crypto.subtle.decrypt.bind(crypto.subtle);
crypto.subtle.decrypt = (...args) =>
new Promise((resolve, reject) => {
decrypts.held++;
waiting.push(() =>
decrypt(...args).then((result) => {
decrypts.done++;
resolve(result);
}, reject),
);
});
const page = window as unknown as { decrypts: typeof decrypts; releaseDecrypts: () => void };
page.decrypts = decrypts;
page.releaseDecrypts = () => {
decrypts.held = 0;
for (const release of waiting.splice(0)) release();
};
}
// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry.
// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own
// window counts.