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
+238 -70

No files matched your search

+5 -2
View File
@@ -52,7 +52,9 @@ the browsers need two things:
- **Finding each other.** The code puts both browsers into the same group on a public - **Finding each other.** The code puts both browsers into the same group on a public
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and [WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
forth. It never sees the file. With the manual exchange you play the tracker yourself. forth. They are encrypted with the code, so the tracker can't read them, and neither can anyone
else in the group without the code. It never sees the file. With the manual exchange you play the
tracker yourself.
- **Reaching each other.** Most devices sit behind a router and don't know their public address. - **Reaching each other.** Most devices sit behind a router and don't know their public address.
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
only on the same network or over a VPN. only on the same network or over a VPN.
@@ -68,7 +70,8 @@ networks, a direct connection may not be possible.
- The file only goes to the person you connected with. - The file only goes to the person you connected with.
- That person learns your IP address, as with any direct connection. The tracker and the STUN - That person learns your IP address, as with any direct connection. The tracker and the STUN
servers see it too. servers see it too, from the request itself. Nobody without the code learns it through the
tracker.
- Settings (STUN on or off, your server lists) are kept in your browser only. - Settings (STUN on or off, your server lists) are kept in your browser only.
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that, - Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
host your own (below). host your own (below).
+170 -43
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 { createSocket, type Socket } from 'node:dgram';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
import { open as openFile, readFile, writeFile } from 'node:fs/promises'; import { open as openFile, readFile, writeFile } from 'node:fs/promises';
@@ -191,15 +191,16 @@ function trackPeers() {
}; };
} }
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets. // The page's peer connections that aren't closed. The app's own check of the STUN servers closes its own.
async function expectClosed(page: Page) { const openPeers = (page: Page) =>
const peers = () =>
page.evaluate( page.evaluate(
() => () =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed') (window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
.length,
); );
await expect.poll(peers).toBe(0);
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
async function expectClosed(page: Page) {
await expect.poll(() => openPeers(page)).toBe(0);
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).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 // Sealing keeps a man in the middle without the code out (see the next test), the proofs hold even
// the middle away. Whoever verifies first ends its connection, the other side may never get the // against one that opens and seals the signaling. They are genuine, made with the right key, only
// proof then, but neither passes. // 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 () => { 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 [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 [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'); for (const page of [sender, receiver]) await page.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share'); 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 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(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 15_000 });
await expect(receiver.locator('#log')).toContainText('looking again', { 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.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share'); 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', { await expect(sender.locator('#log')).toContainText('security check failed, the peer does not know the code', {
timeout: 15_000, 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 () => { 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 [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
const source = await payload(randomBytes(SIZE)); 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 // 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 () => { test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
const sender = await open(name, { init: countAbortListeners }); const sender = await open(name, { init: countAbortListeners });
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); 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 withLogs(sender, sender, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share'); await sender.click('#share');
const code = (await sender.locator('#send-code').textContent())!;
await expect.poll(() => trackers.sockets.length).toBe(2); await expect.poll(() => trackers.sockets.length).toBe(2);
for (let offers = 1; offers <= 25; offers++) { for (let offers = 1; offers <= 25; offers++) {
trackers.sockets[0]!.send(garbageOffer()); trackers.sockets[0]!.send(garbageOffer(code));
await expect.poll(unusable).toBe(offers); await expect.poll(unusable).toBe(offers);
// Once it accepted the announcement, a failure only concerns that one message. // 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' })); 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')).toContainText(': slow down');
await expect(sender.locator('#log')).not.toContainText('rejected by'); await expect(sender.locator('#log')).not.toContainText('rejected by');
await expect(sender.locator('#send-error')).toHaveCount(0); 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 // Opening an offer takes a moment, the share may expire meanwhile. Expired is expired, that offer
// announces another code on the sender's info_hash. Neither side can prove anything to the other. // 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 () => { 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 [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
const source = await payload(randomBytes(SIZE)); const source = await payload(randomBytes(SIZE));
@@ -952,14 +1030,10 @@ for (const name of Object.keys(BROWSERS)) {
await intrude(intruder, swarm(code)); await intrude(intruder, swarm(code));
await intruder.fill('#receive-code', 'notthecode'); await intruder.fill('#receive-code', 'notthecode');
await intruder.click('#receive'); await intruder.click('#receive');
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 45_000 }); await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { 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 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.fill('#receive-code', code);
await receiver.click('#receive'); await receiver.click('#receive');
@@ -1110,13 +1184,16 @@ async function announces(page: Page) {
return announced; return announced;
} }
// Puts the middleman page between the sender and the receiver on their mocked trackers, as a tracker // The first announcement that matches, once there is one.
// could. Without a receiver it reflects, see middleman. async function first(announced: Announce[], match: (msg: Announce['msg']) => unknown) {
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); await expect.poll(() => announced.some(({ msg }) => match(msg))).toBe(true);
return announced.find(({ msg }) => match(msg))!; return announced.find(({ msg }) => match(msg))!;
}; }
// Puts the middleman page between the sender and the receiver on their mocked trackers, as a tracker
// 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 binary = () => randomBytes(20).toString('latin1');
const peerId = binary(); const peerId = binary();
type Hosting = { middle: Middle }; type Hosting = { middle: Middle };
@@ -1124,25 +1201,49 @@ async function interpose(middle: Page, toSender: Announce[], toReceiver?: Announ
if (toReceiver) { if (toReceiver) {
const { msg, ws } = await first(toReceiver, (msg) => msg.offers); const { msg, ws } = await first(toReceiver, (msg) => msg.offers);
const [{ offer, offer_id }] = 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 sdp = await middle.evaluate(
const answer = { type: 'answer', sdp }; (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 })); 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 { 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 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 })); 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); 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. // What secrets in src/core.ts derives from the code for info, PBKDF2 once per code.
const swarm = (code: string) => const masters = new Map<string, Buffer>();
Buffer.from(hkdfSync('sha256', pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'), '', 'swarm', 20)).toString( function secret(code: string, info: string, length: number) {
'latin1', 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) { async function announceGarbage(code: string) {
const ws = new WebSocket(TRACKER); const ws = new WebSocket(TRACKER);
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
@@ -1160,7 +1261,7 @@ async function announceGarbage(code: string) {
downloaded: 0, downloaded: 0,
left: 1, left: 1,
event: 'started', 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; return ws;
@@ -1180,13 +1281,13 @@ async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>, ws
return trackers; return trackers;
} }
// What a tracker relays from a receiver: an offer no browser can parse. // What a tracker relays from a receiver: an offer no browser can parse, sealed with code if given.
const garbageOffer = () => const garbageOffer = (code?: string) =>
JSON.stringify({ JSON.stringify({
action: 'announce', action: 'announce',
peer_id: randomBytes(20).toString('latin1'), peer_id: randomBytes(20).toString('latin1'),
offer_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 // 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; (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. // 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 // 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. // window counts.
+63 -25
View File
@@ -152,7 +152,7 @@ function randomCode() {
// scraping one, can test a guessed code against all of them at once. PBKDF2 makes every guess cost // 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 // 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 // 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. // info_hash tells nothing about the keys: one seals the signaling, see seal, one proves the connection.
async function secrets(code: string) { async function secrets(code: string) {
const text = new TextEncoder(); const text = new TextEncoder();
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']); const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
@@ -168,7 +168,33 @@ async function secrets(code: string) {
'sign', 'sign',
'verify', 'verify',
]); ]);
return { hash: String.fromCharCode(...new Uint8Array(hash)), key }; const sealing = await crypto.subtle.deriveKey(expand('signaling'), master, { name: 'AES-GCM', length: 256 }, false, [
'encrypt',
'decrypt',
]);
return { hash: String.fromCharCode(...new Uint8Array(hash)), key, sealing };
}
// Tracker signaling carries the SDP sealed with the code: neither the trackers nor a peer that found
// the swarm without the code learn the addresses in it, and nobody answers what they can't open. The
// type is sealed along, an offer doesn't pass for an answer. Base64 of IV and ciphertext, in the
// sdp field, so trackers relay it like any other.
async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) {
const text = new TextEncoder();
const iv = crypto.getRandomValues(new Uint8Array(12));
const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) };
const sealed = await crypto.subtle.encrypt(params, key, text.encode(sdp));
return btoa(String.fromCharCode(...iv, ...new Uint8Array(sealed)));
}
// The SDP, unless it wasn't sealed with the code as that type.
async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) {
// atob throws on what isn't base64, decrypt on anything else.
try {
const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0));
const params = { name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: new TextEncoder().encode(type) };
return new TextDecoder().decode(await crypto.subtle.decrypt(params, key, bytes.subarray(12)));
} catch {}
} }
function announce(ws: WebSocket, hash: string, peerId: string, params: object) { function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
@@ -659,13 +685,14 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
// A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason // A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason
// before anything else rejects the announcement, the tracker is no use then and its socket closes, a // before anything else rejects the announcement, the tracker is no use then and its socket closes, a
// later one only concerns that message and is logged. lost runs once it closed without close() being // later one only concerns that message and is logged. message may be async, the next message doesn't
// called: unreachable, lost or rejected. again announces once more, on the first interval it names. // wait for it. lost runs once it closed without close() being called: unreachable, lost or rejected.
// again announces once more, on the first interval it names.
function trackerSocket( function trackerSocket(
url: string, url: string,
signal: AbortSignal, signal: AbortSignal,
events: Events, events: Events,
message: (msg: Message) => void, message: (msg: Message) => void | Promise<void>,
lost: () => void, lost: () => void,
again: () => void, again: () => void,
) { ) {
@@ -706,7 +733,7 @@ function trackerSocket(
if (!reannounce && !closed && typeof msg.interval === 'number') { if (!reannounce && !closed && typeof msg.interval === 'number') {
reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000))); reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000)));
} }
return message(msg); return void message(msg);
} }
if (accepted) return events.log(`${url}: ${failure}`); if (accepted) return events.log(`${url}: ${failure}`);
tracker.rejected = `${url}: ${failure.slice(0, 200)}`; tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
@@ -726,14 +753,15 @@ function noTracker(trackers: (Tracker | undefined)[]) {
} }
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a // Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
// time. Until a receiver proved the code, the next one gets its turn: a peer that found the swarm // time. An offer not sealed with the code gets no turn, a peer that found the swarm without it doesn't
// without it doesn't end the share. Neither does an offer that can't be answered, never connects or // even learn the sender's address. Until a receiver proved the code, the next one gets its turn: an
// proves nothing. Once the download started the share is used up, the trackers go. After // offer that can't be answered, never connects or proves nothing doesn't end the share. Once the
// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn. // 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) { export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
events = live(events, signal); events = live(events, signal);
const code = randomCode(); const code = randomCode();
const { hash, key } = await secrets(code); const { hash, key, sealing } = await secrets(code);
const peerId = randomBinary(20); const peerId = randomBinary(20);
const trackers: Tracker[] = []; const trackers: Tracker[] = [];
let busy = false; let busy = false;
@@ -802,10 +830,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
pc.addEventListener('connectionstatechange', () => { pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed') giveUp('receiver did not connect'); if (pc.connectionState === 'failed') giveUp('receiver did not connect');
}); });
let sdp: string;
try { try {
await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp }); await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp });
await pc.setLocalDescription(); await pc.setLocalDescription();
await gatherIce(pc); await gatherIce(pc);
sdp = await seal(sealing, 'answer', pc.localDescription!.sdp);
} catch (error) { } catch (error) {
return giveUp(`unusable offer via ${url}: ${error}`); return giveUp(`unusable offer via ${url}: ${error}`);
} }
@@ -814,7 +844,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
left: 0, left: 0,
to_peer_id: msg.peer_id, to_peer_id: msg.peer_id,
offer_id: msg.offer_id, offer_id: msg.offer_id,
answer: pc.localDescription, answer: { type: 'answer', sdp },
}); });
} }
@@ -823,11 +853,15 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
url, url,
signal, signal,
events, events,
(msg) => { async (msg) => {
// What a tracker relays from a receiver, anything else is ignored. // What a tracker relays from a receiver, anything else is ignored.
if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return; if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return;
if (typeof msg.offer_id !== 'string') return; if (typeof msg.offer_id !== 'string') return;
const offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id }; const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
// Meanwhile the share may have been used up, expired or ended, its trackers closed then.
if (signal.aborted || !tracker.alive()) return;
if (sdp === undefined) return events.log(`offer without the code via ${url}`);
const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
if (busy) waiting = () => answer(tracker.ws, url, offer); if (busy) waiting = () => answer(tracker.ws, url, offer);
else void answer(tracker.ws, url, offer); else void answer(tracker.ws, url, offer);
}, },
@@ -846,13 +880,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails // Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have // or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
// queued one of them. An answer that can't be used or never connects is replaced right away. Once the // queued one of them. An answer not sealed with the code is ignored, the offer waits for the real one.
// download started, every other offer and tracker socket goes. After TRACKER_WAIT no offer is made or // One that can't be used or never connects is replaced right away. Once the download started, every
// kept any more, a sender connected by then still gets its turn. // other offer and tracker socket goes. After TRACKER_WAIT no offer is made or kept any more, a sender
// connected by then still gets its turn.
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) { export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
events = live(events, signal); events = live(events, signal);
await downloadsReady(); await downloadsReady();
const { hash, key } = await secrets(code.trim()); const { hash, key, sealing } = await secrets(code.trim());
if (signal.aborted) return; if (signal.aborted) return;
const peerId = randomBinary(20); const peerId = randomBinary(20);
// The current offer per tracker, its socket only until the answer came. lost: the socket closed // The current offer per tracker, its socket only until the answer came. lost: the socket closed
@@ -925,7 +960,8 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
pc.setLocalDescription() pc.setLocalDescription()
.then(() => gatherIce(pc)) .then(() => gatherIce(pc))
.then(() => { .then(() => seal(sealing, 'offer', pc.localDescription!.sdp))
.then((sdp) => {
if (pc.signalingState === 'closed' || expired) return; if (pc.signalingState === 'closed' || expired) return;
// Again with the same offer on the interval, a busy sender may have dropped it meanwhile. // Again with the same offer on the interval, a busy sender may have dropped it meanwhile.
const hello = (event?: string) => const hello = (event?: string) =>
@@ -933,21 +969,23 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
left: 1, left: 1,
numwant: 1, numwant: 1,
event, event,
offers: [{ offer_id: offerId, offer: pc.localDescription }], offers: [{ offer_id: offerId, offer: { type: 'offer', sdp } }],
}); });
const tracker = trackerSocket( const tracker = trackerSocket(
url, url,
signal, signal,
events, events,
(msg) => { async (msg) => {
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return; if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
const answer = await unseal(sealing, 'answer', msg.answer.sdp);
// Only one answer per offer, a replacement opens its own socket. Meanwhile it may have
// come, or the search ended, its socket closed then.
if (pc.signalingState === 'closed' || !tracker.alive()) return;
if (answer === undefined) return events.log(`answer without the code via ${url}`);
events.log(`answer via ${url}`); events.log(`answer via ${url}`);
// Only one answer per offer, a replacement opens its own socket.
tracker.close(); tracker.close();
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT); timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() => pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
retry(`unusable answer via ${url}`),
);
}, },
() => { () => {
entry.lost = true; entry.lost = true;