Refactor the app
This commit is contained in:
1 parent
f53d39ae69
commit
8f82700736
11 files changed
+2032
-235
No files matched your search
+53
-2
@@ -16,8 +16,59 @@
|
|||||||
"rules": {
|
"rules": {
|
||||||
"preset": "recommended",
|
"preset": "recommended",
|
||||||
"nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" },
|
"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" }
|
"a11y": { "useSemanticElements": "off" }
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"overrides": [
|
||||||
|
{ "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } }
|
||||||
|
]
|
||||||
}
|
}
|
||||||
+9
-5
@@ -31,7 +31,8 @@ const SIZE = 5_000_000;
|
|||||||
const LARGE_SIZE = 2.5 * 2 ** 30;
|
const LARGE_SIZE = 2.5 * 2 ** 30;
|
||||||
// Big enough that the transfer still runs while a test cancels or disconnects.
|
// Big enough that the transfer still runs while a test cancels or disconnects.
|
||||||
const RUNNING_SIZE = 100_000_000;
|
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 WINDOW = 8 * 2 ** 20;
|
||||||
const PROBE_TIMEOUT = 2000;
|
const PROBE_TIMEOUT = 2000;
|
||||||
const PROOF_TIMEOUT = 10_000;
|
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);
|
if (mode === 'tracker') return proven(sender, receiver);
|
||||||
|
|
||||||
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
|
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}$/, {
|
// Each side shows ? until it has that fingerprint, the remote one can come after the local one.
|
||||||
timeout: 45_000,
|
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-remote')).toHaveText((await check(sender, 'local'))!);
|
||||||
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
|
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
|
||||||
for (const page of [sender, receiver]) {
|
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.
|
// The edges of the chunking and the window, and a name the Content-Disposition header has to encode.
|
||||||
for (const [what, file, size] of [
|
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],
|
['an empty file', 'empty.bin', 0],
|
||||||
['a one byte file', 'one.bin', 1],
|
['a one byte file', 'one.bin', 1],
|
||||||
// Firefox would save a % as _.
|
// Firefox would save a % as _.
|
||||||
|
|||||||
+4
-1
@@ -11,7 +11,9 @@
|
|||||||
"typecheck": "vue-tsc",
|
"typecheck": "vue-tsc",
|
||||||
"lint": "biome check",
|
"lint": "biome check",
|
||||||
"format": "biome check --write",
|
"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:install": "playwright install chromium firefox",
|
||||||
"test:large": "LARGE=1 playwright test -g large"
|
"test:large": "LARGE=1 playwright test -g large"
|
||||||
},
|
},
|
||||||
@@ -25,6 +27,7 @@
|
|||||||
"@vitejs/plugin-vue": "^6.0.10",
|
"@vitejs/plugin-vue": "^6.0.10",
|
||||||
"typescript": "~6.0.3",
|
"typescript": "~6.0.3",
|
||||||
"vite": "^8.3.5",
|
"vite": "^8.3.5",
|
||||||
|
"vitest": "^5.0.5",
|
||||||
"vue-tsc": "^3.3.13",
|
"vue-tsc": "^3.3.13",
|
||||||
"ws": "8.22.0"
|
"ws": "8.22.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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/**' });
|
||||||
Generated
+189
@@ -188,6 +188,9 @@ importers:
|
|||||||
vite:
|
vite:
|
||||||
specifier: ^8.3.5
|
specifier: ^8.3.5
|
||||||
version: 8.3.5(@types/node@26.6.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:
|
vue-tsc:
|
||||||
specifier: ^3.3.13
|
specifier: ^3.3.13
|
||||||
version: 3.3.13(typescript@6.0.3)
|
version: 3.3.13(typescript@6.0.3)
|
||||||
@@ -283,9 +286,16 @@ packages:
|
|||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [win32]
|
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':
|
'@jridgewell/sourcemap-codec@1.6.0':
|
||||||
resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
|
resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
|
||||||
|
|
||||||
|
'@jridgewell/trace-mapping@0.3.31':
|
||||||
|
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||||
|
|
||||||
'@oxc-project/types@0.155.0':
|
'@oxc-project/types@0.155.0':
|
||||||
resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==}
|
resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==}
|
||||||
|
|
||||||
@@ -393,6 +403,15 @@ packages:
|
|||||||
'@rolldown/pluginutils@1.0.1':
|
'@rolldown/pluginutils@1.0.1':
|
||||||
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
|
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':
|
'@types/node@26.6.5':
|
||||||
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
|
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
|
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||||
vue: ^3.2.25 || ^3.6.0-rc.10
|
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':
|
'@volar/language-core@2.4.28':
|
||||||
resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==}
|
resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==}
|
||||||
|
|
||||||
@@ -450,6 +483,14 @@ packages:
|
|||||||
alien-signals@3.2.1:
|
alien-signals@3.2.1:
|
||||||
resolution: {integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==}
|
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:
|
csstype@3.2.3:
|
||||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||||
|
|
||||||
@@ -461,9 +502,19 @@ packages:
|
|||||||
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
|
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
|
||||||
engines: {node: '>=0.12'}
|
engines: {node: '>=0.12'}
|
||||||
|
|
||||||
|
es-module-lexer@2.3.2:
|
||||||
|
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
|
||||||
|
|
||||||
estree-walker@2.0.2:
|
estree-walker@2.0.2:
|
||||||
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
|
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:
|
fdir@6.5.0:
|
||||||
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
||||||
engines: {node: '>=12.0.0'}
|
engines: {node: '>=12.0.0'}
|
||||||
@@ -555,6 +606,9 @@ packages:
|
|||||||
magic-string@0.30.21:
|
magic-string@0.30.21:
|
||||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
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:
|
muggle-string@0.4.1:
|
||||||
resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==}
|
resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==}
|
||||||
|
|
||||||
@@ -563,6 +617,10 @@ packages:
|
|||||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||||
hasBin: true
|
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:
|
path-browserify@1.0.1:
|
||||||
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
|
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
|
||||||
|
|
||||||
@@ -596,6 +654,17 @@ packages:
|
|||||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||||
engines: {node: '>=0.10.0'}
|
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:
|
tinyglobby@0.2.17:
|
||||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||||
engines: {node: '>=12.0.0'}
|
engines: {node: '>=12.0.0'}
|
||||||
@@ -651,6 +720,47 @@ packages:
|
|||||||
yaml:
|
yaml:
|
||||||
optional: true
|
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:
|
vscode-uri@3.2.0:
|
||||||
resolution: {integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==}
|
resolution: {integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==}
|
||||||
|
|
||||||
@@ -668,6 +778,11 @@ packages:
|
|||||||
typescript:
|
typescript:
|
||||||
optional: true
|
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:
|
ws@8.22.0:
|
||||||
resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}
|
resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}
|
||||||
engines: {node: '>=10.0.0'}
|
engines: {node: '>=10.0.0'}
|
||||||
@@ -738,8 +853,15 @@ snapshots:
|
|||||||
'@biomejs/cli-win32-x64@2.6.3':
|
'@biomejs/cli-win32-x64@2.6.3':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@jridgewell/resolve-uri@3.1.2': {}
|
||||||
|
|
||||||
'@jridgewell/sourcemap-codec@1.6.0': {}
|
'@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': {}
|
'@oxc-project/types@0.155.0': {}
|
||||||
|
|
||||||
'@playwright/test@1.64.1':
|
'@playwright/test@1.64.1':
|
||||||
@@ -793,6 +915,15 @@ snapshots:
|
|||||||
|
|
||||||
'@rolldown/pluginutils@1.0.1': {}
|
'@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':
|
'@types/node@26.6.5':
|
||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 8.9.0
|
undici-types: 8.9.0
|
||||||
@@ -803,6 +934,17 @@ snapshots:
|
|||||||
vite: 8.3.5(@types/node@26.6.5)
|
vite: 8.3.5(@types/node@26.6.5)
|
||||||
vue: 3.5.44(typescript@6.0.3)
|
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':
|
'@volar/language-core@2.4.28':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@volar/source-map': 2.4.28
|
'@volar/source-map': 2.4.28
|
||||||
@@ -883,14 +1025,26 @@ snapshots:
|
|||||||
|
|
||||||
alien-signals@3.2.1: {}
|
alien-signals@3.2.1: {}
|
||||||
|
|
||||||
|
assertion-error@2.0.1: {}
|
||||||
|
|
||||||
|
chai@6.3.0: {}
|
||||||
|
|
||||||
csstype@3.2.3: {}
|
csstype@3.2.3: {}
|
||||||
|
|
||||||
detect-libc@2.1.2: {}
|
detect-libc@2.1.2: {}
|
||||||
|
|
||||||
entities@7.0.1: {}
|
entities@7.0.1: {}
|
||||||
|
|
||||||
|
es-module-lexer@2.3.2: {}
|
||||||
|
|
||||||
estree-walker@2.0.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):
|
fdir@6.5.0(picomatch@4.0.7):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@@ -951,10 +1105,16 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@jridgewell/sourcemap-codec': 1.6.0
|
'@jridgewell/sourcemap-codec': 1.6.0
|
||||||
|
|
||||||
|
magic-string@1.4.5:
|
||||||
|
dependencies:
|
||||||
|
'@jridgewell/sourcemap-codec': 1.6.0
|
||||||
|
|
||||||
muggle-string@0.4.1: {}
|
muggle-string@0.4.1: {}
|
||||||
|
|
||||||
nanoid@3.3.20: {}
|
nanoid@3.3.20: {}
|
||||||
|
|
||||||
|
obug@3.0.0: {}
|
||||||
|
|
||||||
path-browserify@1.0.1: {}
|
path-browserify@1.0.1: {}
|
||||||
|
|
||||||
picocolors@1.1.1: {}
|
picocolors@1.1.1: {}
|
||||||
@@ -996,6 +1156,12 @@ snapshots:
|
|||||||
|
|
||||||
source-map-js@1.2.2: {}
|
source-map-js@1.2.2: {}
|
||||||
|
|
||||||
|
std-env@4.3.0: {}
|
||||||
|
|
||||||
|
tinybench@6.2.2: {}
|
||||||
|
|
||||||
|
tinyexec@1.3.1: {}
|
||||||
|
|
||||||
tinyglobby@0.2.17:
|
tinyglobby@0.2.17:
|
||||||
dependencies:
|
dependencies:
|
||||||
fdir: 6.5.0(picomatch@4.0.7)
|
fdir: 6.5.0(picomatch@4.0.7)
|
||||||
@@ -1016,6 +1182,27 @@ snapshots:
|
|||||||
'@types/node': 26.6.5
|
'@types/node': 26.6.5
|
||||||
fsevents: 2.3.3
|
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: {}
|
vscode-uri@3.2.0: {}
|
||||||
|
|
||||||
vue-tsc@3.3.13(typescript@6.0.3):
|
vue-tsc@3.3.13(typescript@6.0.3):
|
||||||
@@ -1034,4 +1221,6 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
typescript: 6.0.3
|
typescript: 6.0.3
|
||||||
|
|
||||||
|
why-is-node-running@3.2.1: {}
|
||||||
|
|
||||||
ws@8.22.0: {}
|
ws@8.22.0: {}
|
||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
// Streams received files into the browser's download manager. It is the only script besides the app
|
// 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
|
// 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
|
// 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.
|
// 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();
|
const chunk = download.chunks.shift();
|
||||||
if (chunk) {
|
if (chunk) {
|
||||||
download.read += chunk.byteLength;
|
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) {
|
if (download.read - download.reported >= 2 ** 20) {
|
||||||
download.reported = download.read;
|
download.reported = download.read;
|
||||||
port.postMessage(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
|
// 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.
|
// finally done (queued as the end marker null) or an error. Pings come in between.
|
||||||
self.addEventListener('message', ({ data, ports: [port] }) => {
|
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 (data.ping) return;
|
||||||
if (port) return open(data.id, data, port);
|
if (port) return open(data.id, data, port);
|
||||||
const download = downloads.get(data.id);
|
const download = downloads.get(data.id);
|
||||||
@@ -77,7 +77,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => {
|
|||||||
|
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
const id = new URL(event.request.url).pathname.split('/').pop();
|
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)
|
if (!id)
|
||||||
return event.respondWith(
|
return event.respondWith(
|
||||||
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
|
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
|
||||||
|
|||||||
+1462
File diff suppressed because it is too large.
Load diff
+148
-222
@@ -1,3 +1,5 @@
|
|||||||
|
import { type Download, downloadsReady, startDownload } from './download';
|
||||||
|
|
||||||
export const DEFAULT_TRACKERS = [
|
export const DEFAULT_TRACKERS = [
|
||||||
'wss://tracker.pagequit.net',
|
'wss://tracker.pagequit.net',
|
||||||
'wss://tracker.webtorrent.dev',
|
'wss://tracker.webtorrent.dev',
|
||||||
@@ -11,6 +13,10 @@ export const DEFAULT_STUN_SERVERS = [
|
|||||||
'stun:stun.nextcloud.com:443',
|
'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.
|
// 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.
|
// Read whenever a connection or tracker socket is created, so changes apply to the next one.
|
||||||
export const settings = {
|
export const settings = {
|
||||||
@@ -19,41 +25,34 @@ export const settings = {
|
|||||||
trackers: [...DEFAULT_TRACKERS],
|
trackers: [...DEFAULT_TRACKERS],
|
||||||
};
|
};
|
||||||
|
|
||||||
const CHUNK_SIZE = 16 * 1024;
|
export const CHUNK_SIZE = 16 * 1024;
|
||||||
const MAX_BUFFERED = 1024 * 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
|
// 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.
|
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM.
|
||||||
const WINDOW = 8 * 1024 * 1024;
|
export 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;
|
|
||||||
const ICE_GRACE = 300;
|
const ICE_GRACE = 300;
|
||||||
const ICE_TIMEOUT = 5000;
|
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;
|
const PROBE_TIMEOUT = 2000;
|
||||||
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
|
// 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,
|
// 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
|
// 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.
|
// 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
|
// 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,
|
// 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.
|
// 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.
|
// 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;
|
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.
|
// 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
|
// 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.
|
// 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.
|
// 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 = {
|
export type Check = {
|
||||||
local: string;
|
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
|
// 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.
|
// the session would keep every connection a rejected or failed peer left behind until it ends.
|
||||||
function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
|
export function own<T extends { close: () => void }>(signal: AbortSignal, resource: T) {
|
||||||
const closeResource = resource.close.bind(resource);
|
const closeResource = resource.close.bind(resource);
|
||||||
// Without the abort event, WebSocket.close() would take it for a close code and throw.
|
// Without the abort event, WebSocket.close() would take it for a close code and throw.
|
||||||
const close = () => closeResource();
|
const close = () => closeResource();
|
||||||
@@ -115,14 +114,14 @@ function own<T extends { close: () => void }>(signal: AbortSignal, resource: T)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Closing everything fires events of its own, none of them reaches the caller after the abort.
|
// Closing everything fires events of its own, none of them reaches the caller after the abort.
|
||||||
function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
|
export function live<T extends Record<string, (...args: never[]) => void>>(events: T, signal: AbortSignal) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
|
Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]),
|
||||||
) as T;
|
) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Runs expire after ms unless closed before, cleared with the session.
|
// 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(() => {
|
const timer = setTimeout(() => {
|
||||||
owned.close();
|
owned.close();
|
||||||
expire();
|
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<typeof probeFrom> | 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
|
// 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,
|
// 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
|
// 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
|
// 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.
|
// own gets none reported (browsers drop it as redundant) and probes them all for every connection.
|
||||||
function stunServer(signal: AbortSignal) {
|
// The page has one, see stun, a test makes its own with a probe of its own.
|
||||||
if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined);
|
export function stunChoice(answers = probe) {
|
||||||
const key = settings.stunServers.join('\n');
|
let current: ReturnType<typeof probeFrom> | undefined;
|
||||||
if (stun?.key !== key || stun.stopped) {
|
// Where the next probe of the list with key starts, if not at its first server.
|
||||||
stun = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
|
let resume: { key: string; at: number } | undefined;
|
||||||
resume = 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.
|
const stun = stunChoice();
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function createPeerConnection(signal: AbortSignal) {
|
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 }] : [] }));
|
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
|
// biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above
|
||||||
type Message = Record<string, any>;
|
type Message = Record<string, any>;
|
||||||
|
|
||||||
function parse(data: unknown): Message | undefined {
|
export function parse(data: unknown): Message | undefined {
|
||||||
if (typeof data !== 'string') return;
|
if (typeof data !== 'string') return;
|
||||||
try {
|
try {
|
||||||
const message = JSON.parse(data);
|
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.
|
// 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 {
|
try {
|
||||||
return { type, sdp: atob(code.replace(/\s/g, '')) };
|
return { type, sdp: atob(code.replace(/\s/g, '')) };
|
||||||
} catch {
|
} catch {
|
||||||
@@ -262,7 +268,7 @@ function randomBinary(length: number) {
|
|||||||
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
|
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
|
// The largest multiple of the alphabet's length a byte holds. The bytes above would make the first
|
||||||
// characters likelier, they are dropped.
|
// characters likelier, they are dropped.
|
||||||
const CODE_LIMIT = 256 - (256 % CODE_CHARS.length);
|
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
|
// 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.
|
// 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.
|
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
|
||||||
const SALT_WINDOW = 6 * 60_000;
|
export const SALT_WINDOW = 6 * 60_000;
|
||||||
const CODE_LENGTH = 11;
|
export const CODE_LENGTH = 11;
|
||||||
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
|
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,
|
// 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.
|
// 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);
|
const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16);
|
||||||
if (own === undefined) return salt;
|
if (own === undefined) return salt;
|
||||||
if (!own.trim()) throw new Error('the own salt is empty');
|
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.
|
// A sender's new code and its salt.
|
||||||
function newCode(own?: string) {
|
export function newCode(own?: string) {
|
||||||
const at = clockWindow(Date.now());
|
const at = clockWindow(Date.now());
|
||||||
return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) };
|
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
|
// 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.
|
// 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)))
|
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`);
|
throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`);
|
||||||
const now = clockWindow(Date.now());
|
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
|
// 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
|
// 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.
|
// 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 text = new TextEncoder();
|
||||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||||
const bits = await crypto.subtle.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
|
// 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
|
// 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.
|
// 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 text = new TextEncoder();
|
||||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||||
const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) };
|
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.
|
// 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.
|
// atob throws on what isn't base64, decrypt on anything else.
|
||||||
try {
|
try {
|
||||||
const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0));
|
const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0));
|
||||||
@@ -411,13 +417,13 @@ async function gatherIce(pc: RTCPeerConnection) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
const [server] = pc.getConfiguration().iceServers ?? [];
|
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
|
// 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
|
// 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.
|
// a public address of its own offers none either, see stunChoice, so it's a hint, not a diagnosis.
|
||||||
function stunHint(pc: RTCPeerConnection, peer: string) {
|
export function stunHint(pc: RTCPeerConnection, peer: string) {
|
||||||
const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? '');
|
const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? '');
|
||||||
const local = offersPublic(pc.localDescription);
|
const local = offersPublic(pc.localDescription);
|
||||||
const remote = offersPublic(pc.remoteDescription);
|
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
|
// 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
|
// brute force with matching certificates. My local code must equal the peer's remote code and vice
|
||||||
// versa, otherwise someone interposed on the signaling.
|
// versa, otherwise someone interposed on the signaling.
|
||||||
function securityCheck(pc: RTCPeerConnection) {
|
export function securityCheck(pc: RTCPeerConnection) {
|
||||||
const short = (sdp = '') =>
|
const short = (sdp = '') =>
|
||||||
sdp
|
sdp
|
||||||
.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]
|
.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.
|
// 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.
|
// 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();
|
[...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
|
// 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
|
// 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
|
// 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.
|
// 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 local = pc.localDescription!;
|
||||||
const remote = pc.remoteDescription!;
|
const remote = pc.remoteDescription!;
|
||||||
const statement = (type: string, own: string, peer: string) =>
|
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
|
// 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
|
// 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.
|
// and the reason is an error. From start on, sendFile and receiveFile handle a loss.
|
||||||
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
export type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
||||||
|
|
||||||
function connected(
|
function connected(
|
||||||
pc: RTCPeerConnection,
|
pc: RTCPeerConnection,
|
||||||
@@ -548,7 +554,7 @@ function connected(
|
|||||||
// { done } once the download manager read the last byte, or { error } when its download was
|
// { 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
|
// cancelled or failed. Any other message, or one out of turn, is ignored. Every way out of the
|
||||||
// transfer closes the connection.
|
// transfer closes the connection.
|
||||||
async function sendFile(
|
export async function sendFile(
|
||||||
pc: RTCPeerConnection,
|
pc: RTCPeerConnection,
|
||||||
channel: RTCDataChannel,
|
channel: RTCDataChannel,
|
||||||
file: File,
|
file: File,
|
||||||
@@ -640,63 +646,19 @@ async function sendFile(
|
|||||||
if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest');
|
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
|
// 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
|
// 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
|
// trusted: a malformed offer ends the connection, more bytes than offered or beyond the window fail
|
||||||
// the download. Once it ended, the connection closes.
|
// the download. Once it ended, the connection closes. startDownload saves it, see src/download.ts.
|
||||||
function receiveFile(
|
export function receiveFile(
|
||||||
pc: RTCPeerConnection,
|
pc: RTCPeerConnection,
|
||||||
channel: RTCDataChannel,
|
channel: RTCDataChannel,
|
||||||
events: ReceiveEvents,
|
events: ReceiveEvents,
|
||||||
handshake: Handshake,
|
handshake: Handshake,
|
||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
) {
|
) {
|
||||||
const id = crypto.randomUUID();
|
|
||||||
const frames: HTMLIFrameElement[] = [];
|
|
||||||
let meta: { name: string; size: number } | undefined;
|
let meta: { name: string; size: number } | undefined;
|
||||||
|
let saving: Download | undefined;
|
||||||
let received = 0;
|
let received = 0;
|
||||||
// By the download manager. The rest of received is held in this page and the worker.
|
// By the download manager. The rest of received is held in this page and the worker.
|
||||||
let read = 0;
|
let read = 0;
|
||||||
@@ -704,86 +666,50 @@ function receiveFile(
|
|||||||
let downloading = false;
|
let downloading = false;
|
||||||
let complete = false;
|
let complete = false;
|
||||||
let ended = false;
|
let ended = false;
|
||||||
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
|
|
||||||
let worker: Promise<ServiceWorker | undefined> = Promise.resolve(undefined);
|
|
||||||
const post = (message: object, transfer: Transferable[] = []) =>
|
|
||||||
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
|
||||||
// To the sender, see sendFile.
|
// To the sender, see sendFile.
|
||||||
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
|
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.
|
// A data channel closes only after sending what it buffered, so the last reply still arrives.
|
||||||
channel.addEventListener('close', () => pc.close());
|
channel.addEventListener('close', () => pc.close());
|
||||||
|
|
||||||
let keepalive: ReturnType<typeof setInterval> | 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) {
|
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;
|
if (ended) return;
|
||||||
ended = true;
|
ended = true;
|
||||||
post({ error: reason });
|
|
||||||
reply({ error: reason });
|
reply({ error: reason });
|
||||||
channel.close();
|
channel.close();
|
||||||
events.error(`download failed: ${reason}`);
|
events.error(`download failed: ${reason}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function startDownload() {
|
function startSaving(file: { name: string; size: number }) {
|
||||||
worker = holdWorker().then(
|
saving = startDownload(file, {
|
||||||
({ frame, worker }) => {
|
read: (bytes) => {
|
||||||
frames.push(frame);
|
read = bytes;
|
||||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
events.progress(read, file.size);
|
||||||
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
|
reply({ read });
|
||||||
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;
|
|
||||||
},
|
},
|
||||||
(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(() => {
|
void handshake.checked.then(() => {
|
||||||
@@ -795,7 +721,7 @@ function receiveFile(
|
|||||||
|
|
||||||
function receivedAll() {
|
function receivedAll() {
|
||||||
complete = true;
|
complete = true;
|
||||||
post({ done: true });
|
saving!.end();
|
||||||
events.log('received');
|
events.log('received');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -809,7 +735,7 @@ function receiveFile(
|
|||||||
events.log(`receiving ${meta!.name}`);
|
events.log(`receiving ${meta!.name}`);
|
||||||
events.status('transfer', 'Receiving');
|
events.status('transfer', 'Receiving');
|
||||||
events.progress(0, meta!.size);
|
events.progress(0, meta!.size);
|
||||||
startDownload();
|
startSaving(meta!);
|
||||||
reply({ start: true });
|
reply({ start: true });
|
||||||
if (!meta!.size) receivedAll();
|
if (!meta!.size) receivedAll();
|
||||||
}
|
}
|
||||||
@@ -832,7 +758,7 @@ function receiveFile(
|
|||||||
if (received > meta!.size) return fail('the sender sent more than it offered');
|
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.
|
// 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');
|
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();
|
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
|
// 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
|
// 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.
|
// without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names.
|
||||||
function trackerSocket(
|
export function trackerSocket(
|
||||||
url: string,
|
url: string,
|
||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
events: Events,
|
events: Events,
|
||||||
@@ -998,7 +924,7 @@ function trackerSocket(
|
|||||||
type Tracker = ReturnType<typeof trackerSocket>;
|
type Tracker = ReturnType<typeof trackerSocket>;
|
||||||
|
|
||||||
// Once none of the trackers is left: what the user can do about it, and why if any rejected.
|
// 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 rejected = trackers.flatMap((tracker) => tracker?.rejected ?? []);
|
||||||
const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable';
|
const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable';
|
||||||
return `${reason}, check the list under Servers and try again`;
|
return `${reason}, check the list under Servers and try again`;
|
||||||
|
|||||||
+155
@@ -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<typeof setInterval> | 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<ServiceWorker | undefined> = 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));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+1
-1
@@ -16,5 +16,5 @@
|
|||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"noEmit": 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"]
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
|
/// <reference types="vitest/config" />
|
||||||
import vue from '@vitejs/plugin-vue';
|
import vue from '@vitejs/plugin-vue';
|
||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [vue()],
|
plugins: [vue()],
|
||||||
|
// Playwright runs e2e.spec.ts and backend/, which Vitest would pick up too.
|
||||||
|
test: { include: ['src/**/*.test.ts'] },
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user