diff --git a/README.md b/README.md index 46365f7..de28834 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,9 @@ the browsers need two things: - **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 - 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. 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. @@ -68,7 +70,8 @@ networks, a direct connection may not be possible. - 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 - 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. - Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that, host your own (below). diff --git a/e2e.spec.ts b/e2e.spec.ts index 1f9070a..dc2ac0b 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -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(); +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, 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. diff --git a/src/core.ts b/src/core.ts index e9b1489..91278df 100644 --- a/src/core.ts +++ b/src/core.ts @@ -152,7 +152,7 @@ function randomCode() { // 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. +// info_hash tells nothing about the keys: one seals the signaling, see seal, one proves the connection. async function secrets(code: string) { const text = new TextEncoder(); const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']); @@ -168,7 +168,33 @@ async function secrets(code: string) { 'sign', '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) { @@ -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 // 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 -// called: unreachable, lost or rejected. again announces once more, on the first interval it names. +// later one only concerns that message and is logged. message may be async, the next message doesn't +// 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( url: string, signal: AbortSignal, events: Events, - message: (msg: Message) => void, + message: (msg: Message) => void | Promise, lost: () => void, again: () => void, ) { @@ -706,7 +733,7 @@ function trackerSocket( if (!reannounce && !closed && typeof msg.interval === 'number') { 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}`); 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 -// 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. +// time. An offer not sealed with the code gets no turn, a peer that found the swarm without it doesn't +// even learn the sender's address. Until a receiver proved the code, the next one gets its turn: an +// offer that can't be answered, never connects or proves nothing doesn't end the share. 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, key } = await secrets(code); + const { hash, key, sealing } = await secrets(code); const peerId = randomBinary(20); const trackers: Tracker[] = []; let busy = false; @@ -802,10 +830,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed') giveUp('receiver did not connect'); }); + let sdp: string; try { await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp }); await pc.setLocalDescription(); await gatherIce(pc); + sdp = await seal(sealing, 'answer', pc.localDescription!.sdp); } catch (error) { return giveUp(`unusable offer via ${url}: ${error}`); } @@ -814,7 +844,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi left: 0, to_peer_id: msg.peer_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, signal, events, - (msg) => { + async (msg) => { // 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 (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); 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 // 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 -// download started, every 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. +// queued one of them. An answer not sealed with the code is ignored, the offer waits for the real one. +// One that can't be used or never connects is replaced right away. Once the download started, every +// 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) { events = live(events, signal); await downloadsReady(); - const { hash, key } = await secrets(code.trim()); + const { hash, key, sealing } = 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 @@ -925,7 +960,8 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig pc.setLocalDescription() .then(() => gatherIce(pc)) - .then(() => { + .then(() => seal(sealing, 'offer', pc.localDescription!.sdp)) + .then((sdp) => { if (pc.signalingState === 'closed' || expired) return; // Again with the same offer on the interval, a busy sender may have dropped it meanwhile. const hello = (event?: string) => @@ -933,21 +969,23 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig left: 1, numwant: 1, event, - offers: [{ offer_id: offerId, offer: pc.localDescription }], + offers: [{ offer_id: offerId, offer: { type: 'offer', sdp } }], }); const tracker = trackerSocket( url, signal, events, - (msg) => { + async (msg) => { 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}`); - // Only one answer per offer, a replacement opens its own socket. tracker.close(); timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT); - pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() => - retry(`unusable answer via ${url}`), - ); + pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`)); }, () => { entry.lost = true;