From ae871a26471df6f1737c7343bbe2ae37c55b8834 Mon Sep 17 00:00:00 2001 From: Schluffe Date: Wed, 28 Oct 2026 22:24:24 +0100 Subject: [PATCH] Improve tests --- e2e.spec.ts | 900 ++++------------------------------------------- src/core.test.ts | 43 +++ 2 files changed, 118 insertions(+), 825 deletions(-) diff --git a/e2e.spec.ts b/e2e.spec.ts index 30bf51a..9f94fce 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -22,28 +22,20 @@ import { build, createServer, preview, type ViteDevServer } from 'vite'; const BROWSERS: Record = { chromium, firefox }; // Chromium needs a permission for the copy buttons, Firefox lets the click do it and rejects the name. const PERMISSIONS: Record = { chromium: ['clipboard-write'], firefox: [] }; -// The live tests use the default trackers and STUN servers in src/core.ts. The first tracker, -// HellCon's own, refuses the dev server's origin, so both sides go on to this one. -const TRACKER = 'wss://tracker.webtorrent.dev'; const SIZE = 5_000_000; // Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS // staging could store in incognito-like contexts. 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, PROBE_TIMEOUT, PROOF_TIMEOUT and CONNECT_TIMEOUT in src/core.ts, DOWNLOAD_GRACE in -// src/download.ts. +// WINDOW, PROBE_TIMEOUT and CONNECT_TIMEOUT in src/core.ts, DOWNLOAD_GRACE in src/download.ts. const WINDOW = 8 * 2 ** 20; const PROBE_TIMEOUT = 2000; -const PROOF_TIMEOUT = 10_000; const CONNECT_TIMEOUT = 30_000; const DOWNLOAD_GRACE = 1000; -// Every page's clock starts a second into the window from 12:00 to 12:06 UTC unless a test sets -// another time, so the test knows the salt of every code, see saltOf. SALT_WINDOW is the one in -// src/core.ts. +// Every page's clock starts a second into the salt's window from 12:00 to 12:06 UTC unless a test +// sets another time, so the test knows when the window of a code ends. const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1); -const SALT_WINDOW = 6 * 60_000; -const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // When a share or search ends, in its error. The browser writes the time its own way. const UNTIL = String.raw`until \d\d?:\d\d(?:[\u00a0\u202f][AP]M)?`; // Enough for a transfer whose receiver holds back its reads to pause at the window. @@ -253,37 +245,6 @@ function holdReads() { }; } -// Init script: keeps the page's data channels in window.channels, its own and the peer's, so a test -// can send on them like a peer that skips the security check or breaks the protocol. -function recordChannels() { - if (window !== window.top) return; - const page = window as unknown as { channels: RTCDataChannel[] }; - page.channels = []; - const create = RTCPeerConnection.prototype.createDataChannel; - RTCPeerConnection.prototype.createDataChannel = function (this: RTCPeerConnection, ...args) { - const channel = create.apply(this, args); - page.channels.push(channel); - return channel; - }; - const PeerConnection = RTCPeerConnection; - window.RTCPeerConnection = class extends PeerConnection { - constructor(config?: RTCConfiguration) { - super(config); - this.addEventListener('datachannel', ({ channel }) => page.channels.push(channel)); - } - }; -} - -// Sends on the page's first data channel, past the app: strings as they are, a number as that many bytes. -const inject = (page: Page, ...messages: (string | number)[]) => - page.evaluate((messages) => { - const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels; - for (const message of messages) { - if (typeof message === 'string') channel!.send(message); - else channel!.send(new Uint8Array(message)); - } - }, messages); - const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received); const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release()); @@ -433,8 +394,9 @@ for (const from of Object.keys(BROWSERS)) { } } -// Through the public STUN servers and trackers. The signaling doesn't depend on the browser pair, one -// pairing each way is enough. +// Through the default STUN servers and trackers in src/core.ts. The first tracker, HellCon's own, +// refuses the dev server's origin, so both sides go on to the next one. The signaling doesn't depend +// on the browser pair, one pairing each way is enough. for (const mode of ['manual', 'tracker']) { for (const [from, to] of [ ['chromium', 'firefox'], @@ -604,39 +566,6 @@ for (const name of Object.keys(BROWSERS)) { expect(next.servers).toEqual([servers[2]]); }); - // A probe serves the sessions waiting for it. A new session takes it over, one without STUN stops - // it: the server after the one it was at hears nothing. 192.0.2.x never answer. - test(`stun: ${name} probing stops once no session waits for it`, async () => { - const page = await open(name); - const fakes = [await fakeStun(), await fakeStun()]; - const requests = [0, 0]; - for (const [i, socket] of fakes.entries()) socket.on('message', () => requests[i]!++); - const fake = (i: number) => `stun:${LOCAL_ADDRESS}:${fakes[i]!.address().port}`; - const offer = async () => { - await expect(page.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 }); - return Buffer.from(await page.inputValue('#offer'), 'base64').toString(); - }; - await page.click('#servers summary'); - await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1))); - await page.click('#send-manual summary'); - - await page.fill('#stun-servers', `stun:192.0.2.1:3478\n${fake(0)}`); - await page.click('#create-offer'); - await page.waitForTimeout(PROBE_TIMEOUT / 4); - await page.click('#create-offer'); - expect(await offer()).toContain(`${PUBLIC_ADDRESS} `); - - await page.fill('#stun-servers', `stun:192.0.2.2:3478\n${fake(1)}`); - await page.click('#create-offer'); - await page.waitForTimeout(PROBE_TIMEOUT / 4); - await page.uncheck('#stun'); - await page.click('#create-offer'); - expect(await offer()).not.toContain(`${PUBLIC_ADDRESS} `); - await page.waitForTimeout(PROBE_TIMEOUT * 1.5); - expect(requests[1]).toBe(0); - for (const socket of fakes) socket.close(); - }); - test(`update: ${name} receives after sw.js changed`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); const source = await payload(randomBytes(SIZE)); @@ -688,21 +617,6 @@ for (const name of Object.keys(BROWSERS)) { }); }); - // Proves the sender's window: the receiver only holds back its { read } reports, its download - // manager still reads. Memory bounds of a really slow disk are beyond what a test can observe. - test(`flow: ${name} sender waits while the receiver reports no reads`, async () => { - const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]); - const source = await payload(randomBytes(HELD_SIZE)); - - await transfer('offline', sender, receiver, source, HELD_SIZE, async () => { - await expect.poll(() => received(receiver)).toBe(WINDOW); - // Proving that nothing more comes needs a moment, the sender fills the window in milliseconds. - await receiver.waitForTimeout(1000); - expect(await received(receiver)).toBe(WINDOW); - await release(receiver); - }); - }); - test(`progress: ${name} follows the shared file, not a later pick`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); const source = await payload(randomBytes(100_000)); @@ -814,58 +728,10 @@ for (const name of Object.keys(BROWSERS)) { }); }); - test(`check: ${name} accepts nothing before the receiver confirmed`, async () => { - const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - let downloads = 0; - receiver.on('download', () => downloads++); - await connect('offline', sender, receiver, source); - // What a man in the middle could send without waiting for anyone's confirmation. - await inject(sender, JSON.stringify({ name: 'injected.bin', size: 4 }), 4); - await sender.click('#confirm'); - await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check"); - // Proving that nothing starts needs a moment, a download would start within milliseconds. - await receiver.waitForTimeout(1000); - expect(await log(receiver)).not.toContain('receiving'); - expect(await log(sender)).not.toContain('sending'); - expect(downloads).toBe(0); - - const started = downloadStarts(receiver); - await receiver.click('#confirm'); - await receiver.click('#download'); - const { download } = await started; - expect(download.suggestedFilename()).toBe('payload.bin'); - expect(await hash(await download.path())).toBe(await hash(source)); - await expect(sender.locator('#log')).toContainText('delivered'); - expect(downloads).toBe(1); - }); - }); - - test(`check: ${name} offers nothing before the sender confirmed`, async () => { - const [sender, receiver] = await Promise.all([open(name), open(name, { init: recordChannels })]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - await connect('offline', sender, receiver, source); - // A receiver that skips its own check and asks for the file right away. - await inject(receiver, JSON.stringify({ ok: true }), JSON.stringify({ start: true })); - await sender.waitForTimeout(1000); - expect(await log(sender)).not.toContain('offered'); - - await sender.click('#confirm'); - await expect(sender.locator('#log')).toContainText('waiting for the receiver to download'); - // The early start counted for nothing, the sender waits for one after its offer. - await sender.waitForTimeout(500); - expect(await log(sender)).not.toContain('sending'); - }); - }); - - // 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. + // The proofs hold even against a man in the middle that opens and seals the signaling. They are + // genuine, made with the right key, only the real certificates' 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. Without the code, sealing keeps it out, see src/core.test.ts. 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)]); @@ -893,105 +759,6 @@ for (const name of Object.keys(BROWSERS)) { }); }); - test(`check: ${name} sender rejects its own proof sent back`, async () => { - const [sender, middle] = await Promise.all([open(name), open(name, { init: middleman })]); - const toSender = await announces(sender); - - await withLogs(sender, sender, async () => { - await sender.uncheck('#stun'); - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - await sender.click('#share'); - 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, - }); - expect(await relayed(middle)).toBe(1); - expect(await log(sender)).not.toContain('security check passed'); - expect(await log(sender)).not.toContain('offered'); - }); - }); - - // 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)); - - await withLogs(sender, receiver, async () => { - await connect('offline', sender, receiver, source); - await receiver.click('#confirm'); - await inject(sender, JSON.stringify({ name: 1, size: 2 })); - await expect(receiver.locator('#receive-error')).toHaveText('the sender offered no valid file'); - await expect(receiver.locator('#download')).toHaveCount(0); - await expectClosed(receiver); - }); - }); - - test(`protocol: ${name} receiver fails a download with more bytes than offered`, async () => { - const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - await connect('offline', sender, receiver, source); - await receiver.click('#confirm'); - await inject(sender, JSON.stringify({ name: 'twenty.bin', size: 20_000 })); - const started = downloadStarts(receiver); - await receiver.click('#download'); - // The download only starts with the first bytes. - await inject(sender, 10_000); - const { download } = await started; - await inject(sender, 10_001); - await expect(receiver.locator('#receive-error')).toHaveText( - 'download failed: the sender sent more than it offered', - ); - await expect(receiver.locator('iframe')).toHaveCount(0); - // Firefox leaves the download stalled instead of failing it, see TODO.md. - if (name === 'chromium') expect(await download.failure()).not.toBeNull(); - await expectClosed(receiver); - }); - }); - test(`protocol: ${name} manual exchange reports a broken offer and answer`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); @@ -1010,181 +777,10 @@ for (const name of Object.keys(BROWSERS)) { await expectClosed(receiver); }); - // An offer that can't be answered used to keep the share busy forever. - test(`live tracker: ${name} sender goes on after an unusable offer`, async () => { - const [sender, receiver] = await Promise.all([open(name), open(name)]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - 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())!; - const garbage = await announceGarbage(code); - await expect(sender.locator('#log')).toContainText('unusable offer'); - await expect(sender.locator('#log')).toContainText('waiting for the next receiver'); - garbage.close(); - - await receiver.fill('#receive-code', code); - await receiver.click('#receive'); - await proven(sender, receiver); - const started = downloadStarts(receiver); - 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'); - }); - }); - - // The 6 minutes only limit finding each other, a receiver connected by then still gets the file. - test(`live tracker: ${name} a receiver connected before the expiry downloads after it`, async () => { - const [sender, receiver] = await Promise.all([open(name), open(name)]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - await sender.setInputFiles('input[type=file]', source); - await MODES.tracker!(sender, receiver); - 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); - } - await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:'); - - const started = downloadStarts(receiver); - 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 expect(sender.locator('#send-error')).toHaveCount(0); - await expect(receiver.locator('#receive-error')).toHaveCount(0); - }); - }); - - // Trackers that keep the socket open but turn the announcement down used to leave both sides waiting. - test(`tracker: ${name} reports trackers that reject the announcement`, async () => { - const [sender, receiver] = await Promise.all([open(name), open(name)]); - const trackers = await Promise.all( - [sender, receiver].map((page) => mockTrackers(page, () => ({ 'failure reason': 'not here' }))), - ); - const rejected = - /^no tracker accepted it \((wss:\S+: not here; ){2}wss:\S+: not here\), check the list under Servers/; - - await withLogs(sender, receiver, async () => { - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - await sender.click('#share'); - await expect(sender.locator('#send-error')).toHaveText(rejected); - await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); - await receiver.click('#receive'); - await expect(receiver.locator('#receive-error')).toHaveText(rejected); - await expect - .poll(() => trackers.map(({ sockets, open }) => [sockets.length, open])) - .toEqual([ - [3, 0], - [3, 0], - ]); - }); - }); - - // Only the tracker in use learns about the share, the next one only once that one failed it. - test(`tracker: ${name} sender stays on the first tracker that accepts it`, async () => { - const sender = await open(name); - const urls = ['wss://one.test', 'wss://two.test', 'wss://three.test']; - const trackers: Awaited> = await mockTrackers(sender, ({ info_hash }, ws) => - ws === trackers.sockets[0] ? { 'failure reason': 'not here' } : { action: 'announce', interval: 120, info_hash }, - ); - - await withLogs(sender, sender, async () => { - await sender.click('#servers summary'); - await sender.fill('#trackers', urls.join('\n')); - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - await sender.click('#share'); - await expect(sender.locator('#log')).toContainText(`rejected by ${urls[0]}: not here`); - await expect(sender.locator('#log')).toContainText(`waiting on ${urls[1]}`); - // A third one would come within milliseconds. - await sender.waitForTimeout(1000); - expect(trackers.sockets.length).toBe(2); - - trackers.sockets[1]!.close(); - await expect(sender.locator('#log')).toContainText(`waiting on ${urls[2]}`); - await expect(sender.locator('#send-error')).toHaveCount(0); - }); - }); - - // The sender is on the first tracker that accepted it, the receiver goes on until it finds it there. - // The trackers it passed keep its offer, in case the sender comes. - test(`tracker: ${name} receiver walks the trackers until one has a seeder`, async () => { - const receiver = await open(name); - const urls = ['wss://one.test', 'wss://two.test', 'wss://three.test']; - const trackers: Awaited> = await mockTrackers(receiver, ({ info_hash }, ws) => ({ - action: 'announce', - interval: 120, - info_hash, - complete: ws === trackers.sockets[1] ? 1 : 0, - })); - - await withLogs(receiver, receiver, async () => { - await receiver.uncheck('#stun'); - await receiver.click('#servers summary'); - await receiver.fill('#trackers', urls.join('\n')); - await receiver.fill('#receive-code', 'somecode123'); - await receiver.click('#receive'); - await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`); - // A third one would come within milliseconds. - await receiver.waitForTimeout(1000); - expect([trackers.sockets.length, trackers.open]).toEqual([2, 2]); - - // The sender lost the second one, its next reply has no seeder. - trackers.sockets[1]!.send(JSON.stringify({ action: 'announce', interval: 120, complete: 0 })); - await expect(receiver.locator('#log')).toContainText(`looking on ${urls[2]}`); - expect([trackers.sockets.length, trackers.open]).toEqual([3, 3]); - await expect(receiver.locator('#receive-error')).toHaveCount(0); - // None has it any more, the search goes on but says so. - await expect(receiver.locator('[data-phase=retry] #receive-status')).toHaveText( - 'No sender with this code on any tracker. Check the code, still looking', - ); - // A sender showed up, busy with another receiver maybe: the code was right. - trackers.sockets[2]!.send(JSON.stringify({ action: 'announce', interval: 120, complete: 1 })); - await expect(receiver.locator('[data-phase=wait] #receive-status')).toHaveText( - 'Found the share on three.test, waiting for the sender to answer', - ); - }); - }); - - // 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. 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 })); - const listeners = () => - sender.evaluate(() => (window as unknown as { abortListeners: () => number }).abortListeners()); - const unusable = async () => (await log(sender))!.match(/unusable offer/g)?.length ?? 0; - - 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(1); - for (let offers = 1; offers <= 25; offers++) { - 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[0]!.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); - // The tracker socket's and the expiry's, none for the closed connections. - expect(await listeners()).toBe(2); - }); - }); - - // The info_hash tells which salt a share took: the window its code ends with, or that and the own - // salt, trimmed and NFC. A code made late in a window still lasts 6 minutes. The salt stays as it is - // while a share runs, a search lets it be fixed for the next Receive. + // A share takes the salt of the window its code ends with, or that and the own salt, trimmed and + // NFC: a search with the same code and salt announces the same info_hash. A code made late in a + // window still lasts 6 minutes. The salt stays as it is while a share runs, a search lets it be + // fixed for the next Receive. src/core.test.ts checks the info_hash against the protocol. test(`salt: ${name} a share takes the clock's salt or the own one, which stays while it runs`, async () => { const sender = await open(name); const hashes: string[] = []; @@ -1200,27 +796,37 @@ for (const name of Object.keys(BROWSERS)) { (at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'), at, ); - // The code and info_hash of the share start begins, by default a click on Share. - const share = async (start = () => sender.click('#share')) => { + // The info_hash a click on Share or Receive announces. A search finds no seeder on the mocks, one + // tracker keeps it to one announcement. + const announced = async (button: string) => { const count = hashes.length; - await start(); + await sender.click(button); await expect.poll(() => hashes.length).toBe(count + 1); - return { code: (await sender.locator('#send-code').textContent())!, hash: hashes.at(-1) }; + return hashes.at(-1); + }; + const share = async () => ({ + hash: await announced('#share'), + code: (await sender.locator('#send-code').textContent())!, + }); + const search = async (code: string) => { + await sender.fill('#receive-code', code); + return announced('#receive'); }; await withLogs(sender, sender, async () => { + await sender.click('#servers summary'); + await sender.fill('#trackers', 'wss://tracker.test'); await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); const first = await share(); - expect(first.hash).toBe(swarm(first.code)); await expect(label).toHaveText(valid); // toHaveText takes a no-break space for any space, the text itself has to have it. expect(await label.textContent()).toMatch(new RegExp(`${UNTIL}:`)); + expect(await search(first.code)).toBe(first.hash); // 12:05:30, half a minute before the window ends. Still valid for 6 minutes, until 12:11. await sender.clock.fastForward('05:29'); const late = await share(); expect(late.code.at(-1)).toBe(first.code.at(-1)); - expect(late.hash).toBe(swarm(late.code)); await expect(label).toHaveText(valid); expect(await label.textContent()).toContain(`until ${await time(Date.UTC(2026, 0, 1, 12, 11, 30))}:`); @@ -1228,7 +834,6 @@ for (const name of Object.keys(BROWSERS)) { await expect(label).toHaveText('Code, no longer valid:'); const next = await share(); expect(next.code.at(-1)).not.toBe(first.code.at(-1)); - expect(next.hash).toBe(swarm(next.code)); // The switch, and the salt with Generate while it's on. const locked = async (disabled: boolean) => { @@ -1249,7 +854,6 @@ for (const name of Object.keys(BROWSERS)) { await sender.fill('#salt', ' Gru\u0308ße '); await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'false'); const own = await share(); - expect(own.hash).toBe(swarm(own.code, 'Grüße')); await expect(label).toHaveText(/^\s*Code, give this and your salt to the receiver, valid until .+:\s*$/); await locked(true); @@ -1260,7 +864,6 @@ for (const name of Object.keys(BROWSERS)) { const generated = await sender.inputValue('#salt'); expect(generated).toMatch(/^[0-9a-zA-Z]{16}$/); const resalted = await share(); - expect(resalted.hash).toBe(swarm(resalted.code, generated)); // What can't be a code is told right away, that search is over. await sender.fill('#receive-code', 'abcdefghij'); @@ -1268,13 +871,13 @@ for (const name of Object.keys(BROWSERS)) { await expect(sender.locator('#receive-error')).toHaveText('a code has 11 letters and digits, check it'); await locked(false); - await sender.fill('#receive-code', 'abcdefghijk'); - await sender.click('#receive'); - await expect.poll(() => hashes).toContain(swarm('abcdefghijk', generated)); + expect(await search(resalted.code)).toBe(resalted.hash); await locked(false); - await sender.fill('#salt', 'fixed'); - await sender.click('#receive'); - await expect.poll(() => hashes).toContain(swarm('abcdefghijk', 'fixed')); + // ü composed, without the spaces. + await sender.fill('#salt', 'Grüße'); + expect(await search(own.code)).toBe(own.hash); + await sender.uncheck('#own-salt'); + expect(await search(own.code)).not.toBe(own.hash); }); }); @@ -1315,128 +918,6 @@ for (const name of Object.keys(BROWSERS)) { }); }); - // Trackers drop a peer that doesn't announce again on their interval, the defaults after 2 to 3 - // minutes. A code nobody uses still ends after 6 minutes, on both sides. - test(`tracker: ${name} both sides announce again until they give up after 6 minutes`, async () => { - const pages = await Promise.all([open(name), open(name)]); - const [sender, receiver] = pages as [Page, Page]; - // biome-ignore lint/suspicious/noExplicitAny: raw tracker messages, the test reads nested fields as it needs them - const announced = pages.map(() => [] as Record[]); - // 0 would announce in a loop, the app waits 30 s at least. - const trackers = await Promise.all( - pages.map(async (page, i) => { - return mockTrackers(page, (msg) => { - announced[i]!.push(msg); - return { action: 'announce', interval: 0, info_hash: msg.info_hash }; - }); - }), - ); - const again = () => announced.map((msgs) => msgs.filter((msg) => !msg.event)); - const fastForward = (ms: number) => Promise.all(pages.map((page) => page.clock.fastForward(ms))); - - await withLogs(sender, receiver, async () => { - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - await sender.click('#share'); - await expect(sender.locator('label[for=send-code]')).toHaveText(/valid until \d/); - await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); - await receiver.click('#receive'); - // The sender on the first tracker, the receiver on all of them: the mocks report no seeder. - await expect.poll(() => announced.map((msgs) => msgs.length)).toEqual([1, 3]); - // Until the replies with the interval reached the pages, and any early announce the test. - await sender.waitForTimeout(500); - await fastForward(25_000); - await sender.waitForTimeout(500); - expect(again().map((msgs) => msgs.length)).toEqual([0, 0]); - await fastForward(5_000); - await expect.poll(() => again().map((msgs) => msgs.length)).toEqual([1, 3]); - // The receiver's offers again, a busy sender may have dropped them. - const offers = announced[1]!.filter((msg) => msg.event === 'started').map((msg) => msg.offers[0].offer_id); - expect( - again()[1]! - .map((msg) => msg.offers[0].offer_id) - .sort(), - ).toEqual(offers.sort()); - - await fastForward(330_000); - await expect(sender.locator('#send-error')).toHaveText( - new RegExp(`^nobody received the file ${UNTIL}, share it again$`), - ); - await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:'); - await expect(sender.locator('#copy-send-code')).toBeDisabled(); - await expect(receiver.locator('#receive-error')).toHaveText( - new RegExp(`^no sender answered ${UNTIL}, ask the sender for a new code$`), - ); - await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]); - await expectClosed(sender); - await expectClosed(receiver); - }); - }); - - // Each expiry used to hold its session until it ran out, a failed receiver its connections. - test(`tracker: ${name} sessions that ended keep no expiry and no connection`, async () => { - const pages = await Promise.all([open(name, { init: countDeadlines }), open(name, { init: countDeadlines })]); - const [sender, receiver] = pages as [Page, Page]; - let rejecting = false; - await Promise.all( - pages.map((page) => - mockTrackers(page, ({ info_hash }) => - rejecting ? { 'failure reason': 'not here' } : { action: 'announce', interval: 120, info_hash }, - ), - ), - ); - const deadlines = () => - Promise.all( - pages.map((page) => page.evaluate(() => (window as unknown as { deadlines: () => number }).deadlines())), - ); - - await withLogs(sender, receiver, async () => { - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - for (let session = 0; session < 5; session++) { - await sender.click('#share'); - await receiver.fill('#receive-code', `nobodyhere${session}`); - await receiver.click('#receive'); - } - await expect.poll(deadlines).toEqual([1, 1]); - - rejecting = true; - await sender.click('#share'); - await receiver.click('#receive'); - await expect(sender.locator('#send-error')).toHaveText(/^no tracker accepted it/); - await expect(receiver.locator('#receive-error')).toHaveText(/^no tracker accepted it/); - await expect.poll(deadlines).toEqual([0, 0]); - await expectClosed(sender); - await expectClosed(receiver); - }); - }); - - // 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 }); - 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(1); - 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( - new RegExp(`^nobody received the file ${UNTIL}, 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); - }); - }); - // Between networks a side without a public address connects nobody. Chromium never fails such a // connection, the timeouts end it. The sender has one from the fake STUN server, the receiver has // STUN off. @@ -1463,92 +944,6 @@ for (const name of Object.keys(BROWSERS)) { }); }); - // Each failed connection says why in the log, the expiry repeats the last reason. - test(`hint: ${name} tracker signaling names the side without a public address`, async () => { - const tracker = await ownTracker(); - const [sender, receiver] = await apart(name); - const fastForward = (time: number | string) => - Promise.all([sender, receiver].map((page) => page.clock.fastForward(time))); - - await withLogs(sender, receiver, async () => { - for (const page of [sender, receiver]) await page.fill('#trackers', tracker); - await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000))); - await MODES.tracker!(sender, receiver); - await expect(receiver.locator('#log')).toContainText(`answer via ${tracker}`); - await fastForward(CONNECT_TIMEOUT); - await expect(sender.locator('#log')).toContainText(`receiver did not connect: the receiver ${NO_PUBLIC}`); - await expect(receiver.locator('#log')).toContainText( - `sender via ${tracker} did not connect: this side ${NO_PUBLIC}`, - ); - // Both keep trying, and say why the last attempt failed. - await expect(sender.locator('[data-phase=retry] #send-status')).toContainText( - `could not connect to the receiver: the receiver ${NO_PUBLIC}`, - ); - await expect(receiver.locator('[data-phase=retry] #receive-status')).toContainText( - `could not connect to the sender: this side ${NO_PUBLIC}`, - ); - // Then once more for the turn a new offer may have taken meanwhile. - await fastForward('06:00'); - await fastForward(CONNECT_TIMEOUT); - await expect(sender.locator('#send-error')).toHaveText( - new RegExp(`^no receiver connected ${UNTIL}: the receiver ${NO_PUBLIC}$`), - ); - await expect(receiver.locator('#receive-error')).toHaveText( - new RegExp(`^no sender connected ${UNTIL}: this side ${NO_PUBLIC}$`), - ); - await expectClosed(sender); - await expectClosed(receiver); - }); - }); - - // 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)); - - await withLogs(sender, receiver, async () => { - 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', 'notthecode0'); - await intruder.click('#receive'); - 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('connected'); - expect(await openPeers(sender)).toBe(0); - - await receiver.fill('#receive-code', code); - await receiver.click('#receive'); - await proven(sender, receiver); - const started = downloadStarts(receiver); - 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'); - }); - }); - - 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 })]); - const source = await payload(randomBytes(SIZE)); - - await withLogs(sender, receiver, async () => { - 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); - }); - }); - test(`disconnect: ${name} fails the download when the sender vanishes`, async () => { const [sender, receiver] = await Promise.all([open(name), open(name)]); const source = await payload(Buffer.alloc(RUNNING_SIZE)); @@ -1567,46 +962,25 @@ 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; +// Stands in for every tracker the page connects to from now on: reply answers each message the page +// sends, on the socket it came from. They don't show up in sockets. +async function mockTrackers(page: Page, reply: (msg: Record, ws: WebSocketRoute) => object) { 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 })); - }); + ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data)), ws)))); }); } -// 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); - }; -} - type Middle = { // Proofs that passed through. relayed: number; answer: (sdp: string) => Promise; - offer: (reflect: boolean) => Promise; + offer: () => Promise; accept: (sdp: string) => Promise; }; // Init script for a man in the middle, driven by interpose: it answers the receiver's offer and // offers to the sender itself, with its own certificate towards each, and relays every message -// between the two. With reflect it only connects to the sender and sends everything back. It runs -// in the hidden frames too, only the app's own window counts. +// between the two. It runs in the hidden frames too, only the app's own window counts. function middleman() { if (window !== window.top) return; type Side = 'sender' | 'receiver'; @@ -1643,9 +1017,9 @@ function middleman() { await pc.setRemoteDescription({ type: 'offer', sdp }); return localSdp(pc); }, - offer(reflect) { + offer() { toSender = new RTCPeerConnection(); - attach('sender', toSender.createDataChannel('file'), reflect ? 'sender' : 'receiver'); + attach('sender', toSender.createDataChannel('file'), 'receiver'); return localSdp(toSender); }, accept: (sdp) => toSender.setRemoteDescription({ type: 'answer', sdp }), @@ -1676,116 +1050,59 @@ async function first(announced: Announce[], match: (msg: Announce['msg']) => unk // 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[]) { +async function interpose(middle: Page, code: string, toSender: Announce[], toReceiver: Announce[]) { + const key = signalingKey(code); const binary = () => randomBytes(20).toString('latin1'); const peerId = binary(); type Hosting = { middle: Middle }; - 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), - 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 toward = await first(toReceiver, (msg) => msg.offers); + const [{ offer, offer_id }] = toward.msg.offers; + const sdp = await middle.evaluate( + (sdp) => (window as unknown as Hosting).middle.answer(sdp), + unseal(key, 'offer', offer.sdp), + ); + const answer = { type: 'answer', sdp: seal(key, 'answer', sdp) }; + toward.ws.send( + JSON.stringify({ action: 'announce', info_hash: toward.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: seal(code, 'offer', sdp) }; - ws.send(JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id: binary(), offer })); + const own = { + type: 'offer', + sdp: seal(key, 'offer', await middle.evaluate(() => (window as unknown as Hosting).middle.offer())), + }; + ws.send( + JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id: binary(), offer: own }), + ); const { msg: reply } = await first(toSender, (msg) => msg.answer); await middle.evaluate( (sdp) => (window as unknown as Hosting).middle.accept(sdp), - unseal(code, 'answer', reply.answer.sdp), + unseal(key, 'answer', reply.answer.sdp), ); } -// The salt src/core.ts derives with for a code made or entered around TEST_TIME: the start of the window -// the code's last character tells, the one nearest TEST_TIME's, then own if given. -function saltOf(code: string, own?: string) { - const now = Math.floor(TEST_TIME / SALT_WINDOW); - const cycle = CODE_CHARS.length; - const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle; - const salt = new Date((now + (ahead < cycle / 2 ? ahead : ahead - cycle)) * SALT_WINDOW).toISOString().slice(0, 16); - return own === undefined ? salt : `${salt} ${own}`; +// The key src/core.ts seals the signaling with, for a code made at TEST_TIME without an own salt: the +// salt is the start of TEST_TIME's window. src/core.test.ts checks the derivation itself. +function signalingKey(code: string) { + const master = pbkdf2Sync(code, `hellcon ${new Date(TEST_TIME).toISOString().slice(0, 16)}`, 600_000, 32, 'sha256'); + return Buffer.from(hkdfSync('sha256', master, '', 'signaling', 32)); } -// What secrets in src/core.ts derives from the code and own salt for info, PBKDF2 once per pair. -const masters = new Map(); -function secret(code: string, info: string, length: number, own?: string) { - const salt = saltOf(code, own); - const pair = JSON.stringify([code, salt]); - if (!masters.has(pair)) masters.set(pair, pbkdf2Sync(code, `hellcon ${salt}`, 600_000, 32, 'sha256')); - return Buffer.from(hkdfSync('sha256', masters.get(pair)!, '', info, length)); -} - -// The info_hash of the code with the own salt, if any. -const swarm = (code: string, own?: string) => secret(code, 'swarm', 20, own).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) { +// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with key. +function seal(key: Buffer, type: 'offer' | 'answer', sdp: string) { const iv = randomBytes(12); - const cipher = createCipheriv('aes-256-gcm', secret(code, 'signaling', 32), iv).setAAD(Buffer.from(type)); + const cipher = createCipheriv('aes-256-gcm', key, 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) { +function unseal(key: Buffer, 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)); + const decipher = createDecipheriv('aes-256-gcm', key, 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) => { - ws.onopen = resolve; - ws.onerror = reject; - }); - const binary = (bytes: Buffer) => bytes.toString('latin1'); - ws.send( - JSON.stringify({ - action: 'announce', - info_hash: swarm(code), - peer_id: binary(randomBytes(20)), - numwant: 1, - uploaded: 0, - downloaded: 0, - left: 1, - event: 'started', - offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: seal(code, 'offer', 'garbage') } }], - }), - ); - return ws; -} - -// Stands in for every tracker the page connects to from now on: reply answers each message the page -// sends, on the socket it came from. The sockets let a test send what a tracker relays from other -// peers, open counts those the page didn't close yet. They don't show up in sockets. -async function mockTrackers(page: Page, reply: (msg: Record, ws: WebSocketRoute) => object) { - const trackers = { sockets: [] as WebSocketRoute[], open: 0 }; - await page.routeWebSocket(/^wss:/, (ws) => { - trackers.sockets.push(ws); - trackers.open++; - ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data)), ws)))); - ws.onClose(() => trackers.open--); - }); - return trackers; -} - -// 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: code ? seal(code, 'offer', 'garbage') : 'garbage' }, - }); - const NO_PUBLIC = 'has no public address, between different networks both sides need STUN'; // A sender and a receiver as if on different networks, with the servers open. @@ -1815,73 +1132,6 @@ function dropHosts() { }; } -// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal -// holds one for each thing it still has to close. It runs in the hidden frames too, only the app's -// own window counts. -function countAbortListeners() { - if (window !== window.top) return; - const listeners = new Set(); - const { addEventListener, removeEventListener } = EventTarget.prototype; - const signal = AbortSignal.prototype as EventTarget; - signal.addEventListener = function (this: AbortSignal, ...args: Parameters) { - if (args[0] === 'abort') listeners.add(args[1]); - addEventListener.apply(this, args); - }; - signal.removeEventListener = function (this: AbortSignal, ...args: Parameters) { - if (args[0] === 'abort') listeners.delete(args[1]); - removeEventListener.apply(this, args); - }; - (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 expiry timers, see deadline in -// src/core.ts. It runs in the hidden frames too, only the app's own window counts. -function countDeadlines() { - if (window !== window.top) return; - const pending = new Set(); - const { setTimeout: set, clearTimeout: clear } = window; - window.setTimeout = ((handler: () => void, ms?: number) => { - if (!/\bdeadline\b.*\/src\/core\.ts/.test(new Error().stack ?? '')) return set(handler, ms); - const id = set(() => { - pending.delete(id); - handler(); - }, ms); - pending.add(id); - return id; - }) as typeof setTimeout; - window.clearTimeout = ((id?: number) => { - pending.delete(id!); - clear(id); - }) as typeof clearTimeout; - (window as unknown as { deadlines: () => number }).deadlines = () => pending.size; -} - for (const name of Object.keys(BROWSERS)) { test(`large: ${name} survives a 40 s stall`, async () => { test.skip(!process.env.LARGE, 'set LARGE=1'); diff --git a/src/core.test.ts b/src/core.test.ts index 43bc79e..6056261 100644 --- a/src/core.test.ts +++ b/src/core.test.ts @@ -1239,9 +1239,14 @@ describe('tracker signaling', () => { await until(() => FakePeer.all[0]?.channels.length); FakePeer.all[0]!.channels[0]!.drop = (data) => typeof data === 'string' && data.includes('"proof"'); await until(() => sender.logged('waiting for the security check')); + // The sender's proof still reaches it. + await until(() => silent.logged('security check passed')); vi.advanceTimersByTime(PROOF_TIMEOUT); await until(() => sender.logged('waiting for the next receiver')); expect(sender.logged('the peer proved no code')).toBe(true); + expect(sender.logged('offered')).toBe(false); + // Left without the sender, it looks again. + await until(() => silent.logged('looking again')); silent.stop(); await receiveViaTracker(code, receiver.events, receiver.signal); @@ -1282,6 +1287,8 @@ describe('tracker signaling', () => { await until(() => sender.errors.length && receiver.errors.length); expect(sender.errors).toEqual([rejected]); expect(receiver.errors).toEqual([rejected]); + // Neither keeps a timer, not even its expiry. + expect(vi.getTimerCount()).toBe(0); trackers.clear(); const lonely = side(); @@ -1317,6 +1324,42 @@ describe('tracker signaling', () => { expect(receiver.errors).toEqual([]); }); + // A tracker sees all signaling, without the code it can read none of it nor get anything answered: + // not an SDP of its own, not the receiver's sealed offer passed off as an answer. + it('seals the offers, ignores answers without the code', async () => { + const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); + settings.trackers = [URLS[0]!]; + const receiver = side(); + await receiveViaTracker('somecode123', receiver.events, receiver.signal); + await until(() => tracker.announced.length); + const [{ offer_id, offer }] = tracker.announced[0].offers; + expect(offer.sdp).not.toContain('a=fingerprint'); + expect(offer.sdp).not.toContain('candidate'); + for (const sdp of ['v=0\r\na=fingerprint:sha-256 AA\r\n', offer.sdp]) { + tracker.sockets[0]!.deliver(relayed({ offer_id, answer: { type: 'answer', sdp } })); + } + await until(() => receiver.count('answer without the code') === 2); + expect(receiver.logged('answer via')).toBe(false); + expect(FakePeer.all.map((pc) => pc.remoteDescription)).toEqual([null]); + }); + + // Trimmed and NFC, an ü typed on one system can be other bytes than on the next. + it('takes the own salt into the swarm, the share is found only with it', async () => { + const tracker = new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, other, receiver] = [side(), side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal, ' Gru\u0308ße '); + await until(() => tracker.announced.length); + expect(tracker.announced[0].info_hash).toBe((await secrets(code, codeSalt(code, 'Grüße'))).hash); + await receiveViaTracker(code, other.events, other.signal, 'Grüße!'); + await until(() => other.status()?.startsWith('retry: No sender')); + expect(other.status()).toBe( + 'retry: No sender with this code on any tracker. Check the code and the salt, still looking', + ); + await receiveViaTracker(code, receiver.events, receiver.signal, 'Grüße'); + await until(() => receiver.files[0]); + }); + // Anyone with the code can send offers no browser can parse, as many as they like. it('lets go of every unusable offer and keeps the tracker, ignores offers without the code', async () => { const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));