Version the protocol for 1.0, fail downloads the page abandoned
PROTOCOL (hellcon/1) goes in front of the PBKDF2 salt and names the data channel, so different versions never meet via a tracker and the manual receiver tells a sender on another protocol apart. The footer shows it, the receiver's hints ask to compare it. Forks are asked to name their own. public/sw.js and the page exchange a VERSION, a mismatch fails the download with outdated. The worker fails a download after 20 s without a chunk or ping from its page, else Firefox saves the truncated file of a closed tab as complete. The build uses relative links and works under any path. On https only wss: trackers and ws: to this device are accepted, one the browser refuses to open counts as lost. Also: a file read short stops the transfer, an offer waiting on a lost tracker isn't answered, a share ended while its key was derived opens no tracker, and tracker and receiver errors lose hidden characters. The README lists what isn't planned and the phone limitation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
44a8a72261
commit
ac4d496a48
11 files changed
+399
-56
No files matched your search
@@ -14,6 +14,10 @@ size limit: the file goes directly to the other person and is never stored on a
|
||||
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
||||
tab was doing.
|
||||
|
||||
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
|
||||
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
|
||||
protocol.
|
||||
|
||||
### Without a tracker
|
||||
|
||||
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
|
||||
@@ -114,7 +118,9 @@ Then serve the `dist/` folder, with these requirements:
|
||||
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
|
||||
trying it out).
|
||||
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
|
||||
HellCon must reach it unchanged, so don't rewrite them to `index.html`.
|
||||
HellCon must reach it unchanged, so don't rewrite them to `index.html`. Any path works, e.g.
|
||||
`https://example.org/hellcon/`, with the trailing slash: the page links its files relative to it,
|
||||
so redirect `/hellcon` there.
|
||||
|
||||
Recommended, as response headers, a `<meta>` can't set them (`index.html` sets
|
||||
`Referrer-Policy: no-referrer` and the rest of its Content-Security-Policy itself, which keeps out
|
||||
@@ -133,12 +139,35 @@ Your own tracker and STUN server are optional, any public ones work. `backend/`
|
||||
Compose services: a tracker that only does what HellCon needs, with an Origin allowlist and limits,
|
||||
and coturn as STUN server. `backend/compose.yaml` says how to set them up.
|
||||
|
||||
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
|
||||
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
|
||||
|
||||
## Not planned
|
||||
|
||||
These were considered and decided against, please don't ask for them without a new reason. HellCon
|
||||
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
|
||||
needs infrastructure of its own or only helps small files doesn't pay off.
|
||||
|
||||
- **The code in a share link:** the code would end up in the browser history and wherever links get
|
||||
handled, for one click less.
|
||||
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
|
||||
the code anyway.
|
||||
- **Saving without the service worker,** holding the file in memory instead: useless for files of
|
||||
several GB.
|
||||
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
|
||||
- **A longer or extendable share,** **several files as a zip,** and **resuming in Chromium:** not
|
||||
for now.
|
||||
- **Keeping a phone sending in the background,** e.g. with a silent audio loop: the sender's page
|
||||
has to stay in front.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
|
||||
but Firefox keeps showing the download as in progress until you cancel it.
|
||||
- **Chromium:** notices a vanished sender only after about 16 seconds.
|
||||
- An interrupted transfer can't be resumed, it starts over.
|
||||
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
|
||||
background. Receiving keeps going.
|
||||
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
|
||||
work, and HellCon tells you so.
|
||||
|
||||
|
||||
@@ -10,11 +10,6 @@
|
||||
own salt too. Open which ones to keep, and how a kept one that differs from the other side's would
|
||||
show, instead of silently breaking a share.
|
||||
|
||||
- Version the protocol for 1.0: put a version into the key derivation, e.g. `hellcon/1 <salt>` as
|
||||
the PBKDF2 salt in `secrets`. Until then any change to it silently breaks sharing between
|
||||
deployments on different versions, the receiver only sees "No sender with this code". Open how a
|
||||
mismatch would be reported, e.g. by trying the previous version's swarm too.
|
||||
|
||||
- Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs
|
||||
"screen may lock" each time the page is visible again, open whether once per session is enough.
|
||||
`awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is
|
||||
@@ -22,6 +17,11 @@
|
||||
|
||||
## Open observations
|
||||
|
||||
- A phone can't send in the background: with Brave on Android (Pixel), the connection is lost as
|
||||
soon as the sender's page goes to the background. Receiving survives it, likely because the
|
||||
browser's download manager runs as a foreground service while the file streams into it. The wake
|
||||
lock only keeps the screen from timing out, the sender's page has to stay in front.
|
||||
|
||||
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
|
||||
logs "download failed: connection lost", but the download stays "in progress" until the user
|
||||
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
|
||||
|
||||
+82
-9
@@ -28,11 +28,13 @@ 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 and CONNECT_TIMEOUT in src/core.ts, DOWNLOAD_GRACE in src/download.ts.
|
||||
// WINDOW, PROBE_TIMEOUT and CONNECT_TIMEOUT in src/core.ts, DOWNLOAD_GRACE in src/download.ts, SILENCE
|
||||
// in public/sw.js.
|
||||
const WINDOW = 8 * 2 ** 20;
|
||||
const PROBE_TIMEOUT = 2000;
|
||||
const CONNECT_TIMEOUT = 30_000;
|
||||
const DOWNLOAD_GRACE = 1000;
|
||||
const SILENCE = 20_000;
|
||||
// Every page's clock starts a second into the salt's window from 12:00 to 12:06 UTC unless a test
|
||||
// sets another time, so the test knows when the window of a code ends.
|
||||
const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1);
|
||||
@@ -135,11 +137,15 @@ test.afterAll(async () => {
|
||||
stun.close();
|
||||
});
|
||||
|
||||
// init runs in the page before the app. base is the app's URL, the dev server's by default. time is
|
||||
// where the page's clock starts.
|
||||
// init runs in the page before the app, several in order. base is the app's URL, the dev server's by
|
||||
// default. time is where the page's clock starts.
|
||||
async function open(
|
||||
name: string,
|
||||
{ init, base = url, time = TEST_TIME }: { init?: () => void; base?: string; time?: number } = {},
|
||||
{
|
||||
init = [],
|
||||
base = url,
|
||||
time = TEST_TIME,
|
||||
}: { init?: (() => void) | (() => void)[]; base?: string; time?: number } = {},
|
||||
) {
|
||||
browsers[name] ??= BROWSERS[name]!.launch();
|
||||
const browser = await browsers[name];
|
||||
@@ -153,7 +159,7 @@ async function open(
|
||||
page.on('pageerror', (error) => errors.push(`${name}: ${error.message}`));
|
||||
await page.addInitScript(trackPeers);
|
||||
await page.addInitScript(failOnCsp);
|
||||
if (init) await page.addInitScript(init);
|
||||
for (const script of [init].flat()) await page.addInitScript(script);
|
||||
await page.goto(base);
|
||||
return page;
|
||||
}
|
||||
@@ -224,6 +230,24 @@ async function expectClosed(page: Page) {
|
||||
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
||||
}
|
||||
|
||||
// Init script for a receiver: it speaks another version to its service worker than sw.js, as if one
|
||||
// of them was updated. The page posts from the hidden frame's worker, the script runs there too.
|
||||
function otherVersion() {
|
||||
const post = ServiceWorker.prototype.postMessage as (this: ServiceWorker, ...args: unknown[]) => void;
|
||||
ServiceWorker.prototype.postMessage = function (this: ServiceWorker, message: { version?: number }, ...rest) {
|
||||
post.call(this, message.version ? { ...message, version: message.version + 1 } : message, ...rest);
|
||||
};
|
||||
}
|
||||
|
||||
// Init script for a receiver: its pings never reach its service worker, as if its timers were held
|
||||
// back in the background. Like otherVersion, it runs in the hidden frame the page posts from.
|
||||
function dropPings() {
|
||||
const post = ServiceWorker.prototype.postMessage as (this: ServiceWorker, ...args: unknown[]) => void;
|
||||
ServiceWorker.prototype.postMessage = function (this: ServiceWorker, message: { ping?: boolean }, ...rest) {
|
||||
if (!message.ping) post.call(this, message, ...rest);
|
||||
};
|
||||
}
|
||||
|
||||
// Init script for a receiver: holds back its { read } reports to the sender until release(), as if
|
||||
// the download manager read nothing, and counts the bytes that arrive. It runs in the hidden frames
|
||||
// too, only the app's own window counts.
|
||||
@@ -534,13 +558,18 @@ for (const [from, to] of [
|
||||
});
|
||||
}
|
||||
|
||||
test('build: chromium sends to firefox from the production build', async () => {
|
||||
// Served below the root of the host, which the build has to work with too.
|
||||
test('build: chromium sends to firefox from the production build under a path', async () => {
|
||||
const outDir = test.info().outputPath('dist');
|
||||
await build({ logLevel: 'silent', build: { outDir, emptyOutDir: true } });
|
||||
const site = await preview({ logLevel: 'silent', build: { outDir }, preview: { port: 0 } });
|
||||
const site = await preview({ logLevel: 'silent', base: '/hellcon/', build: { outDir }, preview: { port: 0 } });
|
||||
try {
|
||||
const base = site.resolvedUrls!.local[0]!;
|
||||
expect(base).toMatch(/\/hellcon\/$/);
|
||||
const [sender, receiver] = await Promise.all([open('chromium', { base }), open('firefox', { base })]);
|
||||
for (const image of await sender.locator('img').all()) {
|
||||
expect(await image.evaluate((img: HTMLImageElement) => img.naturalWidth)).toBeGreaterThan(0);
|
||||
}
|
||||
await transfer('offline', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
|
||||
} finally {
|
||||
await site.close();
|
||||
@@ -676,6 +705,21 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect.poll(() => updated(receiver)).toBe(true);
|
||||
});
|
||||
|
||||
test(`update: ${name} fails a download its service worker speaks another version for`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name, { init: otherVersion })]);
|
||||
const source = await payload(randomBytes(1000));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('offline', sender, receiver, source);
|
||||
for (const page of [sender, receiver]) await page.click('#confirm');
|
||||
await receiver.click('#download');
|
||||
const reason = 'this page and its service worker are different versions, reload once no tab receives';
|
||||
await expect(receiver.locator('#receive-error')).toHaveText(`download failed: ${reason}`);
|
||||
await expect(sender.locator('#send-error')).toHaveText(`receiver stopped: ${reason}`);
|
||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
test(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||
const source = await payload(Buffer.alloc(RUNNING_SIZE));
|
||||
@@ -1112,6 +1156,35 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Without the page, nothing keeps the worker alive. Firefox would stop it 30 s later and save what it
|
||||
// had as the complete file, see SILENCE in public/sw.js.
|
||||
test(`disconnect: ${name} saves no truncated file when the receiving tab closes`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
|
||||
const source = await payload(randomBytes(HELD_SIZE));
|
||||
|
||||
const { download } = await start('offline', sender, receiver, source);
|
||||
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||
await receiver.close();
|
||||
// Firefox reports no failure, but removes the file.
|
||||
if (!(await download.failure())) await expect(readFile(await download.path())).rejects.toThrow('ENOENT');
|
||||
});
|
||||
|
||||
test(`disconnect: ${name} fails a download its service worker heard nothing of for too long`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name, { init: [holdReads, dropPings] })]);
|
||||
const source = await payload(randomBytes(HELD_SIZE));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await start('offline', sender, receiver, source);
|
||||
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||
const reason = 'the service worker heard nothing from this page for too long';
|
||||
await expect(receiver.locator('#receive-error')).toHaveText(`download failed: ${reason}`, {
|
||||
timeout: SILENCE + 10_000,
|
||||
});
|
||||
await expect(sender.locator('#send-error')).toHaveText(`receiver stopped: ${reason}`);
|
||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Stands in for every tracker the page connects to from now on: reply answers each message the page
|
||||
@@ -1171,7 +1244,7 @@ function middleman() {
|
||||
},
|
||||
offer() {
|
||||
toSender = new RTCPeerConnection();
|
||||
attach('sender', toSender.createDataChannel('file'), 'receiver');
|
||||
attach('sender', toSender.createDataChannel('hellcon/1'), 'receiver');
|
||||
return localSdp(toSender);
|
||||
},
|
||||
accept: (sdp) => toSender.setRemoteDescription({ type: 'answer', sdp }),
|
||||
@@ -1237,7 +1310,7 @@ async function interpose(middle: Page, code: string, toSender: Announce[], toRec
|
||||
// The key src/core.ts seals the signaling with, for a code made at TEST_TIME without an own salt: the
|
||||
// salt is the start of TEST_TIME's window. src/core.test.ts checks the derivation itself.
|
||||
function signalingKey(code: string) {
|
||||
const master = pbkdf2Sync(code, `hellcon ${new Date(TEST_TIME).toISOString().slice(0, 16)}`, 600_000, 32, 'sha256');
|
||||
const master = pbkdf2Sync(code, `hellcon/1 ${new Date(TEST_TIME).toISOString().slice(0, 16)}`, 600_000, 32, 'sha256');
|
||||
return Buffer.from(hkdfSync('sha256', master, '', 'signaling', 32));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "hellcon",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
+33
-8
@@ -2,13 +2,36 @@
|
||||
// because service workers can only be registered from a same-origin script URL. Registered with the
|
||||
// scope download/ by src/download.ts, its counterpart in the page, it sees no other requests.
|
||||
|
||||
// Of the messages with the page, see VERSION in src/download.ts.
|
||||
const VERSION = 1;
|
||||
|
||||
// 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.
|
||||
const downloads = new Map();
|
||||
// Responses by download id, until the download navigation fetches them. Each is served only once.
|
||||
const responses = new Map();
|
||||
// The page pings every KEEPALIVE while a transfer stalls, see src/download.ts. Silent for this long,
|
||||
// it is gone, e.g. its tab was closed: Firefox would stop this worker 30 s after the last event and
|
||||
// save the truncated file as complete. A failed stream leaves the download failed instead. A page
|
||||
// that is still there, only late, e.g. throttled in the background, is told with silent.
|
||||
const SILENCE = 20_000;
|
||||
|
||||
function open(id, { name, size }, port) {
|
||||
function watch(id, download) {
|
||||
clearTimeout(download.watchdog);
|
||||
download.watchdog = setTimeout(() => {
|
||||
download.controller.error(new Error('the page is gone'));
|
||||
forget(id);
|
||||
download.port.postMessage('silent');
|
||||
}, SILENCE);
|
||||
}
|
||||
|
||||
function forget(id) {
|
||||
clearTimeout(downloads.get(id)?.watchdog);
|
||||
downloads.delete(id);
|
||||
}
|
||||
|
||||
function open(id, { version, name, size }, port) {
|
||||
if (version !== VERSION) return port.postMessage('outdated');
|
||||
// The page checks the sender's offer already. Anything else would throw below or lie to the browser.
|
||||
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
|
||||
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
|
||||
@@ -30,18 +53,19 @@ function open(id, { name, size }, port) {
|
||||
return controller.enqueue(chunk);
|
||||
}
|
||||
controller.close();
|
||||
downloads.delete(id);
|
||||
forget(id);
|
||||
port.postMessage('finished');
|
||||
},
|
||||
// The user cancelled the download.
|
||||
cancel: () => {
|
||||
downloads.delete(id);
|
||||
forget(id);
|
||||
port.postMessage('cancelled');
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
downloads.set(id, download);
|
||||
watch(id, download);
|
||||
|
||||
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
|
||||
const encoded = encodeURIComponent(name.toWellFormed()).replace(
|
||||
@@ -57,17 +81,18 @@ function open(id, { name, size }, port) {
|
||||
port.postMessage('ready');
|
||||
}
|
||||
|
||||
// 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.
|
||||
// The page posts its version and 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/download.ts.
|
||||
if (data.ping) return;
|
||||
if (port) return open(data.id, data, port);
|
||||
const download = downloads.get(data.id);
|
||||
if (!download) return;
|
||||
watch(data.id, download);
|
||||
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/download.ts.
|
||||
if (data.ping) return;
|
||||
if (data.error) {
|
||||
download.controller.error(new Error(data.error));
|
||||
downloads.delete(data.id);
|
||||
forget(data.id);
|
||||
download.port.postMessage('failed');
|
||||
} else {
|
||||
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
|
||||
|
||||
+23
-6
@@ -11,6 +11,7 @@ import {
|
||||
formatTime,
|
||||
type Incoming,
|
||||
type Phase,
|
||||
PROTOCOL,
|
||||
type ReceiveEvents,
|
||||
randomCode,
|
||||
receiveViaTracker,
|
||||
@@ -46,9 +47,23 @@ function isStun(url: string) {
|
||||
return stunChecks.get(url)!;
|
||||
}
|
||||
|
||||
// Every # starts a fragment, which WebSocket rejects even when empty.
|
||||
const isTracker = (url: string) =>
|
||||
URL.canParse(url) && ['ws:', 'wss:'].includes(new URL(url).protocol) && !url.includes('#');
|
||||
// public/ in the build, which works under any path, see vite.config.ts.
|
||||
const BASE = import.meta.env.BASE_URL;
|
||||
|
||||
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
|
||||
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
|
||||
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
|
||||
const secure = location.protocol === 'https:';
|
||||
const isLocal = (hostname: string) =>
|
||||
hostname === 'localhost' ||
|
||||
hostname.endsWith('.localhost') ||
|
||||
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
|
||||
hostname === '[::1]';
|
||||
const isTracker = (url: string) => {
|
||||
if (!URL.canParse(url) || url.includes('#')) return false;
|
||||
const { protocol, hostname } = new URL(url);
|
||||
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
|
||||
};
|
||||
|
||||
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
|
||||
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
|
||||
@@ -349,7 +364,7 @@ document.addEventListener('visibilitychange', holdWakeLock);
|
||||
<template>
|
||||
<header>
|
||||
<div>
|
||||
<img src="/HellNet_alt.png" alt="" width="40" height="40" />
|
||||
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
|
||||
<h1>HellCon</h1>
|
||||
</div>
|
||||
<div id="options">
|
||||
@@ -574,7 +589,8 @@ document.addEventListener('visibilitychange', holdWakeLock);
|
||||
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label>
|
||||
<textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
|
||||
<p v-if="trackers.invalid.length">
|
||||
Skipped, not a ws: or wss: URL without #: {{ trackers.invalid.join(', ') }}
|
||||
Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
|
||||
{{ trackers.invalid.join(', ') }}
|
||||
</p>
|
||||
</section>
|
||||
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
|
||||
@@ -589,8 +605,9 @@ document.addEventListener('visibilitychange', holdWakeLock);
|
||||
|
||||
<footer>
|
||||
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||
<img src="/gitea.svg" alt="" width="20" height="20" />
|
||||
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
|
||||
Source code
|
||||
</a>
|
||||
<span>Protocol {{ PROTOCOL }}</span>
|
||||
</footer>
|
||||
</template>
|
||||
+155
-7
@@ -1,7 +1,7 @@
|
||||
// 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 { createDecipheriv, createHash, createHmac, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
|
||||
import { getEventListeners } from 'node:events';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
own,
|
||||
PBKDF2_ITERATIONS,
|
||||
PROOF_TIMEOUT,
|
||||
PROTOCOL,
|
||||
parse,
|
||||
prove,
|
||||
type ReceiveEvents,
|
||||
@@ -92,7 +93,7 @@ class FakeChannel extends Target {
|
||||
peer?: FakeChannel;
|
||||
// What this side drops instead of sending.
|
||||
drop = (_data: string | ArrayBuffer) => false;
|
||||
constructor(readonly label = 'file') {
|
||||
constructor(readonly label = PROTOCOL) {
|
||||
super();
|
||||
}
|
||||
set onopen(handler: ((event: Any) => unknown) | null) {
|
||||
@@ -476,7 +477,7 @@ describe('codes and salts', () => {
|
||||
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 master = pbkdf2Sync(code, `hellcon/1 ${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));
|
||||
@@ -725,6 +726,23 @@ describe('tracker socket', () => {
|
||||
expect(session.logs).toEqual(['wss://one.test unreachable']);
|
||||
});
|
||||
|
||||
it('takes a tracker the browser refuses to open for lost, once the caller has it', async () => {
|
||||
vi.stubGlobal(
|
||||
'WebSocket',
|
||||
class {
|
||||
constructor() {
|
||||
throw new DOMException('insecure', 'SecurityError');
|
||||
}
|
||||
},
|
||||
);
|
||||
const { session, tracker, lost } = socket('ws://one.test');
|
||||
expect(lost).not.toHaveBeenCalled();
|
||||
await settle();
|
||||
expect(lost).toHaveBeenCalledTimes(1);
|
||||
expect(session.logs).toEqual(['ws://one.test refused: insecure']);
|
||||
expect(tracker.alive()).toBe(false);
|
||||
});
|
||||
|
||||
it('gives up on a tracker that never answers', async () => {
|
||||
new FakeTracker('wss://one.test', () => undefined);
|
||||
const { session, tracker, lost } = socket();
|
||||
@@ -757,10 +775,13 @@ describe('tracker socket', () => {
|
||||
ws.deliver({ 'not json': undefined });
|
||||
ws.deliver({ 'failure reason': 'slow down' });
|
||||
ws.deliver({ 'failure reason': 'shutting down' });
|
||||
// Controls and bidi controls would fake log lines.
|
||||
ws.deliver({ 'failure reason': 'bye\nsecurity check passed\u202E' });
|
||||
expect(accepted.session.logs).toEqual([
|
||||
`wss://two.test: ${'x'.repeat(200)}`,
|
||||
'wss://two.test: slow down',
|
||||
'wss://two.test: shutting down',
|
||||
'wss://two.test: byesecurity check passed',
|
||||
]);
|
||||
expect(accepted.tracker.alive()).toBe(true);
|
||||
expect(accepted.lost).not.toHaveBeenCalled();
|
||||
@@ -877,6 +898,24 @@ describe('proof of the code', () => {
|
||||
return [a, b] as const;
|
||||
}
|
||||
|
||||
// The protocol in node:crypto, like the derivation in codes and salts: changing it splits old and new clients.
|
||||
it('proves with the key secrets derives, over the fingerprints as the protocol says', async () => {
|
||||
const master = pbkdf2Sync('abcdefghijk', 'hellcon/1 salt', PBKDF2_ITERATIONS, 32, 'sha256');
|
||||
const proofKey = Buffer.from(hkdfSync('sha256', master, '', 'proof', 64));
|
||||
const hmac = (statement: unknown) =>
|
||||
createHmac('sha256', proofKey).update(JSON.stringify(statement)).digest('base64');
|
||||
const { key } = await secrets('abcdefghijk', 'salt');
|
||||
const channel = new FakeChannel();
|
||||
channel.readyState = 'open';
|
||||
const end = vi.fn();
|
||||
const proven = prove(view('offer', 'AA', 'BB'), asChannel(channel), key, end);
|
||||
await until(() => channel.sent.length);
|
||||
expect(channel.sent).toEqual([JSON.stringify({ proof: hmac(['offer', ['sha-256 aa'], ['sha-256 bb']]) })]);
|
||||
channel.emit('message', { data: JSON.stringify({ proof: hmac(['answer', ['sha-256 bb'], ['sha-256 aa']]) }) });
|
||||
await proven;
|
||||
expect(end).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes on both sides with the same key and the same certificates', async () => {
|
||||
const shared = await key();
|
||||
const [a, b] = pair();
|
||||
@@ -1038,7 +1077,7 @@ describe('sending', () => {
|
||||
stopped.channel.receive({ ok: true });
|
||||
await until(() => stopped.channel.sent.length);
|
||||
stopped.channel.receive({ start: true });
|
||||
stopped.channel.receive({ error: `cancelled ${'x'.repeat(300)}` });
|
||||
stopped.channel.receive({ error: `cancelled\n\u202E ${'x'.repeat(300)}` });
|
||||
expect(stopped.session.errors).toEqual([`receiver stopped: cancelled ${'x'.repeat(190)}`]);
|
||||
expect(stopped.pc.signalingState).toBe('closed');
|
||||
|
||||
@@ -1060,6 +1099,17 @@ describe('sending', () => {
|
||||
unreadable.channel.receive({ start: true });
|
||||
await unreadable.done;
|
||||
expect(unreadable.session.errors).toEqual(['could not read gone.bin anymore']);
|
||||
|
||||
// Read short instead of failing.
|
||||
const shrunk = { name: 'shrunk.bin', size: 10, slice: () => ({ arrayBuffer: async () => new ArrayBuffer(5) }) };
|
||||
const short = sending(shrunk as unknown as File);
|
||||
short.check();
|
||||
short.channel.receive({ ok: true });
|
||||
await until(() => short.channel.sent.length);
|
||||
short.channel.receive({ start: true });
|
||||
await short.done;
|
||||
expect(short.session.errors).toEqual(['could not read shrunk.bin anymore']);
|
||||
expect(short.channel.bytes()).toBe(0);
|
||||
});
|
||||
|
||||
it('stops quietly when the connection closes before the transfer or the session ends', async () => {
|
||||
@@ -1228,6 +1278,14 @@ describe('receiving', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Data channels opened from here on carry another protocol's label.
|
||||
function otherProtocol() {
|
||||
const create = FakePeer.prototype.createDataChannel;
|
||||
return vi.spyOn(FakePeer.prototype, 'createDataChannel').mockImplementation(function (this: FakePeer, label: string) {
|
||||
return create.call(this, label === PROTOCOL ? 'other/1' : label);
|
||||
});
|
||||
}
|
||||
|
||||
describe('manual exchange', () => {
|
||||
// Sender and receiver connected by the manual codes, both shown the check.
|
||||
async function exchange(source: File) {
|
||||
@@ -1299,6 +1357,20 @@ describe('manual exchange', () => {
|
||||
await until(() => sender.checks[0]);
|
||||
});
|
||||
|
||||
it('refuses a sender on another protocol', async () => {
|
||||
const [sender, receiver] = [side(), side()];
|
||||
otherProtocol();
|
||||
const { offer, accept } = await createOffer(file(10), sender.events, sender.signal);
|
||||
await accept(await answerOffer(offer, receiver.events, receiver.signal));
|
||||
await until(() => sender.errors.length);
|
||||
expect(receiver.errors).toEqual([`the sender runs another protocol, both pages have to show protocol ${PROTOCOL}`]);
|
||||
expect(receiver.logged('the sender\'s protocol: "other/1"')).toBe(true);
|
||||
expect(receiver.checks).toEqual([]);
|
||||
expect(sender.errors).toEqual(['the receiver left before the transfer']);
|
||||
expect(sender.checks.at(-1)).toBeUndefined();
|
||||
expect(openPeers()).toEqual([]);
|
||||
});
|
||||
|
||||
it('tells why it could not connect, on each side once its time is up', async () => {
|
||||
FakePeer.reachable = false;
|
||||
const [sender, receiver] = [side(), side()];
|
||||
@@ -1366,6 +1438,78 @@ describe('tracker signaling', () => {
|
||||
expect(sender.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('shares on after a receiver on another protocol, with the next receiver', async () => {
|
||||
new FakeTracker(URLS[0]!);
|
||||
settings.trackers = [URLS[0]!];
|
||||
const [sender, other, receiver] = [side(), side(), side()];
|
||||
const { code } = await sendViaTracker(file(10), sender.events, sender.signal);
|
||||
const labels = otherProtocol();
|
||||
await receiveViaTracker(code, other.events, other.signal);
|
||||
await until(() => sender.logged(`receiver via ${URLS[0]} runs another protocol`));
|
||||
await until(() => sender.logged('waiting for the next receiver'));
|
||||
expect(sender.logged('connected via')).toBe(false);
|
||||
other.stop();
|
||||
labels.mockRestore();
|
||||
|
||||
await receiveViaTracker(code, receiver.events, receiver.signal);
|
||||
await until(() => receiver.files[0]);
|
||||
expect(sender.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('walks on past a tracker the browser refuses to open, on both sides', async () => {
|
||||
new FakeTracker(URLS[0]!);
|
||||
settings.trackers = ['ws://refused.test', URLS[0]!];
|
||||
vi.stubGlobal(
|
||||
'WebSocket',
|
||||
class extends FakeSocket {
|
||||
constructor(url: string) {
|
||||
if (url.startsWith('ws:')) throw new DOMException('insecure', 'SecurityError');
|
||||
super(url);
|
||||
}
|
||||
},
|
||||
);
|
||||
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]);
|
||||
for (const peer of [sender, receiver]) expect(peer.logged('ws://refused.test refused: insecure')).toBe(true);
|
||||
expect([...sender.errors, ...receiver.errors]).toEqual([]);
|
||||
});
|
||||
|
||||
it('answers no offer that waited for its turn on a tracker lost meanwhile', async () => {
|
||||
for (const url of URLS.slice(0, 2)) new FakeTracker(url);
|
||||
settings.trackers = URLS.slice(0, 2);
|
||||
const [sender, silent, waiting] = [side(), side(), side()];
|
||||
const { code } = await sendViaTracker(file(10), sender.events, sender.signal);
|
||||
await receiveViaTracker(code, silent.events, silent.signal);
|
||||
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'));
|
||||
await receiveViaTracker(code, waiting.events, waiting.signal);
|
||||
await until(() => waiting.logged(`looking on ${URLS[0]}`));
|
||||
await settle();
|
||||
// The sender's socket, the first one made.
|
||||
FakeSocket.all[0]!.drop();
|
||||
await until(() => sender.logged(`waiting on ${URLS[1]}`));
|
||||
// Answered, so it doesn't time out below.
|
||||
await settle();
|
||||
vi.advanceTimersByTime(PROOF_TIMEOUT);
|
||||
await until(() => sender.logged('waiting for the next receiver'));
|
||||
await settle();
|
||||
expect(sender.count('offer via')).toBe(1);
|
||||
expect(sender.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('opens no tracker for a share that ended while its key was derived', async () => {
|
||||
new FakeTracker(URLS[0]!);
|
||||
settings.trackers = [URLS[0]!];
|
||||
const sender = side();
|
||||
const shared = sendViaTracker(file(10), sender.events, sender.signal);
|
||||
sender.stop();
|
||||
await shared;
|
||||
expect(FakeSocket.all).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]!);
|
||||
@@ -1428,7 +1572,9 @@ describe('tracker signaling', () => {
|
||||
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(receiver.status()).toBe(
|
||||
'retry: No sender with this code on any tracker. Check the code and that both pages show protocol hellcon/1, 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 });
|
||||
@@ -1468,7 +1614,7 @@ describe('tracker signaling', () => {
|
||||
await receiveViaTracker(code, other.events, other.signal, 'Grüße!');
|
||||
await until(() => other.status()?.startsWith('retry: No sender'));
|
||||
expect(other.status()).toBe(
|
||||
'retry: No sender with this code on any tracker. Check the code and the salt, still looking',
|
||||
'retry: No sender with this code on any tracker. Check the code and the salt and that both pages show protocol hellcon/1, still looking',
|
||||
);
|
||||
await receiveViaTracker(code, receiver.events, receiver.signal, 'Grüße');
|
||||
await until(() => receiver.files[0]);
|
||||
@@ -1550,7 +1696,9 @@ describe('tracker signaling', () => {
|
||||
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$/);
|
||||
expect(receiver.errors[0]).toMatch(
|
||||
/^no sender answered until .+, check that both pages show protocol hellcon\/1 or ask the sender for a new code$/,
|
||||
);
|
||||
await settle();
|
||||
expect(openSockets()).toEqual([]);
|
||||
expect(openPeers()).toEqual([]);
|
||||
|
||||
+50
-17
@@ -13,8 +13,8 @@ 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:
|
||||
// App.vue uses the settings and their defaults, PROTOCOL, 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.
|
||||
@@ -28,7 +28,8 @@ export const settings = {
|
||||
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.
|
||||
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM. The
|
||||
// receiver holds the sender to it and CHUNK_SIZE, raising either takes a new PROTOCOL.
|
||||
export const WINDOW = 8 * 1024 * 1024;
|
||||
const ICE_GRACE = 300;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
@@ -55,8 +56,16 @@ export const CONNECT_TIMEOUT = 30_000;
|
||||
// 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 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 takes a new PROTOCOL.
|
||||
export const PBKDF2_ITERATIONS = 600_000;
|
||||
// Goes into the key derivation, see secrets: sides on different versions end up in different swarms
|
||||
// and never meet, the receiver only finds no sender. The manual exchange has no derivation, the data
|
||||
// channel's label carries it there and the side it reaches checks it. The page shows it, so the two
|
||||
// can compare. Every change that breaks sharing between versions takes a new one: the code and its
|
||||
// salt, the derivation, the signaling, the data channel's messages and its flow control. A fork that
|
||||
// changes any of them takes a name of its own, two forks would otherwise share a version that means
|
||||
// different things.
|
||||
export const PROTOCOL = 'hellcon/1';
|
||||
// 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.
|
||||
export const PROOF_TIMEOUT = 10_000;
|
||||
@@ -304,7 +313,7 @@ export const formatTime = (time: number) =>
|
||||
// so the same one comes back every ~6 hours. The receiver takes the window with that character nearest
|
||||
// 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.
|
||||
// Its own constant, not TRACKER_WAIT: changing it takes a new PROTOCOL.
|
||||
export const SALT_WINDOW = 6 * 60_000;
|
||||
export const CODE_LENGTH = 11;
|
||||
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
|
||||
@@ -343,7 +352,9 @@ export function codeSalt(code: string, own?: string) {
|
||||
// clock's salt limits a table to the shares of one window, for 62¹⁰ codes it takes over a million GPU
|
||||
// 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.
|
||||
// nothing about the keys: one seals the signaling, see seal, one proves the connection. The PROTOCOL
|
||||
// goes in front of the salt, each version gets swarms and keys of its own. The proof's HMAC key takes
|
||||
// the hash's block size without a length given, 64 bytes.
|
||||
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']);
|
||||
@@ -351,7 +362,7 @@ export async function secrets(code: string, salt: string) {
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
hash: 'SHA-256',
|
||||
salt: text.encode(`hellcon ${salt.normalize('NFC')}`),
|
||||
salt: text.encode(`${PROTOCOL} ${salt.normalize('NFC')}`),
|
||||
iterations: PBKDF2_ITERATIONS,
|
||||
},
|
||||
password,
|
||||
@@ -624,7 +635,7 @@ export async function sendFile(
|
||||
events.progress(file.size, file.size);
|
||||
stop();
|
||||
} else if (typeof message?.error === 'string') {
|
||||
stop(`receiver stopped: ${message.error.slice(0, 200)}`);
|
||||
stop(`receiver stopped: ${message.error.replace(HIDDEN, '').slice(0, 200)}`);
|
||||
}
|
||||
wake();
|
||||
};
|
||||
@@ -672,7 +683,9 @@ export async function sendFile(
|
||||
.slice(offset, offset + CHUNK_SIZE)
|
||||
.arrayBuffer()
|
||||
.catch(() => undefined);
|
||||
if (!chunk) return stop(`could not read ${file.name} anymore`);
|
||||
// A browser may read a file that shrank meanwhile short instead of failing.
|
||||
if (chunk?.byteLength !== Math.min(CHUNK_SIZE, file.size - offset))
|
||||
return stop(`could not read ${file.name} anymore`);
|
||||
if (!open()) return;
|
||||
channel.send(chunk);
|
||||
}
|
||||
@@ -842,7 +855,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the offer');
|
||||
const pc = await createPeerConnection(signal);
|
||||
const channel = pc.createDataChannel('file');
|
||||
const channel = pc.createDataChannel(PROTOCOL);
|
||||
channel.onopen = () =>
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', 'receiver', events), signal);
|
||||
const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver');
|
||||
@@ -878,6 +891,11 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
// The sender's file channel, anything more is none of ours.
|
||||
if (opened) return;
|
||||
opened = true;
|
||||
if (channel.label !== PROTOCOL) {
|
||||
events.log(`the sender's protocol: ${JSON.stringify(channel.label.replace(HIDDEN, '').slice(0, 100))}`);
|
||||
pc.close();
|
||||
return events.error(`the sender runs another protocol, both pages have to show protocol ${PROTOCOL}`);
|
||||
}
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', 'sender', events), signal);
|
||||
};
|
||||
const wait = failUnconnected(pc, () => opened, events, signal, 'sender');
|
||||
@@ -908,7 +926,15 @@ export function trackerSocket(
|
||||
lost: () => void,
|
||||
again: () => void,
|
||||
) {
|
||||
const ws = new WebSocket(url);
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(url);
|
||||
} catch (error) {
|
||||
// Chromium refuses e.g. ws: on an https page right away, Firefox only closes the socket. Lost all
|
||||
// the same, once the caller has it.
|
||||
ws = Object.assign(new EventTarget(), { close: () => {} }) as unknown as WebSocket;
|
||||
queueMicrotask(() => end(`${url} refused: ${error instanceof Error ? error.message : error}`));
|
||||
}
|
||||
let opened = false;
|
||||
let accepted = false;
|
||||
let closed = false;
|
||||
@@ -968,7 +994,7 @@ export function trackerSocket(
|
||||
}
|
||||
return void message(msg);
|
||||
}
|
||||
reject(`${url}: ${failure.slice(0, 200)}`);
|
||||
reject(`${url}: ${failure.replace(HIDDEN, '').slice(0, 200)}`);
|
||||
});
|
||||
// A problem with the tracker's message: the end before acceptance, after it only that message's.
|
||||
const reject = (reason: string) => {
|
||||
@@ -1090,6 +1116,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
if (settled) return;
|
||||
// Only a fork that kept the name derives these keys.
|
||||
if (channel.label !== PROTOCOL) return giveUp(`receiver via ${url} runs another protocol`);
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
const handshake = connected(pc, channel, url, 'receiver', events, next, key);
|
||||
@@ -1141,7 +1169,11 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
if (signal.aborted || !tracker.alive()) return;
|
||||
if (sdp === undefined) return tracker.note(`offer without the code via ${url}`);
|
||||
const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||
// A lost tracker would take no answer, a receiver that came by it looks on the next one.
|
||||
if (busy)
|
||||
waiting = async () => {
|
||||
if (tracker.alive()) await answer(tracker.ws, url, offer);
|
||||
};
|
||||
else void answer(tracker.ws, url, offer);
|
||||
},
|
||||
() => {
|
||||
@@ -1159,7 +1191,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo
|
||||
trackers.push(tracker);
|
||||
}
|
||||
|
||||
join(0);
|
||||
// Ended while the key was derived.
|
||||
if (!signal.aborted) join(0);
|
||||
return { code, until };
|
||||
}
|
||||
|
||||
@@ -1208,7 +1241,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
const nobody = () =>
|
||||
hint
|
||||
? `no sender connected until ${formatTime(until)}: ${hint}`
|
||||
: `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`;
|
||||
: `no sender answered until ${formatTime(until)}, check that both pages show protocol ${PROTOCOL}${ownSalt === undefined ? '' : ' and you use the same salt'} or ask the sender for a new code`;
|
||||
// Without a sender connected the search is over, every offer goes.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1253,7 +1286,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
entry.pc = pc;
|
||||
// Meanwhile the download may have started or the search ended.
|
||||
if (signal.aborted || started || expired) return pc.close();
|
||||
const channel = pc.createDataChannel('file');
|
||||
const channel = pc.createDataChannel(PROTOCOL);
|
||||
const offerId = randomBinary(20);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
// Unless another offer is connected, next replaces this one then.
|
||||
@@ -1322,7 +1355,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
if (none)
|
||||
events.status(
|
||||
'retry',
|
||||
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'}, still looking`,
|
||||
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'} and that both pages show protocol ${PROTOCOL}, still looking`,
|
||||
);
|
||||
else if (failure) events.status('retry', `${failure}. Looking again`);
|
||||
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
||||
|
||||
+11
-1
@@ -5,11 +5,17 @@
|
||||
|
||||
// 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.
|
||||
// Without either for longer, public/sw.js takes the page for gone and fails the download, see SILENCE.
|
||||
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;
|
||||
// Of the messages between this page and public/sw.js, which has it too. A page can talk to a worker
|
||||
// of another version: a new page while another tab's download holds the old worker, or an old page
|
||||
// once an update took over. The worker refuses a version it doesn't speak with outdated, each change
|
||||
// to the messages takes a new one, in both files.
|
||||
const VERSION = 1;
|
||||
|
||||
const downloads = registerDownloads();
|
||||
// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window.
|
||||
@@ -110,11 +116,15 @@ export function startDownload(file: { name: string; size: number }, events: Down
|
||||
if (data === 'finished') events.finished();
|
||||
if (data === 'cancelled') events.cancelled();
|
||||
if (data === 'failed') events.failed('the service worker refused it');
|
||||
if (data === 'silent') events.failed('the service worker heard nothing from this page for too long');
|
||||
if (data === 'outdated') {
|
||||
events.failed('this page and its service worker are different versions, reload once no tab receives');
|
||||
}
|
||||
}
|
||||
ended = true;
|
||||
release(data === 'finished');
|
||||
};
|
||||
worker.postMessage({ id, ...file }, [port2]);
|
||||
worker.postMessage({ id, version: VERSION, ...file }, [port2]);
|
||||
return worker;
|
||||
},
|
||||
(error) => {
|
||||
|
||||
+7
-1
@@ -616,14 +616,20 @@ output {
|
||||
/* Source link, quiet below everything */
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
padding-bottom: var(--space-6);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
footer a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition);
|
||||
|
||||
@@ -23,6 +23,8 @@ export default defineConfig({
|
||||
// The dev server would inline small images like gitea.svg as data: URLs, which index.html's
|
||||
// Content-Security-Policy blocks. The production build links them as files either way.
|
||||
build: { assetsInlineLimit: 0 },
|
||||
// Relative links, so the build works under any path, not only at the root of a host.
|
||||
base: './',
|
||||
// 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