From 8f8270073606e97941c1b85c8d24df8bb42d2e25 Mon Sep 17 00:00:00 2001 From: Schluffe Date: Wed, 28 Oct 2026 21:05:47 +0100 Subject: [PATCH] Refactor the app --- biome.json | 55 +- e2e.spec.ts | 14 +- package.json | 5 +- playwright.config.ts | 4 + pnpm-lock.yaml | 189 ++++++ public/sw.js | 8 +- src/core.test.ts | 1462 ++++++++++++++++++++++++++++++++++++++++++ src/core.ts | 370 +++++------ src/download.ts | 155 +++++ tsconfig.json | 2 +- vite.config.ts | 3 + 11 files changed, 2032 insertions(+), 235 deletions(-) create mode 100644 playwright.config.ts create mode 100644 src/core.test.ts create mode 100644 src/download.ts diff --git a/biome.json b/biome.json index 65a6464..b8e2c65 100644 --- a/biome.json +++ b/biome.json @@ -16,8 +16,59 @@ "rules": { "preset": "recommended", "nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" }, - "style": { "noNonNullAssertion": "off", "noDescendingSpecificity": "off" }, + "style": { + "noNonNullAssertion": "off", + "noDescendingSpecificity": "off", + "noRestrictedImports": { + "level": "error", + "options": { + "paths": { + "./core": { + "message": "only src/core.test.ts imports this export of src/core.ts", + "importNames": [ + "CHUNK_SIZE", + "MAX_BUFFERED", + "WINDOW", + "TRACKER_TIMEOUT", + "CONNECT_TIMEOUT", + "MIN_INTERVAL", + "PBKDF2_ITERATIONS", + "PROOF_TIMEOUT", + "MAX_NAME", + "own", + "live", + "deadline", + "stunChoice", + "parse", + "decode", + "CODE_CHARS", + "SALT_WINDOW", + "CODE_LENGTH", + "trackerSalt", + "newCode", + "codeSalt", + "secrets", + "seal", + "unseal", + "stunHint", + "securityCheck", + "fingerprints", + "prove", + "Handshake", + "sendFile", + "receiveFile", + "trackerSocket", + "noTracker" + ] + } + } + } + } + }, "a11y": { "useSemanticElements": "off" } } - } + }, + "overrides": [ + { "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } } + ] } diff --git a/e2e.spec.ts b/e2e.spec.ts index a3aa3ac..30bf51a 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -31,7 +31,8 @@ const SIZE = 5_000_000; const LARGE_SIZE = 2.5 * 2 ** 30; // Big enough that the transfer still runs while a test cancels or disconnects. const RUNNING_SIZE = 100_000_000; -// WINDOW, PROBE_TIMEOUT, PROOF_TIMEOUT, CONNECT_TIMEOUT and DOWNLOAD_GRACE in src/core.ts. +// WINDOW, PROBE_TIMEOUT, PROOF_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; @@ -329,9 +330,12 @@ async function connect(mode: string, sender: Page, receiver: Page, source: strin if (mode === 'tracker') return proven(sender, receiver); const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent(); - await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, { - timeout: 45_000, - }); + // Each side shows ? until it has that fingerprint, the remote one can come after the local one. + for (const side of ['local', 'remote']) { + await expect(sender.locator(`#check-${side}`)).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, { + timeout: 45_000, + }); + } await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!); await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!); for (const page of [sender, receiver]) { @@ -718,7 +722,7 @@ for (const name of Object.keys(BROWSERS)) { // The edges of the chunking and the window, and a name the Content-Disposition header has to encode. for (const [what, file, size] of [ - // Read whole before the browser takes the download, see DOWNLOAD_GRACE in src/core.ts. + // Read whole before the browser takes the download, see DOWNLOAD_GRACE in src/download.ts. ['an empty file', 'empty.bin', 0], ['a one byte file', 'one.bin', 1], // Firefox would save a % as _. diff --git a/package.json b/package.json index 2859358..0f46311 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,9 @@ "typecheck": "vue-tsc", "lint": "biome check", "format": "biome check --write", - "test": "playwright test", + "test": "vitest run && playwright test", + "test:unit": "vitest", + "test:e2e": "playwright test", "test:install": "playwright install chromium firefox", "test:large": "LARGE=1 playwright test -g large" }, @@ -25,6 +27,7 @@ "@vitejs/plugin-vue": "^6.0.10", "typescript": "~6.0.3", "vite": "^8.3.5", + "vitest": "^5.0.5", "vue-tsc": "^3.3.13", "ws": "8.22.0" }, diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..ec7fa06 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,4 @@ +import { defineConfig } from '@playwright/test'; + +// src/core.test.ts is Vitest's, see vite.config.ts. Loaded by Playwright, its vi.mock fails the whole run. +export default defineConfig({ testIgnore: 'src/**' }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9e4cd31..6064d86 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -188,6 +188,9 @@ importers: vite: specifier: ^8.3.5 version: 8.3.5(@types/node@26.6.5) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)) vue-tsc: specifier: ^3.3.13 version: 3.3.13(typescript@6.0.3) @@ -283,9 +286,16 @@ packages: cpu: [x64] os: [win32] + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@oxc-project/types@0.155.0': resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} @@ -393,6 +403,15 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/node@26.6.5': resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} @@ -403,6 +422,20 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 || ^3.6.0-rc.10 + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@volar/language-core@2.4.28': resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==} @@ -450,6 +483,14 @@ packages: alien-signals@3.2.1: resolution: {integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==} + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} @@ -461,9 +502,19 @@ packages: resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} engines: {node: '>=0.12'} + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + estree-walker@2.0.2: resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -555,6 +606,9 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + muggle-string@0.4.1: resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} @@ -563,6 +617,10 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + path-browserify@1.0.1: resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} @@ -596,6 +654,17 @@ packages: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@6.2.2: + resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -651,6 +720,47 @@ packages: yaml: optional: true + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + vscode-uri@3.2.0: resolution: {integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==} @@ -668,6 +778,11 @@ packages: typescript: optional: true + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + ws@8.22.0: resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} engines: {node: '>=10.0.0'} @@ -738,8 +853,15 @@ snapshots: '@biomejs/cli-win32-x64@2.6.3': optional: true + '@jridgewell/resolve-uri@3.1.2': {} + '@jridgewell/sourcemap-codec@1.6.0': {} + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + '@oxc-project/types@0.155.0': {} '@playwright/test@1.64.1': @@ -793,6 +915,15 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + '@types/node@26.6.5': dependencies: undici-types: 8.9.0 @@ -803,6 +934,17 @@ snapshots: vite: 8.3.5(@types/node@26.6.5) vue: 3.5.44(typescript@6.0.3) + '@vitest/mocker@5.0.5(vite@8.3.5(@types/node@26.6.5))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.5(@types/node@26.6.5) + + '@vitest/spy@5.0.5': {} + '@volar/language-core@2.4.28': dependencies: '@volar/source-map': 2.4.28 @@ -883,14 +1025,26 @@ snapshots: alien-signals@3.2.1: {} + assertion-error@2.0.1: {} + + chai@6.3.0: {} + csstype@3.2.3: {} detect-libc@2.1.2: {} entities@7.0.1: {} + es-module-lexer@2.3.2: {} + estree-walker@2.0.2: {} + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -951,10 +1105,16 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + muggle-string@0.4.1: {} nanoid@3.3.20: {} + obug@3.0.0: {} + path-browserify@1.0.1: {} picocolors@1.1.1: {} @@ -996,6 +1156,12 @@ snapshots: source-map-js@1.2.2: {} + std-env@4.3.0: {} + + tinybench@6.2.2: {} + + tinyexec@1.3.1: {} + tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) @@ -1016,6 +1182,27 @@ snapshots: '@types/node': 26.6.5 fsevents: 2.3.3 + vitest@5.0.5(@types/node@26.6.5)(vite@8.3.5(@types/node@26.6.5)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.5(@types/node@26.6.5)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@26.6.5) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.5 + transitivePeerDependencies: + - msw + vscode-uri@3.2.0: {} vue-tsc@3.3.13(typescript@6.0.3): @@ -1034,4 +1221,6 @@ snapshots: optionalDependencies: typescript: 6.0.3 + why-is-node-running@3.2.1: {} + ws@8.22.0: {} diff --git a/public/sw.js b/public/sw.js index f1d719a..a24b7a6 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,6 +1,6 @@ // Streams received files into the browser's download manager. It is the only script besides the app // because service workers can only be registered from a same-origin script URL. Registered with the -// scope download/ by src/core.ts, it sees no other requests. +// scope download/ by src/download.ts, its counterpart in the page, it sees no other requests. // Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the // reply port and how many bytes the download manager has read. @@ -22,7 +22,7 @@ function open(id, { name, size }, port) { const chunk = download.chunks.shift(); if (chunk) { download.read += chunk.byteLength; - // Every MiB, src/core.ts forwards it to the sender for its flow control window. + // Every MiB, the receiver forwards it to the sender for its flow control window. if (download.read - download.reported >= 2 ** 20) { download.reported = download.read; port.postMessage(download.read); @@ -60,7 +60,7 @@ function open(id, { name, size }, port) { // The page posts the metadata with a reply port first, then every chunk as its own message and // finally done (queued as the end marker null) or an error. Pings come in between. self.addEventListener('message', ({ data, ports: [port] }) => { - // Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/core.ts. + // Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/download.ts. if (data.ping) return; if (port) return open(data.id, data, port); const download = downloads.get(data.id); @@ -77,7 +77,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => { self.addEventListener('fetch', (event) => { const id = new URL(event.request.url).pathname.split('/').pop(); - // download/ itself is the empty page src/core.ts keeps open to hold this worker during a transfer. + // download/ itself is the empty page src/download.ts keeps open to hold this worker during a transfer. if (!id) return event.respondWith( new Response('', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }), diff --git a/src/core.test.ts b/src/core.test.ts new file mode 100644 index 0000000..43bc79e --- /dev/null +++ b/src/core.test.ts @@ -0,0 +1,1462 @@ +// The core on its own, in Node without browsers: the protocol, the transfer and both kinds of +// signaling, on fake connections, tracker sockets and timers in memory. e2e.spec.ts covers what only +// browsers can tell: real WebRTC, the service worker and the network. +import { createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto'; +import { getEventListeners } from 'node:events'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + answerOffer, + CHUNK_SIZE, + type Check, + CODE_CHARS, + CODE_LENGTH, + CONNECT_TIMEOUT, + codeSalt, + createOffer, + DEFAULT_STUN_SERVERS, + deadline, + decode, + fingerprints, + type Incoming, + live, + MAX_BUFFERED, + MAX_NAME, + MIN_INTERVAL, + newCode, + noTracker, + own, + PBKDF2_ITERATIONS, + PROOF_TIMEOUT, + parse, + prove, + type ReceiveEvents, + randomCode, + receiveFile, + receiveViaTracker, + SALT_WINDOW, + type SendEvents, + seal, + secrets, + securityCheck, + sendFile, + sendViaTracker, + settings, + stunChoice, + stunHint, + TRACKER_TIMEOUT, + TRACKER_WAIT, + trackerSalt, + trackerSocket, + unseal, + WINDOW, +} from './core'; +import type { Download, DownloadEvents } from './download'; + +// The receiver saves into memory instead of the service worker, see saveInMemory. +vi.mock('./download', () => ({ + downloadsReady: async () => {}, + startDownload: (file: { name: string; size: number }, events: DownloadEvents) => saveInMemory(file, events), +})); + +// A second into the window from 12:00 to 12:06 UTC, so every code made now has the same salt. +const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1); + +// biome-ignore lint/suspicious/noExplicitAny: messages and handlers of the fakes, the tests read what they need +type Any = any; + +// The browser's on properties: a handler listens in the place where it was first set. +class Target extends EventTarget { + #handlers = new Map unknown) | null>(); + protected on(type: string, handler: ((event: Any) => unknown) | null) { + if (!this.#handlers.has(type)) this.addEventListener(type, (event) => this.#handlers.get(type)?.(event)); + this.#handlers.set(type, handler); + } + emit(type: string, props: object = {}) { + this.dispatchEvent(Object.assign(new Event(type), props)); + } +} + +// A data channel. Connected, what one side sends arrives a moment later at the other, also when this +// side closes right after: a channel sends what it buffered first. +class FakeChannel extends Target { + readyState: RTCDataChannelState = 'connecting'; + bufferedAmount = 0; + bufferedAmountLowThreshold = 0; + binaryType: BinaryType = 'blob'; + // Everything this side sent. + sent: (string | ArrayBuffer)[] = []; + peer?: FakeChannel; + // What this side drops instead of sending. + drop = (_data: string | ArrayBuffer) => false; + constructor(readonly label = 'file') { + super(); + } + set onopen(handler: ((event: Any) => unknown) | null) { + this.on('open', handler); + } + set onmessage(handler: ((event: Any) => unknown) | null) { + this.on('message', handler); + } + send(data: string | ArrayBuffer) { + if (this.readyState !== 'open') throw new DOMException('not open', 'InvalidStateError'); + if (this.drop(data)) return; + this.sent.push(data); + const { peer } = this; + const copy = typeof data === 'string' ? data : data.slice(0); + if (peer) setImmediate(() => peer.readyState === 'open' && peer.emit('message', { data: copy })); + } + // What the peer sends, arriving right away. An object as JSON. + receive(data: object | string | ArrayBuffer) { + const message = typeof data === 'string' || data instanceof ArrayBuffer ? data : JSON.stringify(data); + this.emit('message', { data: message }); + } + open() { + this.readyState = 'open'; + this.emit('open'); + } + close() { + if (this.readyState === 'closed') return; + this.readyState = 'closed'; + setImmediate(() => this.emit('close')); + const { peer } = this; + if (peer && peer !== this) setImmediate(() => peer.close()); + } + // The JSON messages this side sent. + json() { + return this.sent.filter((data) => typeof data === 'string').map((data) => JSON.parse(data)); + } + // How many bytes of binary messages this side sent. + bytes() { + return this.sent.reduce((sum, data) => sum + (typeof data === 'string' ? 0 : data.byteLength), 0); + } +} + +const named = (description: RTCSessionDescriptionInit | null) => + description?.sdp?.match(/a=fingerprint:\S+ (\S+)/)?.[1]; + +// A peer connection. Two connect in memory once each has the other's description, unless the test +// keeps them apart. Its SDP has a fingerprint of its own, and a public address with a STUN server. +class FakePeer extends Target { + static all: FakePeer[] = []; + static reachable = true; + readonly fingerprint = Array.from(randomBytes(32), (byte) => byte.toString(16).padStart(2, '0')) + .join(':') + .toUpperCase(); + localDescription: RTCSessionDescriptionInit | null = null; + remoteDescription: RTCSessionDescriptionInit | null = null; + signalingState: RTCSignalingState = 'stable'; + iceGatheringState: RTCIceGatheringState = 'new'; + connectionState: RTCPeerConnectionState = 'new'; + channels: FakeChannel[] = []; + constructor(readonly config: RTCConfiguration = {}) { + super(); + FakePeer.all.push(this); + } + set ondatachannel(handler: ((event: Any) => unknown) | null) { + this.on('datachannel', handler); + } + getConfiguration() { + return this.config; + } + createDataChannel(label: string) { + const channel = new FakeChannel(label); + this.channels.push(channel); + return channel; + } + async setLocalDescription() { + if (this.signalingState === 'closed') throw new DOMException('closed', 'InvalidStateError'); + const type = this.signalingState === 'have-remote-offer' ? 'answer' : 'offer'; + const srflx = this.config.iceServers?.length ? 'a=candidate:2 1 udp 1 203.0.113.5 50000 typ srflx\r\n' : ''; + const host = 'a=candidate:1 1 udp 2 192.168.0.2 50000 typ host\r\n'; + this.localDescription = { type, sdp: `v=0\r\na=fingerprint:sha-256 ${this.fingerprint}\r\n${host}${srflx}` }; + this.signalingState = type === 'offer' ? 'have-local-offer' : 'stable'; + this.iceGatheringState = 'complete'; + this.link(); + } + async setRemoteDescription({ type, sdp }: RTCSessionDescriptionInit) { + if (this.signalingState === 'closed') throw new DOMException('closed', 'InvalidStateError'); + if (!sdp?.startsWith('v=0\r\n') || !named({ type, sdp })) throw new DOMException('no SDP', 'OperationError'); + if (this.signalingState !== (type === 'answer' ? 'have-local-offer' : 'stable')) { + throw new DOMException('wrong state', 'InvalidStateError'); + } + this.remoteDescription = { type, sdp }; + this.signalingState = type === 'offer' ? 'have-remote-offer' : 'stable'; + this.link(); + } + close() { + if (this.signalingState === 'closed') return; + this.signalingState = 'closed'; + this.connectionState = 'closed'; + // Without events on this side, the other one's channels close. + for (const channel of this.channels) { + channel.readyState = 'closed'; + const { peer } = channel; + if (peer) setImmediate(() => peer.close()); + } + } + // The connection's state changed to state. + state(state: RTCPeerConnectionState) { + this.connectionState = state; + this.emit('connectionstatechange'); + } + private link() { + const other = FakePeer.all.find((peer) => peer !== this && peer.fingerprint === named(this.remoteDescription)); + if (!other || named(other.remoteDescription) !== this.fingerprint || !FakePeer.reachable) return; + if (!this.localDescription || !other.localDescription) return; + const [offerer, answerer] = this.localDescription.type === 'offer' ? [this, other] : [other, this]; + setImmediate(() => { + if (offerer.signalingState === 'closed' || answerer.signalingState === 'closed') return; + offerer.state('connected'); + answerer.state('connected'); + for (const channel of offerer.channels) { + const end = new FakeChannel(channel.label); + answerer.channels.push(end); + channel.peer = end; + end.peer = channel; + answerer.emit('datachannel', { channel: end }); + end.open(); + channel.open(); + } + }); + } +} + +const trackers = new Map(); + +// A tracker socket, to the FakeTracker of its URL. Without one the URL is unreachable. +class FakeSocket extends Target { + static all: FakeSocket[] = []; + readyState = 0; + constructor(readonly url: string) { + super(); + FakeSocket.all.push(this); + setImmediate(() => { + if (this.readyState) return; + const tracker = trackers.get(url); + this.readyState = tracker ? 1 : 3; + if (!tracker) return this.emit('close'); + tracker.sockets.push(this); + this.emit('open'); + }); + } + set onopen(handler: ((event: Any) => unknown) | null) { + this.on('open', handler); + } + send(data: string) { + if (this.readyState !== 1) throw new DOMException('not open', 'InvalidStateError'); + const msg = JSON.parse(data); + setImmediate(() => trackers.get(this.url)?.receive(this, msg)); + } + close() { + if (this.readyState >= 2) return; + this.readyState = 2; + trackers.get(this.url)?.forget(this); + setImmediate(() => { + this.readyState = 3; + this.emit('close'); + }); + } + // What the tracker sends. + deliver(msg: object) { + if (this.readyState === 1) this.emit('message', { data: JSON.stringify(msg) }); + } + // The tracker closed it. + drop() { + if (this.readyState >= 2) return; + this.readyState = 3; + trackers.get(this.url)?.forget(this); + this.emit('close'); + } +} + +// A WebTorrent tracker in memory at url: it relays the offers in a swarm and the answers back, and +// answers announcements with the swarm's seeders. reply takes over the answer: what it returns goes +// back, nothing relayed, undefined is no answer. +class FakeTracker { + sockets: FakeSocket[] = []; + // Everything announced to it. + announced: Any[] = []; + swarms = new Map>(); + constructor( + readonly url: string, + public reply?: (msg: Any, socket: FakeSocket) => object | undefined, + ) { + trackers.set(url, this); + } + receive(socket: FakeSocket, msg: Any) { + if (socket.readyState !== 1) return; + this.announced.push(msg); + if (this.reply) { + const reply = this.reply(msg, socket); + if (reply) socket.deliver(reply); + return; + } + const { info_hash, peer_id } = msg; + const swarm = this.swarms.get(info_hash) ?? new Map(); + this.swarms.set(info_hash, swarm); + swarm.set(peer_id, { socket, seeder: msg.left === 0 }); + if (msg.answer) { + const answer = { action: 'announce', info_hash, peer_id, offer_id: msg.offer_id, answer: msg.answer }; + return swarm.get(msg.to_peer_id)?.socket.deliver(answer); + } + const complete = [...swarm.values()].filter((peer) => peer.seeder).length; + socket.deliver({ action: 'announce', interval: 120, info_hash, complete, incomplete: swarm.size - complete }); + const others = [...swarm].filter(([id]) => id !== peer_id); + for (const { offer_id, offer } of msg.offers ?? []) { + for (const [, peer] of others) peer.socket.deliver({ action: 'announce', info_hash, peer_id, offer_id, offer }); + } + } + forget(socket: FakeSocket) { + for (const swarm of this.swarms.values()) { + for (const [id, peer] of swarm) if (peer.socket === socket) swarm.delete(id); + } + } + // Its sockets still open. + open() { + return this.sockets.filter((socket) => socket.readyState === 1); + } +} + +// What the mocked src/download.ts saved, newest last. Unless autoSave is off, the download manager +// reads each chunk right away, reports that every MiB like public/sw.js and finishes once ended. +// Like startDownload, nothing comes once failed, the tests calling events themselves aside. +type Saved = { file: { name: string; size: number }; events: DownloadEvents; chunks: Uint8Array[]; ended: boolean }; +const saved: (Saved & { failed?: string })[] = []; +let autoSave = true; + +function saveInMemory(file: { name: string; size: number }, events: DownloadEvents): Download { + const download: Saved & { failed?: string } = { file, events, chunks: [], ended: false }; + saved.push(download); + let read = 0; + let reported = 0; + return { + write: (chunk) => { + download.chunks.push(new Uint8Array(chunk)); + read += chunk.byteLength; + if (!autoSave || read - reported < 2 ** 20) return; + reported = read; + const bytes = read; + setImmediate(() => download.failed === undefined && events.read(bytes)); + }, + end: () => { + download.ended = true; + if (autoSave) setImmediate(() => download.failed === undefined && events.finished()); + }, + fail: (reason) => { + download.failed = reason; + }, + }; +} + +// A digest to compare files by, toEqual on megabytes takes seconds. +const digest = (bytes: Uint8Array | ArrayBuffer) => createHash('sha256').update(new Uint8Array(bytes)).digest('hex'); +const savedDigest = (download: Saved) => digest(Buffer.concat(download.chunks)); +const fileDigest = async (source: File) => digest(await source.arrayBuffer()); + +// A session's events, kept to check them, and its signal. Every one ends after its test. +const sessions: AbortController[] = []; +function side() { + const controller = new AbortController(); + sessions.push(controller); + const seen = { + signal: controller.signal, + stop: () => controller.abort(), + logs: [] as string[], + statuses: [] as string[], + errors: [] as string[], + checks: [] as (Check | undefined)[], + files: [] as (Incoming | undefined)[], + progress: [] as number[], + expired: false, + logged: (text: string) => seen.logs.some((line) => line.includes(text)), + count: (text: string) => seen.logs.filter((line) => line.includes(text)).length, + status: () => seen.statuses.at(-1), + }; + const events: SendEvents & ReceiveEvents = { + log: (message) => seen.logs.push(message), + status: (phase, text) => seen.statuses.push(`${phase}: ${text}`), + error: (message) => seen.errors.push(message), + check: (check) => seen.checks.push(check), + progress: (read) => seen.progress.push(read), + incoming: (file) => seen.files.push(file), + expired: () => (seen.expired = true), + }; + return Object.assign(seen, { events }); +} + +// Lets the fakes and real asynchronous work, Web Crypto above all, go on until check passes. The fake +// timers only move when a test says so. +async function until(check: () => unknown, ms = 5000) { + const end = performance.now() + ms; + while (!check()) { + if (performance.now() > end) throw new Error(`timed out: ${check}`); + await new Promise((resolve) => setImmediate(resolve)); + } +} + +// Gives everything that is under way a few turns, enough for nothing more to happen. +const settle = async () => { + for (let turn = 0; turn < 20; turn++) await new Promise((resolve) => setImmediate(resolve)); +}; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => (resolve = done)); + return { promise, resolve }; +} + +const file = (size: number, name = 'payload.bin') => new File([randomBytes(size)], name); +const openPeers = () => FakePeer.all.filter((pc) => pc.signalingState !== 'closed'); +const openSockets = () => FakeSocket.all.filter((ws) => ws.readyState < 2); +const asPeer = (pc: FakePeer) => pc as unknown as RTCPeerConnection; +const asChannel = (channel: FakeChannel) => channel as unknown as RTCDataChannel; + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'], now: TEST_TIME }); + vi.stubGlobal('RTCPeerConnection', FakePeer); + vi.stubGlobal('WebSocket', FakeSocket); + Object.assign(settings, { stun: false, stunServers: [...DEFAULT_STUN_SERVERS], trackers: [] }); + FakePeer.all = []; + FakePeer.reachable = true; + FakeSocket.all = []; + trackers.clear(); + saved.length = 0; + autoSave = true; +}); + +afterEach(async () => { + for (const session of sessions.splice(0)) session.abort(); + await settle(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('codes and salts', () => { + it('makes codes of the 62 characters, each equally likely', () => { + const counts = new Map(); + for (const char of randomCode(62_000)) counts.set(char, (counts.get(char) ?? 0) + 1); + expect([...counts.keys()].sort()).toEqual([...CODE_CHARS].sort()); + for (const count of counts.values()) expect(count).toBeGreaterThan(800); + }); + + it("ends a code with its window, a receiver's clock hours off still finds its salt", () => { + const { code, salt } = newCode(); + expect(code).toMatch(new RegExp(`^[0-9a-zA-Z]{${CODE_LENGTH}}$`)); + expect(salt).toBe('2026-01-01T12:00'); + for (const hours of [-3, -1, 0, 1, 3]) { + vi.setSystemTime(TEST_TIME + hours * 3_600_000); + expect(codeSalt(code)).toBe(salt); + } + // Half the characters' windows away it still does, one more and it takes the next cycle's. + vi.setSystemTime(TEST_TIME + (CODE_CHARS.length / 2) * SALT_WINDOW); + expect(codeSalt(code)).toBe(salt); + vi.setSystemTime(TEST_TIME + (CODE_CHARS.length / 2 + 1) * SALT_WINDOW); + expect(codeSalt(code)).not.toBe(salt); + }); + + it('adds an own salt trimmed, refuses a blank one', () => { + const at = Math.floor(TEST_TIME / SALT_WINDOW); + expect(trackerSalt(at, ' Grüße ')).toBe('2026-01-01T12:00 Grüße'); + expect(() => trackerSalt(at, ' ')).toThrow('the own salt is empty'); + expect(newCode('own').salt).toBe('2026-01-01T12:00 own'); + }); + + it("refuses what can't be a code", () => { + for (const code of ['abcdefghij', 'abcdefghijkl', 'abcdefghij-', 'abcdefghijü']) { + expect(() => codeSalt(code)).toThrow('a code has 11 letters and digits, check it'); + } + }); + + // The protocol in node:crypto, independent of Web Crypto: changing it splits old and new clients. + it('derives the swarm and the sealing key as the protocol says, the salt in NFC', async () => { + const code = 'abcdefghijk'; + const salt = '2026-01-01T12:00 Grüße'; + const master = pbkdf2Sync(code, `hellcon ${salt}`, PBKDF2_ITERATIONS, 32, 'sha256'); + const expand = (info: string, length: number) => Buffer.from(hkdfSync('sha256', master, '', info, length)); + const { hash, sealing } = await secrets(code, salt.normalize('NFD')); + expect(Buffer.from(hash, 'latin1')).toEqual(expand('swarm', 20)); + + const sealed = Buffer.from(await seal(sealing, 'offer', 'the sdp'), 'base64'); + const decipher = createDecipheriv('aes-256-gcm', expand('signaling', 32), sealed.subarray(0, 12)); + decipher.setAAD(Buffer.from('offer')).setAuthTag(sealed.subarray(-16)); + expect(Buffer.concat([decipher.update(sealed.subarray(12, -16)), decipher.final()]).toString()).toBe('the sdp'); + }); + + it('opens only what was sealed with the key as that type', async () => { + const [{ sealing }, other] = await Promise.all([secrets('abcdefghijk', 'salt'), secrets('abcdefghijl', 'salt')]); + const sealed = await seal(sealing, 'offer', 'the sdp'); + expect(await unseal(sealing, 'offer', sealed)).toBe('the sdp'); + expect(await unseal(sealing, 'answer', sealed)).toBeUndefined(); + expect(await unseal(other.sealing, 'offer', sealed)).toBeUndefined(); + expect(await unseal(sealing, 'offer', 'not base64!')).toBeUndefined(); + const bytes = Buffer.from(sealed, 'base64'); + bytes[20]! ^= 1; + expect(await unseal(sealing, 'offer', bytes.toString('base64'))).toBeUndefined(); + }); +}); + +describe('messages', () => { + it('reads only JSON objects', () => { + expect(parse('{"ok":true}')).toEqual({ ok: true }); + for (const data of ['null', '1', '"text"', '{', undefined, new ArrayBuffer(2)]) expect(parse(data)).toBeUndefined(); + }); + + it('reads manual codes wrapped by a chat, tells a broken one', () => { + const code = btoa('v=0\r\nsdp'); + expect(decode(`${code.slice(0, 4)}\n ${code.slice(4)} `, 'offer')).toEqual({ type: 'offer', sdp: 'v=0\r\nsdp' }); + expect(() => decode('not base64!', 'answer')).toThrow('not a valid answer, copy all of it'); + }); + + it('counts every fingerprint once, at session or media level', () => { + const sdp = + 'v=0\r\na=fingerprint:sha-256 AB:CD\r\nm=application\r\na=fingerprint:SHA-256 ab:cd\r\na=fingerprint:sha-1 01\r\n'; + expect(fingerprints(sdp)).toEqual(['sha-1 01', 'sha-256 ab:cd']); + }); + + it('shows the first 8 bytes of both fingerprints for the check', () => { + const sdp = (fingerprint: string) => ({ sdp: `v=0\r\na=fingerprint:sha-256 ${fingerprint}\r\n` }); + const pc = { + localDescription: sdp('aa:bb:cc:dd:ee:ff:00:11:22:33'), + remoteDescription: sdp('01:02:03:04:05:06:07:08:09'), + } as RTCPeerConnection; + expect(securityCheck(pc)).toEqual({ local: 'AA BB CC DD EE FF 00 11', remote: '01 02 03 04 05 06 07 08' }); + expect(securityCheck({ localDescription: null, remoteDescription: null } as RTCPeerConnection)).toEqual({ + local: '?', + remote: '?', + }); + }); + + it('names the side without a public address', () => { + const sdp = (srflx: boolean) => ({ sdp: srflx ? 'a=candidate:2 1 udp 1 203.0.113.5 5 typ srflx\r\n' : '' }); + const hint = (local: boolean, remote: boolean) => + stunHint({ localDescription: sdp(local), remoteDescription: sdp(remote) } as RTCPeerConnection, 'receiver'); + const need = ', between different networks both sides need STUN'; + expect(hint(true, true)).toBeUndefined(); + expect(hint(true, false)).toBe(`the receiver has no public address${need}`); + expect(hint(false, true)).toBe(`this side has no public address${need}`); + expect(hint(false, false)).toBe(`neither side has a public address${need}`); + }); + + it('tells why no tracker is left', () => { + const rejected = (reason?: string) => ({ rejected: reason }) as Parameters[0][number]; + expect(noTracker([rejected(), undefined])).toBe('no tracker reachable, check the list under Servers and try again'); + expect(noTracker([rejected('a: no'), rejected(), rejected('b: full')])).toBe( + 'no tracker accepted it (a: no; b: full), check the list under Servers and try again', + ); + }); +}); + +describe('session lifetime', () => { + it('closes what a session owns once it ends, lets go of what closed before', () => { + const session = new AbortController(); + const [kept, closed, late] = [vi.fn(), vi.fn(), vi.fn()]; + own(session.signal, { close: kept }); + own(session.signal, { close: closed }).close(); + expect(closed).toHaveBeenCalledTimes(1); + expect(getEventListeners(session.signal, 'abort')).toHaveLength(1); + session.abort(); + expect(kept).toHaveBeenCalledTimes(1); + own(session.signal, { close: late }); + expect(late).toHaveBeenCalledTimes(1); + }); + + it('expires once after ms, not after the session ended', () => { + const session = new AbortController(); + const expire = vi.fn(); + deadline(session.signal, expire, 1000); + vi.advanceTimersByTime(999); + expect(expire).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(expire).toHaveBeenCalledTimes(1); + expect(getEventListeners(session.signal, 'abort')).toHaveLength(0); + + deadline(session.signal, expire, 1000); + session.abort(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('calls no more events once the session ended', () => { + const session = new AbortController(); + const log = vi.fn(); + const events = live({ log }, session.signal); + events.log('before'); + session.abort(); + events.log('after'); + expect(log.mock.calls).toEqual([['before']]); + }); +}); + +describe('STUN servers', () => { + // A probe each test answers itself, the servers asked in order. + function prober() { + const asked: { url: string; answer: (ok: boolean) => void; stopped: AbortSignal }[] = []; + const probe = (url: string, stopped: AbortSignal) => + new Promise((answer) => asked.push({ url, answer, stopped })); + return { asked, choice: stunChoice(probe), urls: () => asked.map(({ url }) => url) }; + } + + beforeEach(() => Object.assign(settings, { stun: true, stunServers: ['stun:a', 'stun:b', 'stun:c'] })); + + it('takes the first server that answers and keeps it, the next one once it gave no address', async () => { + const { asked, choice, urls } = prober(); + const session = new AbortController(); + const first = choice.server(session.signal); + await until(() => asked.length === 1); + asked[0]!.answer(false); + await until(() => asked.length === 2); + asked[1]!.answer(true); + expect(await first).toBe('stun:b'); + expect(await choice.server(session.signal)).toBe('stun:b'); + expect(urls()).toEqual(['stun:a', 'stun:b']); + + await choice.failed('stun:b'); + const next = choice.server(session.signal); + await until(() => asked.length === 3); + expect(asked[2]!.url).toBe('stun:c'); + asked[2]!.answer(false); + // Around to the start of the list. + await until(() => asked.length === 4); + expect(asked[3]!.url).toBe('stun:a'); + asked[3]!.answer(true); + expect(await next).toBe('stun:a'); + }); + + it('starts over when the list changed, uses none without STUN or servers', async () => { + const { asked, choice } = prober(); + const session = new AbortController(); + const first = choice.server(session.signal); + await until(() => asked.length === 1); + asked[0]!.answer(true); + expect(await first).toBe('stun:a'); + settings.stunServers = ['stun:x', 'stun:a']; + const changed = choice.server(session.signal); + await until(() => asked.length === 2); + expect(asked[1]!.url).toBe('stun:x'); + asked[1]!.answer(true); + expect(await changed).toBe('stun:x'); + + settings.stun = false; + expect(await choice.server(session.signal)).toBeUndefined(); + settings.stun = true; + settings.stunServers = []; + expect(await choice.server(session.signal)).toBeUndefined(); + }); + + it('stops probing once no session waits, the next probe goes on from there', async () => { + const { asked, choice } = prober(); + const [one, two] = [new AbortController(), new AbortController()]; + void choice.server(one.signal); + void choice.server(two.signal); + await until(() => asked.length === 1); + asked[0]!.answer(false); + await until(() => asked.length === 2); + one.abort(); + expect(asked[1]!.stopped.aborted).toBe(false); + two.abort(); + expect(asked[1]!.stopped.aborted).toBe(true); + asked[1]!.answer(false); + await settle(); + expect(asked).toHaveLength(2); + + // At the one it stopped at, that one never got to answer. + const three = new AbortController(); + const resumed = choice.server(three.signal); + await until(() => asked.length === 3); + expect(asked[2]!.url).toBe('stun:b'); + asked[2]!.answer(true); + expect(await resumed).toBe('stun:b'); + }); + + it('contacts no further server once STUN was turned off', async () => { + const { asked, choice } = prober(); + const session = new AbortController(); + const server = choice.server(session.signal); + await until(() => asked.length === 1); + settings.stun = false; + asked[0]!.answer(false); + expect(await server).toBeUndefined(); + expect(asked).toHaveLength(1); + }); +}); + +describe('tracker socket', () => { + // A socket to url on the session, with what it reported. + function socket(url = 'wss://one.test') { + const session = side(); + const got: Any[] = []; + const lost = vi.fn(); + const again = vi.fn(); + const tracker = trackerSocket(url, session.signal, session.events, (msg) => void got.push(msg), lost, again); + return { session, tracker, got, lost, again }; + } + + it('reports an unreachable tracker once', async () => { + const { session, lost } = socket(); + await until(() => lost.mock.calls.length); + await settle(); + expect(lost).toHaveBeenCalledTimes(1); + expect(session.logs).toEqual(['wss://one.test unreachable']); + }); + + it('gives up on a tracker that never answers', async () => { + new FakeTracker('wss://one.test', () => undefined); + const { session, tracker, lost } = socket(); + await until(() => tracker.ws.readyState === 1); + tracker.ws.send('{}'); + vi.advanceTimersByTime(TRACKER_TIMEOUT); + expect(session.logs).toEqual(['wss://one.test did not answer']); + expect(lost).toHaveBeenCalledTimes(1); + expect(tracker.ws.readyState).toBeGreaterThanOrEqual(2); + }); + + it('takes a failure before anything else for a rejection, after that only logs it', async () => { + new FakeTracker('wss://one.test', () => ({ 'failure reason': 'not here' })); + const rejected = socket(); + await until(() => rejected.tracker.ws.readyState === 1); + rejected.tracker.ws.send('{}'); + await until(() => rejected.lost.mock.calls.length); + expect(rejected.tracker.rejected).toBe('wss://one.test: not here'); + expect(rejected.session.logs).toEqual(['rejected by wss://one.test: not here']); + expect(rejected.tracker.alive()).toBe(false); + + new FakeTracker('wss://two.test', () => ({ action: 'announce' })); + const accepted = socket('wss://two.test'); + await until(() => accepted.tracker.ws.readyState === 1); + accepted.tracker.ws.send('{}'); + await until(() => accepted.got.length); + (accepted.tracker.ws as unknown as FakeSocket).deliver({ 'failure reason': 'slow down' }); + (accepted.tracker.ws as unknown as FakeSocket).deliver({ 'not json': undefined }); + expect(accepted.session.logs).toEqual(['wss://two.test: slow down']); + expect(accepted.tracker.alive()).toBe(true); + expect(accepted.lost).not.toHaveBeenCalled(); + }); + + it('announces again on the interval it names, at least MIN_INTERVAL, at most TRACKER_WAIT', async () => { + for (const [interval, every] of [ + [0, MIN_INTERVAL], + [120, 120_000], + ['1e999', TRACKER_WAIT], + ] as const) { + const url = `wss://${interval}.test`; + new FakeTracker(url); + const { tracker, again } = socket(url); + await until(() => tracker.ws.readyState === 1); + (tracker.ws as unknown as FakeSocket).emit('message', { data: `{"interval":${interval}}` }); + vi.advanceTimersByTime(every - 1); + expect(again).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(again).toHaveBeenCalledTimes(1); + tracker.close(); + } + expect(vi.getTimerCount()).toBe(0); + }); + + it('closes without reporting it lost, and with the session', async () => { + new FakeTracker('wss://one.test'); + const closed = socket(); + closed.tracker.close(); + await settle(); + expect(closed.lost).not.toHaveBeenCalled(); + expect(closed.session.logs).toEqual([]); + + const ended = socket(); + await until(() => ended.tracker.ws.readyState === 1); + ended.session.stop(); + await settle(); + expect(ended.tracker.alive()).toBe(false); + expect(ended.lost).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); +}); + +describe('proof of the code', () => { + const key = () => + crypto.subtle.importKey('raw', randomBytes(32), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']); + const sdp = (fingerprint: string) => `v=0\r\na=fingerprint:sha-256 ${fingerprint}\r\n`; + // One side of a connection as it sees it: its own SDP of type and the peer's. + const view = (type: 'offer' | 'answer', local: string, remote: string) => + ({ + localDescription: { type, sdp: sdp(local) }, + remoteDescription: { type: type === 'offer' ? 'answer' : 'offer', sdp: sdp(remote) }, + }) as RTCPeerConnection; + + function pair() { + const [a, b] = [new FakeChannel(), new FakeChannel()]; + a.peer = b; + b.peer = a; + a.readyState = b.readyState = 'open'; + return [a, b] as const; + } + + it('passes on both sides with the same key and the same certificates', async () => { + const shared = await key(); + const [a, b] = pair(); + const end = vi.fn(); + // Sent once the channel opens. + a.readyState = 'connecting'; + const proven = Promise.all([ + prove(view('offer', 'AA', 'BB'), asChannel(a), shared, end), + prove(view('answer', 'BB', 'AA'), asChannel(b), shared, end), + ]); + a.open(); + await proven; + expect(end).not.toHaveBeenCalled(); + }); + + it('fails with another key, other certificates or a proof sent back', async () => { + const shared = await key(); + for (const [views, keys] of [ + [ + [view('offer', 'AA', 'BB'), view('answer', 'BB', 'AA')], + [shared, await key()], + ], + // A man in the middle with its own certificate towards each side. + [ + [view('offer', 'AA', 'M1'), view('answer', 'BB', 'M2')], + [shared, shared], + ], + ] as const) { + const [a, b] = pair(); + const ends = [vi.fn(), vi.fn()]; + void prove(views[0], asChannel(a), keys[0], ends[0]!); + void prove(views[1], asChannel(b), keys[1], ends[1]!); + await until(() => ends.every((end) => end.mock.calls.length)); + for (const end of ends) + expect(end).toHaveBeenCalledWith('security check failed, the peer does not know the code'); + } + + const reflecting = new FakeChannel(); + reflecting.peer = reflecting; + reflecting.readyState = 'open'; + const end = vi.fn(); + void prove(view('offer', 'AA', 'BB'), asChannel(reflecting), shared, end); + await until(() => end.mock.calls.length); + expect(end).toHaveBeenCalledWith('security check failed, the peer does not know the code'); + }); + + it('gives up on a peer that proves nothing within PROOF_TIMEOUT', async () => { + const [a] = pair(); + const end = vi.fn(); + void prove(view('offer', 'AA', 'BB'), asChannel(a), await key(), end); + vi.advanceTimersByTime(PROOF_TIMEOUT - 1); + expect(end).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(end).toHaveBeenCalledWith('the peer proved no code'); + }); + + // The transfer listens after it and would take the proof for an offer. + it('keeps the proof from the listeners after it', async () => { + const shared = await key(); + const [a, b] = pair(); + const later = vi.fn(); + const proven = prove(view('answer', 'BB', 'AA'), asChannel(b), shared, vi.fn()); + b.addEventListener('message', later); + void prove(view('offer', 'AA', 'BB'), asChannel(a), shared, vi.fn()); + await proven; + expect(later).not.toHaveBeenCalled(); + }); +}); + +describe('sending', () => { + // A transfer of file on a connection whose handshake passes once check is called. + function sending(source: File) { + const pc = new FakePeer(); + const channel = new FakeChannel(); + channel.readyState = 'open'; + const checked = deferred(); + const handshake = { checked: checked.promise, start: vi.fn(), end: vi.fn() }; + const session = side(); + const done = sendFile(asPeer(pc), asChannel(channel), source, session.events, handshake, session.signal); + return { pc, channel, session, handshake, done, check: checked.resolve }; + } + + it("offers once checked and confirmed by the receiver, sends once asked, waits for the receiver's save", async () => { + const source = file(100_000); + const { pc, channel, session, handshake, check } = sending(source); + // Too early, the receiver has to ask after the offer. + channel.receive({ ok: true }); + channel.receive({ start: true }); + await settle(); + expect(channel.sent).toEqual([]); + check(); + await until(() => channel.sent.length); + expect(channel.json()).toEqual([{ name: 'payload.bin', size: 100_000 }]); + await settle(); + expect(channel.sent).toHaveLength(1); + expect(handshake.start).not.toHaveBeenCalled(); + + channel.receive({ start: true }); + await until(() => session.logged('sent')); + expect(handshake.start).toHaveBeenCalled(); + expect(channel.bytes()).toBe(100_000); + const chunks = channel.sent.slice(1).map((chunk) => new Uint8Array(chunk as ArrayBuffer)); + expect(digest(Buffer.concat(chunks))).toBe(await fileDigest(source)); + expect(session.status()).toBe('transfer: Sent, waiting for the receiver to save the rest'); + expect(pc.signalingState).not.toBe('closed'); + + channel.receive({ done: true }); + expect(session.status()).toBe('done: Delivered'); + expect(session.progress.at(-1)).toBe(100_000); + expect(pc.signalingState).toBe('closed'); + expect(session.errors).toEqual([]); + }); + + // The receiver's download manager reports what it read, the rest is held in its RAM. + it('keeps at most WINDOW unread, ignores reads that make no sense', async () => { + const size = 3 * WINDOW; + const { channel, session, check } = sending(file(size)); + check(); + channel.receive({ ok: true }); + await until(() => channel.sent.length); + channel.receive({ start: true }); + await until(() => channel.bytes() === WINDOW); + await settle(); + expect(channel.bytes()).toBe(WINDOW); + for (const read of [size + 1, -1, 1.5, '1000', 0]) channel.receive({ read }); + await settle(); + expect(channel.bytes()).toBe(WINDOW); + expect(session.progress).toEqual([0]); + + channel.receive({ read: CHUNK_SIZE }); + await until(() => channel.bytes() === WINDOW + CHUNK_SIZE); + // Not back. + channel.receive({ read: 1 }); + channel.receive({ read: WINDOW }); + await until(() => channel.bytes() === 2 * WINDOW); + channel.receive({ read: 2 * WINDOW }); + await until(() => session.logged('sent')); + expect(channel.bytes()).toBe(size); + expect(session.progress).toEqual([0, CHUNK_SIZE, WINDOW, 2 * WINDOW]); + }); + + it("waits while the channel's buffer is full", async () => { + const { channel, check } = sending(file(4 * CHUNK_SIZE)); + check(); + channel.receive({ ok: true }); + await until(() => channel.sent.length); + channel.bufferedAmount = MAX_BUFFERED + 1; + channel.receive({ start: true }); + await settle(); + expect(channel.bytes()).toBe(0); + channel.bufferedAmount = 0; + channel.emit('bufferedamountlow'); + await until(() => channel.bytes() === 4 * CHUNK_SIZE); + }); + + it("reports the receiver's error, a lost connection and a file it can't read anymore", async () => { + const stopped = sending(file(WINDOW + 1)); + stopped.check(); + stopped.channel.receive({ ok: true }); + await until(() => stopped.channel.sent.length); + stopped.channel.receive({ start: true }); + stopped.channel.receive({ error: `cancelled ${'x'.repeat(300)}` }); + expect(stopped.session.errors).toEqual([`receiver stopped: cancelled ${'x'.repeat(190)}`]); + expect(stopped.pc.signalingState).toBe('closed'); + + const lost = sending(file(WINDOW + 1)); + lost.check(); + lost.channel.receive({ ok: true }); + await until(() => lost.channel.sent.length); + lost.channel.receive({ start: true }); + await until(() => lost.channel.bytes() === WINDOW); + lost.pc.state('failed'); + expect(lost.session.errors).toEqual(['connection lost']); + await lost.done; + + const gone = { name: 'gone.bin', size: 10, slice: () => ({ arrayBuffer: () => Promise.reject(new Error()) }) }; + const unreadable = sending(gone as unknown as File); + unreadable.check(); + unreadable.channel.receive({ ok: true }); + await until(() => unreadable.channel.sent.length); + unreadable.channel.receive({ start: true }); + await unreadable.done; + expect(unreadable.session.errors).toEqual(['could not read gone.bin anymore']); + }); + + it('stops quietly when the connection closes before the transfer or the session ends', async () => { + const closed = sending(file(1000)); + closed.channel.close(); + closed.check(); + await closed.done; + expect(closed.channel.sent).toEqual([]); + expect(closed.session.errors).toEqual([]); + + const ended = sending(file(WINDOW + 1)); + ended.check(); + ended.channel.receive({ ok: true }); + await until(() => ended.channel.sent.length); + ended.channel.receive({ start: true }); + await until(() => ended.channel.bytes() === WINDOW); + ended.session.stop(); + await ended.done; + expect(ended.pc.signalingState).toBe('closed'); + expect(ended.session.errors).toEqual([]); + }); +}); + +describe('receiving', () => { + // A transfer into the mocked download, on a connection whose handshake passes once check is called. + function receiving() { + autoSave = false; + const pc = new FakePeer(); + const channel = new FakeChannel(); + channel.readyState = 'open'; + const checked = deferred(); + const handshake = { checked: checked.promise, start: vi.fn(), end: vi.fn() }; + const session = side(); + receiveFile(asPeer(pc), asChannel(channel), session.events, handshake, session.signal); + return { pc, channel, session, handshake, check: checked.resolve }; + } + + // Offered and confirmed, with the download started. + async function downloading(size: number) { + const receiver = receiving(); + receiver.check(); + await until(() => receiver.channel.sent.length); + receiver.channel.receive({ name: 'payload.bin', size }); + receiver.session.files[0]!.download(); + return { ...receiver, download: saved.at(-1)! }; + } + + it('accepts nothing before the check, offers the file to the user once', async () => { + const { channel, session, check } = receiving(); + channel.receive({ name: 'early.bin', size: 1 }); + await settle(); + expect(session.files).toEqual([]); + expect(channel.sent).toEqual([]); + check(); + await until(() => channel.sent.length); + expect(channel.json()).toEqual([{ ok: true }]); + channel.receive(new ArrayBuffer(4)); + channel.receive({ name: 'payload.bin', size: 4 }); + channel.receive({ name: 'second.bin', size: 1 }); + expect(session.files).toMatchObject([{ name: 'payload.bin', size: 4 }]); + expect(session.status()).toBe('wait: Click Download to save the file'); + expect(saved).toEqual([]); + }); + + it("ends the connection on an offer that isn't a file", async () => { + for (const offer of [ + { name: 1, size: 2 }, + { name: 'x'.repeat(MAX_NAME + 1), size: 2 }, + { name: 'a', size: -1 }, + { name: 'a', size: 1.5 }, + { name: 'a', size: 2 ** 53 }, + 'not json', + ]) { + const { channel, session, handshake, check } = receiving(); + check(); + await until(() => channel.sent.length); + channel.receive(offer); + expect(handshake.end).toHaveBeenCalledWith('the sender offered no valid file'); + expect(session.files).toEqual([]); + } + }); + + it("saves the chunks in order, reports the download manager's reads and when it finished", async () => { + const { channel, session, handshake, download } = await downloading(3 * CHUNK_SIZE); + expect(handshake.start).toHaveBeenCalled(); + expect(download.file).toEqual({ name: 'payload.bin', size: 3 * CHUNK_SIZE }); + expect(channel.json().at(-1)).toEqual({ start: true }); + const chunks = [0, 1, 2].map(() => randomBytes(CHUNK_SIZE)); + for (const chunk of chunks) channel.receive(new Uint8Array(chunk).buffer); + expect(savedDigest(download)).toBe(digest(Buffer.concat(chunks))); + expect(download.ended).toBe(true); + // Once all arrived, nothing more counts. + channel.receive(new ArrayBuffer(1)); + expect(session.errors).toEqual([]); + + download.events.read(CHUNK_SIZE); + expect(channel.json().at(-1)).toEqual({ read: CHUNK_SIZE }); + download.events.finished(); + expect(channel.json().at(-1)).toEqual({ done: true }); + expect(session.status()).toBe('done: Download complete'); + expect(session.progress).toEqual([0, CHUNK_SIZE, 3 * CHUNK_SIZE]); + expect(channel.readyState).toBe('closed'); + }); + + it('ends an empty file right away', async () => { + const { download } = await downloading(0); + expect(download.ended).toBe(true); + }); + + it('fails the download on more bytes than offered or beyond the window', async () => { + for (const [size, chunks, reason] of [ + [10, [6, 5], 'the sender sent more than it offered'], + [4 * WINDOW, [WINDOW, CHUNK_SIZE, 1], 'the sender ignored the flow control'], + ] as const) { + const { channel, session, download } = await downloading(size); + for (const bytes of chunks) channel.receive(new ArrayBuffer(bytes)); + expect(download.failed).toBe(reason); + expect(session.errors).toEqual([`download failed: ${reason}`]); + expect(channel.json().at(-1)).toEqual({ error: reason }); + expect(channel.readyState).toBe('closed'); + } + }); + + it('tells the sender when the user cancelled, the user when the download failed', async () => { + const cancelled = await downloading(10); + cancelled.download.events.cancelled(); + expect(cancelled.channel.json().at(-1)).toEqual({ error: 'download cancelled' }); + expect(cancelled.session.status()).toBe('stopped: Download cancelled'); + expect(cancelled.session.errors).toEqual([]); + + const failed = await downloading(10); + failed.download.events.failed('service worker stopped'); + expect(failed.session.errors).toEqual(['download failed: service worker stopped']); + expect(failed.channel.json().at(-1)).toEqual({ error: 'service worker stopped' }); + }); + + it('withdraws the offer when the sender leaves before the download, fails it after', async () => { + const before = receiving(); + before.check(); + await until(() => before.channel.sent.length); + before.channel.receive({ name: 'payload.bin', size: 10 }); + before.pc.state('failed'); + expect(before.session.files).toMatchObject([{ name: 'payload.bin' }, undefined]); + + const after = await downloading(10); + after.channel.close(); + await until(() => after.session.errors.length); + expect(after.session.errors).toEqual(['download failed: connection lost']); + }); + + it('fails the download once the session ended', async () => { + const { session, download } = await downloading(10); + session.stop(); + expect(download.failed).toBe('stopped'); + }); +}); + +describe('manual exchange', () => { + // Sender and receiver connected by the manual codes, both shown the check. + async function exchange(source: File) { + const [sender, receiver] = [side(), side()]; + const { offer, accept } = await createOffer(source, sender.events, sender.signal); + const answer = await answerOffer(offer, receiver.events, receiver.signal); + await accept(answer); + await until(() => sender.checks[0] && receiver.checks[0]); + return { sender, receiver, accept, answer }; + } + + it('sends a file once both compared the same codes', async () => { + const source = file(WINDOW + 100_000); + const { sender, receiver } = await exchange(source); + const [own, peer] = [sender.checks[0]!, receiver.checks[0]!]; + expect([own.local, own.remote]).toEqual([peer.remote, peer.local]); + expect(sender.status()).toBe('wait: Compare the security codes above with the receiver'); + + own.confirm(); + await until(() => sender.logged("waiting for the receiver's security check")); + expect(receiver.files).toEqual([]); + peer.confirm(); + await until(() => receiver.files[0]); + receiver.files[0]!.download(); + await until(() => sender.logged('delivered') && receiver.logged('download complete')); + expect(savedDigest(saved[0]!)).toBe(await fileDigest(source)); + expect(openPeers()).toEqual([]); + expect([...sender.errors, ...receiver.errors]).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it('ends both sides when one says the codes differ', async () => { + const { sender, receiver } = await exchange(file(10)); + receiver.checks[0]!.reject(); + await until(() => sender.errors.length); + expect(receiver.errors).toEqual(['security check failed']); + expect(sender.errors).toEqual(['the receiver left before the transfer']); + expect(sender.checks.at(-1)).toBeUndefined(); + expect(openPeers()).toEqual([]); + }); + + it('reports a broken offer and answer, the offer stays good for the right answer', async () => { + const receiver = side(); + await expect(answerOffer(btoa('v=0 but nothing else'), receiver.events, receiver.signal)).rejects.toThrow( + 'not a valid offer, copy all of it', + ); + expect(openPeers()).toEqual([]); + await expect(answerOffer('not base64!', receiver.events, receiver.signal)).rejects.toThrow( + 'not a valid offer, copy all of it', + ); + + const sender = side(); + const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); + await expect(accept(btoa('v=0\r\nnothing'))).rejects.toThrow('not a valid answer to this offer, copy all of it'); + await accept(await answerOffer(offer, receiver.events, receiver.signal)); + await until(() => sender.checks[0]); + }); + + it('tells why it could not connect, on each side once its time is up', async () => { + FakePeer.reachable = false; + const [sender, receiver] = [side(), side()]; + const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); + await accept(await answerOffer(offer, receiver.events, receiver.signal)); + const neither = + 'could not connect: neither side has a public address, between different networks both sides need STUN'; + vi.advanceTimersByTime(CONNECT_TIMEOUT); + expect(sender.errors).toEqual([neither]); + expect(receiver.errors).toEqual([]); + vi.advanceTimersByTime(TRACKER_WAIT - CONNECT_TIMEOUT); + expect(receiver.errors).toEqual([neither]); + expect(openPeers()).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); +}); + +describe('tracker signaling', () => { + const URLS = ['wss://one.test', 'wss://two.test', 'wss://three.test']; + // An announcement as a tracker relays it from another peer. + const relayed = (msg: object) => ({ action: 'announce', peer_id: randomBytes(20).toString('latin1'), ...msg }); + const offerId = () => randomBytes(20).toString('latin1'); + + it('sends a file proven by the code, the share is used up after', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, receiver] = [side(), side()]; + const source = file(2 * WINDOW); + const { code } = await sendViaTracker(source, sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.files[0]); + expect([...sender.checks, ...receiver.checks]).toEqual([]); + expect(sender.logged('security check passed') && receiver.logged('security check passed')).toBe(true); + + receiver.files[0]!.download(); + await until(() => sender.logged('delivered') && receiver.logged('download complete')); + expect(savedDigest(saved[0]!)).toBe(await fileDigest(source)); + expect(openPeers()).toEqual([]); + expect(openSockets()).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it('shares on after a peer that proves no code, with the next receiver', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, silent, receiver] = [side(), side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, silent.events, silent.signal); + // Its offer's channel, the first one made. + 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')); + vi.advanceTimersByTime(PROOF_TIMEOUT); + await until(() => sender.logged('waiting for the next receiver')); + expect(sender.logged('the peer proved no code')).toBe(true); + silent.stop(); + + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.files[0]); + expect(sender.errors).toEqual([]); + }); + + it('stays on the first tracker that accepts the share, the next only once that one is lost', async () => { + new FakeTracker(URLS[0]!, () => ({ 'failure reason': 'not here' })); + const second = new FakeTracker(URLS[1]!); + new FakeTracker(URLS[2]!); + settings.trackers = URLS; + const sender = side(); + await sendViaTracker(file(10), sender.events, sender.signal); + await until(() => sender.logged(`waiting on ${URLS[1]}`)); + await settle(); + expect(FakeSocket.all.map((ws) => ws.url)).toEqual(URLS.slice(0, 2)); + expect(sender.logged(`rejected by ${URLS[0]}: not here`)).toBe(true); + + second.sockets[0]!.drop(); + await until(() => sender.logged(`waiting on ${URLS[2]}`)); + expect(sender.errors).toEqual([]); + trackers.get(URLS[2]!)!.sockets[0]!.drop(); + await until(() => sender.errors.length); + expect(sender.errors).toEqual([ + `no tracker accepted it (${URLS[0]}: not here), check the list under Servers and try again`, + ]); + expect(vi.getTimerCount()).toBe(0); + }); + + it('reports trackers that reject on both sides, unreachable ones as such', async () => { + for (const url of URLS) new FakeTracker(url, () => ({ 'failure reason': 'not here' })); + settings.trackers = URLS; + const [sender, receiver] = [side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + const rejected = `no tracker accepted it (${URLS.map((url) => `${url}: not here`).join('; ')}), check the list under Servers and try again`; + await until(() => sender.errors.length && receiver.errors.length); + expect(sender.errors).toEqual([rejected]); + expect(receiver.errors).toEqual([rejected]); + + trackers.clear(); + const lonely = side(); + await sendViaTracker(file(10), lonely.events, lonely.signal); + await until(() => lonely.errors.length); + expect(lonely.errors).toEqual(['no tracker reachable, check the list under Servers and try again']); + expect(openPeers()).toEqual([]); + expect(openSockets()).toEqual([]); + }); + + it('walks the trackers until one has a seeder, keeps its offer on those it passed', async () => { + let seeders = [0, 1, 0]; + for (const [i, url] of URLS.entries()) { + new FakeTracker(url, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash, complete: seeders[i] })); + } + settings.trackers = URLS; + const receiver = side(); + await receiveViaTracker('somecode123', receiver.events, receiver.signal); + await until(() => receiver.logged(`looking on ${URLS[1]}`)); + await settle(); + expect(openSockets().map((ws) => ws.url)).toEqual(URLS.slice(0, 2)); + + // The sender lost the second one. + seeders = [0, 0, 0]; + trackers.get(URLS[1]!)!.sockets[0]!.deliver({ action: 'announce', interval: 120, complete: 0 }); + await until(() => receiver.logged(`looking on ${URLS[2]}`)); + await until(() => receiver.status()?.startsWith('retry: No sender')); + expect(receiver.status()).toBe('retry: No sender with this code on any tracker. Check the code, still looking'); + expect(openSockets()).toHaveLength(3); + // It showed up again, busy with another receiver maybe. + trackers.get(URLS[2]!)!.sockets[0]!.deliver({ action: 'announce', interval: 120, complete: 1 }); + expect(receiver.status()).toBe('wait: Found the share on three.test, waiting for the sender to answer'); + expect(receiver.errors).toEqual([]); + }); + + // 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 })); + settings.trackers = [URLS[0]!]; + const sender = side(); + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + const { sealing } = await secrets(code, codeSalt(code)); + await until(() => tracker.open().length); + const ws = tracker.sockets[0]!; + for (let offers = 1; offers <= 25; offers++) { + ws.deliver( + relayed({ offer_id: offerId(), offer: { type: 'offer', sdp: await seal(sealing, 'offer', 'garbage') } }), + ); + await until(() => sender.count('unusable offer') === offers); + if (offers === 1) ws.deliver({ 'failure reason': 'slow down' }); + } + for (let offers = 0; offers < 5; offers++) ws.deliver(relayed({ offer_id: offerId(), offer: { sdp: 'garbage' } })); + await until(() => sender.count('offer without the code') === 5); + expect(sender.logged(`${URLS[0]}: slow down`)).toBe(true); + expect(sender.logged('rejected by')).toBe(false); + expect(sender.errors).toEqual([]); + expect(FakePeer.all).toHaveLength(25); + expect(openPeers()).toEqual([]); + // The tracker socket's and the expiry's, none for the closed connections. + expect(getEventListeners(sender.signal, 'abort')).toHaveLength(2); + }); + + it('gives an offer still being opened no turn after the expiry', async () => { + const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); + settings.trackers = [URLS[0]!]; + const sender = side(); + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + const { sealing } = await secrets(code, codeSalt(code)); + const sealed = await seal(sealing, 'offer', 'v=0\r\na=fingerprint:sha-256 AA\r\n'); + await until(() => tracker.open().length); + const decrypt = vi.spyOn(crypto.subtle, 'decrypt'); + tracker.sockets[0]!.deliver(relayed({ offer_id: offerId(), offer: { type: 'offer', sdp: sealed } })); + expect(decrypt).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(TRACKER_WAIT); + expect(sender.errors).toHaveLength(1); + expect(sender.errors[0]).toMatch(/^nobody received the file until .+, share it again$/); + await decrypt.mock.results[0]!.value; + await settle(); + expect(sender.logged('offer via')).toBe(false); + expect(FakePeer.all).toEqual([]); + }); + + // Trackers drop a peer that doesn't announce again on their interval. + it('announces again on both sides until they give up after TRACKER_WAIT', async () => { + const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 0, info_hash })); + settings.trackers = [URLS[0]!]; + const [sender, receiver] = [side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => tracker.announced.length === 2); + const [shared, offered] = tracker.announced; + vi.advanceTimersByTime(MIN_INTERVAL - 1); + await settle(); + expect(tracker.announced).toHaveLength(2); + vi.advanceTimersByTime(1); + await until(() => tracker.announced.length === 4); + const again = tracker.announced.slice(2); + expect(again.map((msg) => [msg.info_hash, msg.left, msg.event])).toEqual([ + [shared.info_hash, 0, undefined], + [shared.info_hash, 1, undefined], + ]); + // The same offer, a busy sender may have dropped it. + expect(again[1].offers).toEqual(offered.offers); + + vi.advanceTimersByTime(TRACKER_WAIT - MIN_INTERVAL); + expect(sender.errors[0]).toMatch(/^nobody received the file until .+, share it again$/); + expect(sender.expired).toBe(true); + expect(receiver.errors[0]).toMatch(/^no sender answered until .+, ask the sender for a new code$/); + await settle(); + expect(openSockets()).toEqual([]); + expect(openPeers()).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it('lets a receiver connected before the expiry download after it', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, receiver] = [side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.files[0]); + vi.advanceTimersByTime(TRACKER_WAIT); + expect(sender.expired).toBe(true); + await settle(); + expect(openSockets()).toEqual([]); + receiver.files[0]!.download(); + await until(() => sender.logged('delivered')); + expect([...sender.errors, ...receiver.errors]).toEqual([]); + }); + + it('keeps nothing of sessions that ended', async () => { + new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); + settings.trackers = [URLS[0]!]; + for (let session = 0; session < 5; session++) { + const [sender, receiver] = [side(), side()]; + await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(`nobodyhere${session}`, receiver.events, receiver.signal); + await until(() => receiver.logged('looking on')); + sender.stop(); + receiver.stop(); + } + await settle(); + expect(openSockets()).toEqual([]); + expect(openPeers()).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it('tells why the peers could not connect, until the time is up', async () => { + FakePeer.reachable = false; + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, receiver] = [side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.logged('answer via')); + const neither = 'neither side has a public address, between different networks both sides need STUN'; + vi.advanceTimersByTime(CONNECT_TIMEOUT); + expect(sender.logs).toContain(`receiver did not connect: ${neither}`); + expect(receiver.logs).toContain(`sender via ${URLS[0]} did not connect: ${neither}`); + expect(sender.status()).toBe( + `retry: could not connect to the receiver: ${neither}. Waiting for the receiver to try again`, + ); + + vi.advanceTimersByTime(TRACKER_WAIT); + await settle(); + expect(sender.errors).toHaveLength(1); + expect(sender.errors[0]).toMatch(new RegExp(`^no receiver connected until .+: ${neither}$`)); + expect(receiver.errors[0]).toMatch(new RegExp(`^no sender connected until .+: ${neither}$`)); + }); + + it("tells a code that can't be one right away", async () => { + const receiver = side(); + await expect(receiveViaTracker('abcdefghij', receiver.events, receiver.signal)).rejects.toThrow( + 'a code has 11 letters and digits, check it', + ); + expect(FakeSocket.all).toEqual([]); + }); +}); diff --git a/src/core.ts b/src/core.ts index cac70b0..d42489b 100644 --- a/src/core.ts +++ b/src/core.ts @@ -1,3 +1,5 @@ +import { type Download, downloadsReady, startDownload } from './download'; + export const DEFAULT_TRACKERS = [ 'wss://tracker.pagequit.net', 'wss://tracker.webtorrent.dev', @@ -11,6 +13,10 @@ export const DEFAULT_STUN_SERVERS = [ 'stun:stun.nextcloud.com:443', ]; +// App.vue uses the settings and their defaults, randomCode, formatTime, the types and the sessions +// at the end. src/core.test.ts also tests the other exports on their own, biome.json keeps them to it: +// a new one goes on its list there. + // Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody. // Read whenever a connection or tracker socket is created, so changes apply to the next one. export const settings = { @@ -19,41 +25,34 @@ export const settings = { trackers: [...DEFAULT_TRACKERS], }; -const CHUNK_SIZE = 16 * 1024; -const MAX_BUFFERED = 1024 * 1024; +export const CHUNK_SIZE = 16 * 1024; +export const MAX_BUFFERED = 1024 * 1024; // The receiving side can't pause a data channel, so it reports how much the download manager has // read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM. -const WINDOW = 8 * 1024 * 1024; -// Firefox stops a service worker after 30 s without events, also in the middle of a download, and -// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings. -const KEEPALIVE = 10_000; -// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its -// download manager. Its frame removed before that, the download never shows up, though the worker -// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests. -const DOWNLOAD_GRACE = 1000; +export const WINDOW = 8 * 1024 * 1024; const ICE_GRACE = 300; const ICE_TIMEOUT = 5000; -// A STUN server that reports no public address by then gets passed over, see stunServer. +// A STUN server that reports no public address by then gets passed over, see stunChoice. const PROBE_TIMEOUT = 2000; // A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn. -const TRACKER_TIMEOUT = 10_000; +export const TRACKER_TIMEOUT = 10_000; // A tracker peer that got an answer but never opens the data channel gives up its turn after this, // e.g. one whose SDP has no usable candidates: Chromium never even fails its connection. The manual // sender gives up on the answer after it as well. -const CONNECT_TIMEOUT = 30_000; +export const CONNECT_TIMEOUT = 30_000; // A share, or a receiver looking for one, gives up after this without a download: nobody announces // all day for a code nobody uses. Until then both announce again on the interval the tracker names, // else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names. // The manual receiver waits this long for the sender to connect, it has to get the answer first. export const TRACKER_WAIT = 6 * 60_000; -const MIN_INTERVAL = 30_000; +export const MIN_INTERVAL = 30_000; // OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms. -const PBKDF2_ITERATIONS = 600_000; +export const PBKDF2_ITERATIONS = 600_000; // A tracker peer that connects but proves no code gives up its turn after this. Signing takes // milliseconds, a peer that knows the code is never near it. -const PROOF_TIMEOUT = 10_000; +export const PROOF_TIMEOUT = 10_000; // Far beyond what a file system stores, but keeps an absurd name out of the page and the worker. -const MAX_NAME = 1024; +export const MAX_NAME = 1024; export type Check = { local: string; @@ -101,7 +100,7 @@ export type ReceiveEvents = Events & { // Closes it once the session ends, right away if it already did. Closing it earlier lets go of it, else // the session would keep every connection a rejected or failed peer left behind until it ends. -function own void }>(signal: AbortSignal, resource: T) { +export function own void }>(signal: AbortSignal, resource: T) { const closeResource = resource.close.bind(resource); // Without the abort event, WebSocket.close() would take it for a close code and throw. const close = () => closeResource(); @@ -115,14 +114,14 @@ function own void }>(signal: AbortSignal, resource: T) } // Closing everything fires events of its own, none of them reaches the caller after the abort. -function live void>>(events: T, signal: AbortSignal) { +export function live void>>(events: T, signal: AbortSignal) { return Object.fromEntries( Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]), ) as T; } // Runs expire after ms unless closed before, cleared with the session. -function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) { +export function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) { const timer = setTimeout(() => { owned.close(); expire(); @@ -158,81 +157,88 @@ async function probe(url: string, stop: AbortSignal) { } } -// Probes list in order from start on, the ones before start last, see stunServer. -function probeFrom(list: string[], start: number) { - const key = list.join('\n'); - const stop = new AbortController(); - let at = start; - let settled = false; - let waiting = 0; - const server = (async () => { - for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) { - // No further server is contacted once nobody waits, STUN was turned off or the list changed. - if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return; - if (await probe(list[at]!, stop.signal)) return list[at]; - } - })().finally(() => (settled = true)); - const choice = { - list, - key, - server, - // Before it found one, the next probe goes on where this one stopped. - stopped: false, - // The server for a session's connection. Once no session waits for it any more, the probe stops. - async wait(signal: AbortSignal) { - if (signal.aborted) return; - waiting++; - const leave = () => { - if (--waiting || settled) return; - choice.stopped = true; - resume = { key, at }; - stop.abort(); - }; - signal.addEventListener('abort', leave, { once: true }); - try { - return await server; - } finally { - signal.removeEventListener('abort', leave); - if (!signal.aborted) waiting--; - } - }, - }; - // E.g. offline, the next connection probes again. - void server.then((url) => { - if (!url && stun === choice) stun = undefined; - }); - return choice; -} - -let stun: ReturnType | undefined; -// Where the next probe of the list with key starts, if not at its first server. -let resume: { key: string; at: number } | undefined; - // Each connection uses one STUN server, so only that one learns the address: the first in the list // that reports one. It stays for the page's lifetime, unless a connection gets no address from it, // then the next connection probes on from the server after it. A changed list starts over. None, or // none reporting an address, means connections without STUN. A device with a public address of its // own gets none reported (browsers drop it as redundant) and probes them all for every connection. -function stunServer(signal: AbortSignal) { - if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined); - const key = settings.stunServers.join('\n'); - if (stun?.key !== key || stun.stopped) { - stun = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0); - resume = undefined; +// The page has one, see stun, a test makes its own with a probe of its own. +export function stunChoice(answers = probe) { + let current: ReturnType | undefined; + // Where the next probe of the list with key starts, if not at its first server. + let resume: { key: string; at: number } | undefined; + + // Probes list in order from start on, the ones before start last. + function probeFrom(list: string[], start: number) { + const key = list.join('\n'); + const stop = new AbortController(); + let at = start; + let settled = false; + let waiting = 0; + const server = (async () => { + for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) { + // No further server is contacted once nobody waits, STUN was turned off or the list changed. + if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return; + if (await answers(list[at]!, stop.signal)) return list[at]; + } + })().finally(() => (settled = true)); + const choice = { + list, + key, + server, + // Before it found one, the next probe goes on where this one stopped. + stopped: false, + // The server for a session's connection. Once no session waits for it any more, the probe stops. + async wait(signal: AbortSignal) { + if (signal.aborted) return; + waiting++; + const leave = () => { + if (--waiting || settled) return; + choice.stopped = true; + resume = { key, at }; + stop.abort(); + }; + signal.addEventListener('abort', leave, { once: true }); + try { + return await server; + } finally { + signal.removeEventListener('abort', leave); + if (!signal.aborted) waiting--; + } + }, + }; + // E.g. offline, the next connection probes again. + void server.then((url) => { + if (!url && current === choice) current = undefined; + }); + return choice; } - return stun.wait(signal); + + return { + // The server for a connection of the session with signal, if any. + server(signal: AbortSignal) { + if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined); + const key = settings.stunServers.join('\n'); + if (current?.key !== key || current.stopped) { + current = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0); + resume = undefined; + } + return current.wait(signal); + }, + // A connection got no public address from url. + async failed(url: string) { + const choice = current; + if (!choice || (await choice.server) !== url || current !== choice) return; + resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length }; + current = undefined; + }, + }; } -// A connection got no public address from url. -async function stunFailed(url: string) { - const choice = stun; - if (!choice || (await choice.server) !== url || stun !== choice) return; - resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length }; - stun = undefined; -} +const stun = stunChoice(); async function createPeerConnection(signal: AbortSignal) { - const server = await stunServer(signal); + const server = await stun.server(signal); return own(signal, new RTCPeerConnection({ iceServers: server ? [{ urls: server }] : [] })); } @@ -241,7 +247,7 @@ async function createPeerConnection(signal: AbortSignal) { // biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above type Message = Record; -function parse(data: unknown): Message | undefined { +export function parse(data: unknown): Message | undefined { if (typeof data !== 'string') return; try { const message = JSON.parse(data); @@ -250,7 +256,7 @@ function parse(data: unknown): Message | undefined { } // The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored. -function decode(code: string, type: 'offer' | 'answer') { +export function decode(code: string, type: 'offer' | 'answer') { try { return { type, sdp: atob(code.replace(/\s/g, '')) }; } catch { @@ -262,7 +268,7 @@ function randomBinary(length: number) { return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length))); } -const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; +export const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // The largest multiple of the alphabet's length a byte holds. The bytes above would make the first // characters likelier, they are dropped. const CODE_LIMIT = 256 - (256 % CODE_CHARS.length); @@ -286,13 +292,13 @@ export const formatTime = (time: number) => // its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts // TRACKER_WAIT from the click whenever in its window that was. // Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms. -const SALT_WINDOW = 6 * 60_000; -const CODE_LENGTH = 11; +export const SALT_WINDOW = 6 * 60_000; +export const CODE_LENGTH = 11; const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW); // The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo, // not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share. -function trackerSalt(at: number, own?: string) { +export function trackerSalt(at: number, own?: string) { const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16); if (own === undefined) return salt; if (!own.trim()) throw new Error('the own salt is empty'); @@ -300,14 +306,14 @@ function trackerSalt(at: number, own?: string) { } // A sender's new code and its salt. -function newCode(own?: string) { +export function newCode(own?: string) { const at = clockWindow(Date.now()); return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) }; } // The salt of the code a receiver got, its window from half the characters before the clock's to half // after. Anything else can't be a code, a typo gets told right away instead of searched for. -function codeSalt(code: string, own?: string) { +export function codeSalt(code: string, own?: string) { if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char))) throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`); const now = clockWindow(Date.now()); @@ -325,7 +331,7 @@ function codeSalt(code: string, own?: string) { // years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one // system can be other bytes than on the next. HKDF splits the result, the public info_hash tells // nothing about the keys: one seals the signaling, see seal, one proves the connection. -async function secrets(code: string, salt: string) { +export async function secrets(code: string, salt: string) { const text = new TextEncoder(); const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']); const bits = await crypto.subtle.deriveBits( @@ -356,7 +362,7 @@ async function secrets(code: string, salt: string) { // 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) { +export 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) }; @@ -365,7 +371,7 @@ async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) { } // The SDP, unless it wasn't sealed with the code as that type. -async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) { +export 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)); @@ -411,13 +417,13 @@ async function gatherIce(pc: RTCPeerConnection) { }); }); const [server] = pc.getConfiguration().iceServers ?? []; - if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!); + if (server && !reported && pc.signalingState !== 'closed') void stun.failed([server.urls].flat()[0]!); } // Why pc didn't connect, if a missing public address explains it: a side without one from STUN offers // only local addresses, enough on the same network or VPN. peer names the other side. A device with -// a public address of its own offers none either, see stunServer, so it's a hint, not a diagnosis. -function stunHint(pc: RTCPeerConnection, peer: string) { +// a public address of its own offers none either, see stunChoice, so it's a hint, not a diagnosis. +export function stunHint(pc: RTCPeerConnection, peer: string) { const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? ''); const local = offersPublic(pc.localDescription); const remote = offersPublic(pc.remoteDescription); @@ -439,7 +445,7 @@ const host = (url: string) => URL.parse(url)?.host || url; // Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can // brute force with matching certificates. My local code must equal the peer's remote code and vice // versa, otherwise someone interposed on the signaling. -function securityCheck(pc: RTCPeerConnection) { +export function securityCheck(pc: RTCPeerConnection) { const short = (sdp = '') => sdp .match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1] @@ -452,7 +458,7 @@ function securityCheck(pc: RTCPeerConnection) { // Every fingerprint the SDP names, in full: one added beside the real one changes the result too. // Browsers may move them between session and media level, so each counts once. -const fingerprints = (sdp: string) => +export const fingerprints = (sdp: string) => [...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort(); // The security check of tracker signaling, resolves once the peer proved the code. Each side signs its @@ -460,7 +466,7 @@ const fingerprints = (sdp: string) => // against its own view. An interposer has its own certificate towards each side and can't sign for it // without the code, neither can a peer that found the swarm some other way. One that sends no proof // within PROOF_TIMEOUT or a wrong one ends the connection. -function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) { +export function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) { const local = pc.localDescription!; const remote = pc.remoteDescription!; const statement = (type: string, own: string, peer: string) => @@ -502,7 +508,7 @@ function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, e // pass, a failed check, a peer that left or end closes the connection and calls next: tracker // signaling goes on with another peer. Without next, as in the manual exchange, the session is over // and the reason is an error. From start on, sendFile and receiveFile handle a loss. -type Handshake = { checked: Promise; start: () => void; end: (reason: string) => void }; +export type Handshake = { checked: Promise; start: () => void; end: (reason: string) => void }; function connected( pc: RTCPeerConnection, @@ -548,7 +554,7 @@ function connected( // { done } once the download manager read the last byte, or { error } when its download was // cancelled or failed. Any other message, or one out of turn, is ignored. Every way out of the // transfer closes the connection. -async function sendFile( +export async function sendFile( pc: RTCPeerConnection, channel: RTCDataChannel, file: File, @@ -640,63 +646,19 @@ async function sendFile( if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest'); } -// Received files are streamed into the browser's download manager by public/sw.js, so a file never -// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests. -const downloads = registerDownloads(); -// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window. -downloads.catch(() => {}); - -// Only the first visit has to wait here, updates are picked up per transfer by holdWorker. -async function registerDownloads() { - const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' }); - const pending = registration.installing ?? registration.waiting; - if (!registration.active && pending) { - await new Promise((resolve) => - pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)), - ); - } - if (!registration.active) throw new Error('service worker did not activate'); -} - -// Awaited before receiving starts, so a browser without service workers fails before connecting. -function downloadsReady() { - return downloads.catch((error) => { - throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`); - }); -} - -// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling -// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that -// worker in the middle of the download. -async function holdWorker() { - await downloads; - const frame = document.createElement('iframe'); - frame.hidden = true; - frame.src = 'download/'; - document.body.append(frame); - await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true })); - const worker = frame.contentWindow!.navigator.serviceWorker.controller; - if (!worker) { - frame.remove(); - throw new Error('service worker did not take over'); - } - return { frame, worker }; -} - // Accepts nothing until checked resolved, then tells the sender with { ok }. Its file is offered to // the user, chunks are accepted only once they started the download. Nothing the sender sends is // trusted: a malformed offer ends the connection, more bytes than offered or beyond the window fail -// the download. Once it ended, the connection closes. -function receiveFile( +// the download. Once it ended, the connection closes. startDownload saves it, see src/download.ts. +export function receiveFile( pc: RTCPeerConnection, channel: RTCDataChannel, events: ReceiveEvents, handshake: Handshake, signal: AbortSignal, ) { - const id = crypto.randomUUID(); - const frames: HTMLIFrameElement[] = []; let meta: { name: string; size: number } | undefined; + let saving: Download | undefined; let received = 0; // By the download manager. The rest of received is held in this page and the worker. let read = 0; @@ -704,86 +666,50 @@ function receiveFile( let downloading = false; let complete = false; let ended = false; - // Chunks can arrive before the worker is held, chaining every post on this keeps them in order. - let worker: Promise = Promise.resolve(undefined); - const post = (message: object, transfer: Transferable[] = []) => - void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer)); // To the sender, see sendFile. const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message)); // A data channel closes only after sending what it buffered, so the last reply still arrives. channel.addEventListener('close', () => pc.close()); - let keepalive: ReturnType | undefined; - - // Releases the worker, so a waiting update can take over. A finished download keeps its own frame - // for DOWNLOAD_GRACE, that one doesn't hold the worker. - function release(finished = false) { - clearInterval(keepalive); - const [hold, download] = frames; - hold?.remove(); - if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE); - else download?.remove(); - } - - // The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the - // download running instead of failing it. function fail(reason: string) { + if (ended) return; + saving?.fail(reason); + failed(reason); + } + + // Also when the download failed on its own, no telling it then. + function failed(reason: string) { if (ended) return; ended = true; - post({ error: reason }); reply({ error: reason }); channel.close(); events.error(`download failed: ${reason}`); } - function startDownload() { - worker = holdWorker().then( - ({ frame, worker }) => { - frames.push(frame); - keepalive = setInterval(() => post({ ping: true }), KEEPALIVE); - // Only if something else than an update stops it, e.g. clearing the site data. It can't answer. - worker.addEventListener('statechange', () => { - if (worker.state !== 'redundant') return; - fail('service worker stopped'); - release(); - }); - const { port1, port2 } = new MessageChannel(); - port1.onmessage = ({ data }) => { - if (typeof data === 'number') { - read = data; - events.progress(read, meta!.size); - return reply({ read }); - } - if (data === 'ready' && !ended) { - // A navigation, not fetch(): only navigations hand the response to the download manager. - const download = document.createElement('iframe'); - download.hidden = true; - download.src = `download/${id}`; - document.body.append(download); - frames.push(download); - return; - } - if (data === 'failed') fail('the service worker refused it'); - if (data === 'finished') { - events.log('download complete'); - events.status('done', 'Download complete'); - events.progress(meta!.size, meta!.size); - reply({ done: true }); - } - if (data === 'cancelled' && !ended) { - events.log('download cancelled'); - events.status('stopped', 'Download cancelled'); - reply({ error: 'download cancelled' }); - } - ended = true; - channel.close(); - release(data === 'finished'); - }; - worker.postMessage({ id, ...meta }, [port2]); - return worker; + function startSaving(file: { name: string; size: number }) { + saving = startDownload(file, { + read: (bytes) => { + read = bytes; + events.progress(read, file.size); + reply({ read }); }, - (error) => void fail(String(error)), - ); + finished: () => { + events.log('download complete'); + events.status('done', 'Download complete'); + events.progress(file.size, file.size); + reply({ done: true }); + ended = true; + channel.close(); + }, + cancelled: () => { + events.log('download cancelled'); + events.status('stopped', 'Download cancelled'); + reply({ error: 'download cancelled' }); + ended = true; + channel.close(); + }, + failed, + }); } void handshake.checked.then(() => { @@ -795,7 +721,7 @@ function receiveFile( function receivedAll() { complete = true; - post({ done: true }); + saving!.end(); events.log('received'); } @@ -809,7 +735,7 @@ function receiveFile( events.log(`receiving ${meta!.name}`); events.status('transfer', 'Receiving'); events.progress(0, meta!.size); - startDownload(); + startSaving(meta!); reply({ start: true }); if (!meta!.size) receivedAll(); } @@ -832,7 +758,7 @@ function receiveFile( if (received > meta!.size) return fail('the sender sent more than it offered'); // sendFile never has more than WINDOW unread plus the chunk it just sent. if (received - read > WINDOW + CHUNK_SIZE) return fail('the sender ignored the flow control'); - post({ chunk: data }, [data]); + saving!.write(data); if (received === meta!.size) receivedAll(); } }; @@ -938,7 +864,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal: // 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, rejected or // without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names. -function trackerSocket( +export function trackerSocket( url: string, signal: AbortSignal, events: Events, @@ -998,7 +924,7 @@ function trackerSocket( type Tracker = ReturnType; // Once none of the trackers is left: what the user can do about it, and why if any rejected. -function noTracker(trackers: (Tracker | undefined)[]) { +export function noTracker(trackers: (Tracker | undefined)[]) { const rejected = trackers.flatMap((tracker) => tracker?.rejected ?? []); const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable'; return `${reason}, check the list under Servers and try again`; diff --git a/src/download.ts b/src/download.ts new file mode 100644 index 0000000..85b621f --- /dev/null +++ b/src/download.ts @@ -0,0 +1,155 @@ +// Received files are streamed into the browser's download manager by public/sw.js, so a file never +// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests. +// This is the page's half of it. The receiver in src/core.ts only sees startDownload, so it can be +// tested against a download in memory, and another way of saving could take this one's place. + +// Firefox stops a service worker after 30 s without events, also in the middle of a download, and +// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings. +const KEEPALIVE = 10_000; +// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its +// download manager. Its frame removed before that, the download never shows up, though the worker +// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests. +const DOWNLOAD_GRACE = 1000; + +const downloads = registerDownloads(); +// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window. +downloads.catch(() => {}); + +// Only the first visit has to wait here, updates are picked up per transfer by holdWorker. +async function registerDownloads() { + const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' }); + const pending = registration.installing ?? registration.waiting; + if (!registration.active && pending) { + await new Promise((resolve) => + pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)), + ); + } + if (!registration.active) throw new Error('service worker did not activate'); +} + +// Awaited before receiving starts, so a browser without service workers fails before connecting. +export function downloadsReady() { + return downloads.catch((error) => { + throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`); + }); +} + +// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling +// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that +// worker in the middle of the download. +async function holdWorker() { + await downloads; + const frame = document.createElement('iframe'); + frame.hidden = true; + frame.src = 'download/'; + document.body.append(frame); + await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true })); + const worker = frame.contentWindow!.navigator.serviceWorker.controller; + if (!worker) { + frame.remove(); + throw new Error('service worker did not take over'); + } + return { frame, worker }; +} + +// What the download manager does with a download, see startDownload. Each one but read ends it, only +// the first of them comes, and none after fail. +export type DownloadEvents = { + // How many bytes it has read so far, every MiB. + read: (bytes: number) => void; + // It has read the last byte. + finished: () => void; + // The user cancelled it. + cancelled: () => void; + // Something else than fail ended it: no worker, the worker refused it or stopped. + failed: (reason: string) => void; +}; + +// The receiver writes every chunk, then ends it once all arrived, or fails it. +export type Download = { + write: (chunk: ArrayBuffer) => void; + end: () => void; + fail: (reason: string) => void; +}; + +// Starts saving file in the browser's download manager. Writes can come before the worker is held, +// they wait for it in order. Once it ended, its frames go and the worker is free for an update. +export function startDownload(file: { name: string; size: number }, events: DownloadEvents): Download { + const id = crypto.randomUUID(); + const frames: HTMLIFrameElement[] = []; + let keepalive: ReturnType | undefined; + // By whatever came first: the worker's answer, its stop or fail. + let ended = false; + // Chaining every post on this keeps them in order. + const worker: Promise = holdWorker().then( + ({ frame, worker }) => { + frames.push(frame); + keepalive = setInterval(() => post({ ping: true }), KEEPALIVE); + // An update takes over only once the frames are released, then this changes nothing. Else + // something stopped it in the middle, e.g. clearing the site data, it can't answer then. + worker.addEventListener('statechange', () => { + if (worker.state !== 'redundant') return; + if (!ended) events.failed('service worker stopped'); + ended = true; + release(); + }); + const { port1, port2 } = new MessageChannel(); + port1.onmessage = ({ data }) => { + if (typeof data === 'number') return ended || events.read(data); + if (data === 'ready') { + if (ended) return; + // A navigation, not fetch(): only navigations hand the response to the download manager. + const download = document.createElement('iframe'); + download.hidden = true; + download.src = `download/${id}`; + document.body.append(download); + frames.push(download); + return; + } + if (!ended) { + if (data === 'finished') events.finished(); + if (data === 'cancelled') events.cancelled(); + if (data === 'failed') events.failed('the service worker refused it'); + } + ended = true; + release(data === 'finished'); + }; + worker.postMessage({ id, ...file }, [port2]); + return worker; + }, + (error) => { + if (!ended) events.failed(String(error)); + ended = true; + return undefined; + }, + ); + const post = (message: object, transfer: Transferable[] = []) => + void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer)); + + // Removed earlier, Chromium keeps a failed download running instead of failing it. A finished + // download keeps its own frame for DOWNLOAD_GRACE, that one doesn't hold the worker. Only the first + // call counts, a later one would take that frame right away. + let released = false; + function release(finished = false) { + if (released) return; + released = true; + clearInterval(keepalive); + const [hold, download] = frames; + hold?.remove(); + if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE); + else download?.remove(); + } + + return { + write: (chunk) => post({ chunk }, [chunk]), + end: () => post({ done: true }), + // The worker answers with failed, only then the frames go. A worker that restarted lost the + // download, and its stream with it, it never answers: they go after KEEPALIVE anyway. + fail: (reason) => { + if (ended) return; + ended = true; + post({ error: reason }); + void worker.then(() => setTimeout(release, KEEPALIVE)); + }, + }; +} diff --git a/tsconfig.json b/tsconfig.json index 0a9d055..77ea477 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,5 +16,5 @@ "allowJs": true, "noEmit": true }, - "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"] + "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "playwright.config.ts", "e2e.spec.ts"] } diff --git a/vite.config.ts b/vite.config.ts index 7b6cf7e..788926a 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,6 +1,9 @@ +/// import vue from '@vitejs/plugin-vue'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [vue()], + // Playwright runs e2e.spec.ts and backend/, which Vitest would pick up too. + test: { include: ['src/**/*.test.ts'] }, });