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:
SchluffeandClaude Opus 5.5 committed 2026-10-30 15:10:09 +01:00
1 parent 44a8a72261
commit ac4d496a48
11 files changed
+399 -56

No files matched your search

+82 -9
View File
@@ -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));
}