Files
HellCon/e2e.spec.ts
T
SchluffeandClaude Opus 5.5 ac4d496a48 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>
2026-10-30 15:10:09 +01:00

1410 lines
66 KiB
TypeScript

import { createCipheriv, createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
import { createSocket, type Socket } from 'node:dgram';
import { once } from 'node:events';
import { createReadStream } from 'node:fs';
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
import type { AddressInfo } from 'node:net';
import { networkInterfaces } from 'node:os';
import {
type Browser,
type BrowserContext,
type BrowserType,
chromium,
expect,
firefox,
type Page,
type WebSocket as PageSocket,
test,
type WebSocketRoute,
} from '@playwright/test';
import { build, createServer, preview, type ViteDevServer } from 'vite';
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
// Chromium needs a permission for the copy buttons, Firefox lets the click do it and rejects the name.
const PERMISSIONS: Record<string, string[]> = { chromium: ['clipboard-write'], firefox: [] };
const SIZE = 5_000_000;
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
// staging could store in incognito-like contexts.
const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test cancels or disconnects.
const RUNNING_SIZE = 100_000_000;
// WINDOW, PROBE_TIMEOUT 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);
// When a share or search ends, in its error. The browser writes the time its own way.
const UNTIL = String.raw`until \d\d?:\d\d(?:[\u00a0\u202f][AP]M)?`;
// Enough for a transfer whose receiver holds back its reads to pause at the window.
const HELD_SIZE = 3 * WINDOW;
// What the fake STUN server reports as public address, reserved for documentation.
const PUBLIC_ADDRESS = '203.0.113.5';
// Where the browsers reach the fake STUN server. Firefox sends nothing to a loopback one, and the
// browsers gather from the network interfaces anyway, without one no test connects.
const LOCAL_ADDRESS =
Object.values(networkInterfaces())
.flat()
.find((address) => address?.family === 'IPv4' && !address.internal)?.address ?? '127.0.0.1';
// Each mode connects a sender page that already picked a file to a receiver page.
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
async manual(sender, receiver) {
await sender.click('#send-manual summary');
await sender.click('#create-offer');
await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
await sender.click('#copy-offer');
await expect(sender.locator('#copy-offer')).toHaveText('Copied');
await receiver.click('#receive-manual summary');
await receiver.fill('#offer-input', await sender.inputValue('#offer'));
await receiver.click('#create-answer');
await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 });
await sender.fill('#answer-input', await receiver.inputValue('#answer'));
await sender.click('#accept-answer');
},
async offline(sender, receiver) {
await sender.uncheck('#stun');
await receiver.uncheck('#stun');
await MODES.manual!(sender, receiver);
for (const code of [await sender.inputValue('#offer'), await receiver.inputValue('#answer')]) {
expect(Buffer.from(code, 'base64').toString()).not.toContain('typ srflx');
}
},
async tracker(sender, receiver) {
await sender.click('#share');
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{11}$/);
await sender.click('#copy-send-code');
await expect(sender.locator('#copy-send-code')).toHaveText('Copied');
await expect(sender.locator('#log')).toContainText('waiting on');
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
await receiver.click('#receive');
},
};
let server: ViteDevServer;
let url: string;
let stun: Socket;
// Appended to sw.js, so raising it makes the browser see an update, like a deploy.
let swVersion = 0;
// Launched once per worker on first use. Every test gets fresh contexts, closed right after it.
const browsers: Record<string, Promise<Browser>> = {};
let contexts: BrowserContext[] = [];
// Uncaught errors in the test's pages, they fail it even if everything else passed.
let errors: string[] = [];
// Tracker sockets per page, the dev server's own one left out.
const sockets = new Map<Page, PageSocket[]>();
test.describe.configure({ mode: 'parallel' });
test.setTimeout(60_000);
test.beforeAll(async () => {
server = await createServer({
logLevel: 'silent',
server: { port: 0 },
plugins: [
{
name: 'sw-version',
configureServer({ middlewares }) {
middlewares.use('/sw.js', async (_, res) => {
res.setHeader('Content-Type', 'text/javascript');
res.end(`${await readFile('public/sw.js', 'utf8')}\n// ${swVersion}\n`);
});
},
},
],
});
await server.listen();
url = server.resolvedUrls!.local[0]!;
stun = await fakeStun();
});
test.afterEach(async () => {
await Promise.all(contexts.map((context) => context.close()));
contexts = [];
sockets.clear();
const uncaught = errors;
errors = [];
expect(uncaught).toEqual([]);
});
test.afterAll(async () => {
await Promise.all(Object.values(browsers).map(async (browser) => (await browser).close()));
await server.close();
stun.close();
});
// 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) | (() => void)[]; base?: string; time?: number } = {},
) {
browsers[name] ??= BROWSERS[name]!.launch();
const browser = await browsers[name];
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
contexts.push(context);
const page = await context.newPage();
await page.clock.install({ time });
const trackers: PageSocket[] = [];
sockets.set(page, trackers);
page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws));
page.on('pageerror', (error) => errors.push(`${name}: ${error.message}`));
await page.addInitScript(trackPeers);
await page.addInitScript(failOnCsp);
for (const script of [init].flat()) await page.addInitScript(script);
await page.goto(base);
return page;
}
// Answers every STUN binding request with PUBLIC_ADDRESS, instantly and without network access.
async function fakeStun() {
const socket = createSocket('udp4');
socket.on('message', (request, from) => {
if (request.length < 20 || request.readUInt16BE(0) !== 0x0001) return;
const response = Buffer.alloc(32);
// Binding success with the request's cookie and transaction id, then XOR-MAPPED-ADDRESS.
response.writeUInt16BE(0x0101, 0);
response.writeUInt16BE(12, 2);
request.copy(response, 4, 4, 20);
response.writeUInt16BE(0x0020, 20);
response.writeUInt16BE(8, 22);
response.writeUInt16BE(0x0001, 24);
response.writeUInt16BE(from.port ^ 0x2112, 26);
const address = PUBLIC_ADDRESS.split('.').reduce((value, byte) => value * 256 + Number(byte), 0);
response.writeUInt32BE((address ^ 0x2112a442) >>> 0, 28);
socket.send(response, from.port, from.address);
});
await new Promise<void>((resolve) => socket.bind(0, LOCAL_ADDRESS, resolve));
return socket;
}
async function hash(path: string) {
const sha = createHash('sha256');
for await (const chunk of createReadStream(path)) sha.update(chunk);
return sha.digest('hex');
}
const log = (page: Page) => page.locator('#log').textContent();
// Init script for every page: whatever index.html's Content-Security-Policy blocks fails the test, the
// browsers only log it.
function failOnCsp() {
document.addEventListener('securitypolicyviolation', ({ violatedDirective, blockedURI }) => {
throw new Error(`Content-Security-Policy blocked ${blockedURI || 'inline'} by ${violatedDirective}`);
});
}
// Init script for every page: keeps its peer connections in window.peers, so a test can check that
// they were closed. It runs in the hidden frames too, only the app's own window counts.
function trackPeers() {
if (window !== window.top) return;
const page = window as unknown as { peers: RTCPeerConnection[] };
page.peers = [];
const PeerConnection = RTCPeerConnection;
window.RTCPeerConnection = class extends PeerConnection {
constructor(config?: RTCConfiguration) {
super(config);
page.peers.push(this);
}
};
}
// The page's peer connections that aren't closed. The app's own check of the STUN servers closes its own.
const openPeers = (page: Page) =>
page.evaluate(
() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
);
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
async function expectClosed(page: Page) {
await expect.poll(() => openPeers(page)).toBe(0);
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.
function holdReads() {
if (window !== window.top) return;
const page = window as unknown as { received: number; release: () => void };
const held: [RTCDataChannel, string][] = [];
let holding = true;
page.received = 0;
const send = RTCDataChannel.prototype.send as (this: RTCDataChannel, data: unknown) => void;
RTCDataChannel.prototype.send = function (this: RTCDataChannel, data: unknown) {
if (holding && typeof data === 'string' && data.includes('"read"')) return void held.push([this, data]);
send.call(this, data);
};
// Registered before the app's handlers, so the chunks are counted before it transfers them away.
const PeerConnection = RTCPeerConnection;
window.RTCPeerConnection = class extends PeerConnection {
constructor(config?: RTCConfiguration) {
super(config);
this.addEventListener('datachannel', ({ channel }) =>
channel.addEventListener('message', ({ data }) => (page.received += data.byteLength ?? 0)),
);
}
};
page.release = () => {
holding = false;
for (const [channel, data] of held) send.call(channel, data);
};
}
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
type FakeWakeLock = EventTarget & { released: boolean; release: () => Promise<void> };
// Init script for a page whose wake lock the test follows, a headless browser may not grant a real
// one. Like a browser, it refuses one to a hidden page and releases each once the page is hidden,
// which setHidden makes it. It runs in the hidden frames too, only the app's own window counts.
function fakeWakeLock() {
if (window !== window.top) return;
const page = window as unknown as { wakeLocks: FakeWakeLock[]; setHidden: (hidden: boolean) => void };
page.wakeLocks = [];
let hidden = false;
Object.defineProperty(document, 'hidden', { get: () => hidden });
const request = async () => {
if (hidden) throw new DOMException('page is hidden', 'NotAllowedError');
const sentinel: FakeWakeLock = Object.assign(new EventTarget(), {
released: false,
release: async () => {
if (sentinel.released) return;
sentinel.released = true;
sentinel.dispatchEvent(new Event('release'));
},
});
page.wakeLocks.push(sentinel);
return sentinel;
};
Object.defineProperty(navigator, 'wakeLock', { value: { request } });
page.setHidden = (value) => {
hidden = value;
if (hidden) for (const sentinel of page.wakeLocks) void sentinel.release();
document.dispatchEvent(new Event('visibilitychange'));
};
}
const setHidden = (page: Page, hidden: boolean) =>
page.evaluate((hidden) => (window as unknown as { setHidden: (hidden: boolean) => void }).setHidden(hidden), hidden);
// The wake locks the page holds, and whether it would ask before a reload or a closed tab.
const awake = (page: Page) =>
page.evaluate(() => {
const leave = new Event('beforeunload', { cancelable: true });
dispatchEvent(leave);
const { wakeLocks } = window as unknown as { wakeLocks: FakeWakeLock[] };
return { locks: wakeLocks.filter((sentinel) => !sentinel.released).length, asks: leave.defaultPrevented };
});
// Changes sw.js and has the page's browser install it, as after a deploy while the tab is open.
async function updateWorker(page: Page) {
await expect
.poll(() => page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.active))
.toBe(true);
swVersion++;
await page.evaluate(async () => {
const registration = (await navigator.serviceWorker.getRegistration('download/'))!;
Object.assign(window, { previous: registration.active });
await registration.update();
});
}
// Whether the updated sw.js took over from the one that was active when updateWorker ran.
const updated = (page: Page) =>
page.evaluate(
async () =>
(await navigator.serviceWorker.getRegistration('download/'))!.active !==
(window as { previous?: ServiceWorker }).previous,
);
// Runs fn and attaches both logs to the report, also when it fails. A closed page has none left.
async function withLogs(sender: Page, receiver: Page, fn: () => Promise<void>) {
try {
await fn();
} finally {
for (const [name, page] of [
['sender', sender],
['receiver', receiver],
] as const) {
await test.info().attach(`${name} log`, { body: (await log(page).catch(() => null)) ?? '' });
}
}
}
// Connects and verifies that both sides show the same security check, swapped. Over a tracker the
// code proves the connection, nobody sees one.
async function connect(mode: string, sender: Page, receiver: Page, source: string) {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
if (mode === 'tracker') return proven(sender, receiver);
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
// The check shows up once both are connected, which can take a while.
for (const side of ['local', 'remote']) {
await expect(sender.locator(`#check-${side}`)).toHaveText(/^([0-9A-F]{2} ){15}[0-9A-F]{2}$/, {
timeout: 45_000,
});
}
await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!);
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
for (const page of [sender, receiver]) {
await expect(page.locator('#log')).toContainText('waiting for the security check');
}
await expect(sender.locator('#send-status')).toHaveText('Compare the security codes above with the receiver');
await expect(receiver.locator('#receive-status')).toHaveText('Compare the security codes above with the sender');
}
// Resolves with the download, which starts once the receiver clicked Download, and the receiver log
// at that moment.
const downloadStarts = (receiver: Page) =>
receiver
.waitForEvent('download', { timeout: test.info().timeout })
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
// Both sides passed the security check of tracker signaling, without showing one.
async function proven(sender: Page, receiver: Page) {
for (const page of [sender, receiver]) {
await expect(page.locator('#log')).toContainText('security check passed', { timeout: 45_000 });
await expect(page.locator('#check-local')).toHaveCount(0);
}
}
// Connects, confirms the security check on both sides unless the code proved it, and starts the download.
async function start(mode: string, sender: Page, receiver: Page, source: string) {
await connect(mode, sender, receiver, source);
const started = downloadStarts(receiver);
if (mode !== 'tracker') {
await sender.click('#confirm');
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#confirm');
}
// Offered, but nothing is sent before the user asks for it.
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
await expect(receiver.locator('#log')).not.toContainText('receiving');
await expect(sender.locator('[data-phase=wait] #send-status')).toHaveText('Waiting for the receiver to download');
await expect(receiver.locator('[data-phase=wait] #receive-status')).toHaveText('Click Download to save the file');
await receiver.click('#download');
return started;
}
// Sends the file at source and verifies the downloaded bytes. during runs once the download started.
async function transfer(
mode: string,
sender: Page,
receiver: Page,
source: string,
size: number,
during?: () => Promise<void>,
) {
await withLogs(sender, receiver, async () => {
const { download, logAtStart } = await start(mode, sender, receiver, source);
// Streamed, not staged: 2.5 GiB can't arrive before the download manager takes over.
if (size === LARGE_SIZE) expect(logAtStart).not.toContain('received');
await during?.();
expect(download.suggestedFilename()).toBe(source.split('/').pop());
expect(await hash(await download.path())).toBe(await hash(source));
await expect(receiver.locator('#log')).toContainText('download complete');
await expect(sender.locator('#log')).toContainText('delivered');
if (mode === 'tracker') {
// The transfer used the share up, another receiver would wait for nothing.
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
await expect(sender.locator('#copy-send-code')).toBeDisabled();
}
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100);
await expect(sender.locator('[data-phase=done] #send-status')).toHaveText('Delivered');
await expect(receiver.locator('[data-phase=done] #receive-status')).toHaveText('Download complete');
// Removed hidden pages release the service worker for updates.
await expect(receiver.locator('iframe')).toHaveCount(0);
await expectClosed(sender);
await expectClosed(receiver);
});
}
// A file in the test's output directory.
async function payload(content: Buffer, name = 'payload.bin') {
const source = test.info().outputPath(name);
await writeFile(source, content);
return source;
}
// Where a man in the middle of the manual exchange may put the a=fingerprint line it claims beside
// its own: a parser may read the claimed one where the browser reads the own one. With the own one
// on a line of its own the browser connects to the middle. Or the own one where a parser may miss
// it: Chromium and Firefox don't read it there and don't connect, a browser that did must not get
// the sender's code either.
const HIDDEN: Record<string, { connects: boolean; place: (own: string, claimed: string) => string }> = {
'a line before': { connects: true, place: (own, claimed) => `${claimed}\r\n${own}` },
'a candidate line': {
connects: true,
place: (own, claimed) => `a=candidate:1 1 udp 1 127.0.0.1 9 typ host ${claimed}\r\n${own}`,
},
'another attribute': { connects: true, place: (own, claimed) => `a=x-decoy:${claimed}\r\n${own}` },
'a line after a bare CR': { connects: true, place: (own, claimed) => `a=x-decoy:\r${claimed}\r\n${own}` },
'an indented own line': { connects: false, place: (own, claimed) => `${claimed}\r\n ${own}` },
'an own line after a bare CR': { connects: false, place: (own, claimed) => `${claimed}\r\na=x-decoy:\r${own}` },
};
// The security code of the manual exchange for these fingerprints, like securityCheck in src/core.ts.
const manualCode = (fingerprints: string[]) =>
createHash('sha256')
.update(JSON.stringify(fingerprints))
.digest('hex')
.slice(0, 32)
.toUpperCase()
.match(/../g)!
.join(' ');
// Interoperability and data integrity between every pair, with no server involved.
for (const from of Object.keys(BROWSERS)) {
for (const to of Object.keys(BROWSERS)) {
test(`offline: ${from} sends to ${to}`, async () => {
const [sender, receiver] = await Promise.all([open(from), open(to)]);
await transfer('offline', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
for (const page of [sender, receiver]) expect(sockets.get(page)).toEqual([]);
});
}
}
// Through the default STUN servers and trackers in src/core.ts. The first tracker, HellCon's own,
// refuses the dev server's origin, so both sides go on to the next one. The signaling doesn't depend
// on the browser pair, one pairing each way is enough.
for (const mode of ['manual', 'tracker']) {
for (const [from, to] of [
['chromium', 'firefox'],
['firefox', 'chromium'],
] as const) {
test(`live ${mode}: ${from} sends to ${to}`, async () => {
const [sender, receiver] = await Promise.all([open(from), open(to)]);
await transfer(mode, sender, receiver, await payload(randomBytes(SIZE)), SIZE);
if (mode === 'manual') for (const page of [sender, receiver]) expect(sockets.get(page)).toEqual([]);
});
}
}
// The tracker from backend/, in this worker on a free port, allowing the dev server's origin.
// backend/tracker.spec.mjs tests its rules on their own.
async function ownTracker() {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${new URL(url).origin}`;
const { server } = await import('./backend/tracker.mjs');
if (!server.listening) await once(server, 'listening');
return `ws://127.0.0.1:${(server.address() as AddressInfo).port}`;
}
// Through the own tracker alone, without STUN. With the public ones as fallbacks, a tracker that
// doesn't understand the client would go unnoticed.
for (const [from, to] of [
['chromium', 'firefox'],
['firefox', 'chromium'],
] as const) {
test(`own tracker: ${from} sends to ${to}`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(from), open(to)]);
// With an own salt, the clock's is in the live tests.
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
await page.check('#own-salt');
await page.fill('#salt', 'own tracker');
}
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
});
// The code tells its window, the receiver's clock can be hours off. With the clock's salt.
test(`own tracker: ${from} sends to ${to} with the receiver's clock 2 hours behind`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(from), open(to, { time: TEST_TIME - 2 * 3_600_000 })]);
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
}
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
});
}
// 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', 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();
}
});
for (const name of Object.keys(BROWSERS)) {
test(`servers: ${name} skips invalid lines, a reload brings back the defaults`, async () => {
const page = await open(name);
const core = () =>
page.evaluate(
(path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]),
'/src/core.ts',
);
await page.click('#servers summary');
// Both would make the constructors throw.
await page.fill('#stun-servers', 'stun:stun.example:99999');
await page.fill('#trackers', 'tracker.example\nwss://tracker.example/#\nwss://tracker.example');
await expect(page.locator('#servers')).toContainText('accepts: stun:stun.example:99999');
await expect(page.locator('#servers')).toContainText('without #: tracker.example, wss://tracker.example/#');
expect(await core()).toEqual([[], ['wss://tracker.example']]);
await page.uncheck('#stun');
await page.check('#own-salt');
await page.fill('#salt', 'salt');
await page.reload();
await page.click('#servers summary');
await expect(page.locator('#trackers')).toHaveValue(/^wss:\/\/tracker\.pagequit\.net\n/);
await expect(page.locator('#stun')).toBeChecked();
await expect(page.locator('#own-salt')).not.toBeChecked();
await expect(page.locator('#salt')).toHaveCount(0);
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
await page.fill('#receive-code', 'code');
await page.fill('#trackers', '');
await expect(page.locator('#receive')).toBeDisabled();
await page.click('#reset-servers');
await expect(page.locator('#receive')).toBeEnabled();
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
});
test(`servers: ${name} notes while no STUN server would be used`, async () => {
const page = await open(name);
await expect(page.locator('#no-stun')).toHaveCount(0);
await page.uncheck('#stun');
await expect(page.locator('#no-stun')).toHaveText(
'STUN is off: only devices on the same network or VPN can connect.',
);
await page.check('#stun');
await page.click('#servers summary');
// A line this browser rejects is no server either.
await page.fill('#stun-servers', 'stun:stun.example:99999');
await expect(page.locator('#no-stun')).toHaveText(
'No STUN server under Servers: only devices on the same network or VPN can connect.',
);
await page.click('#reset-servers');
await expect(page.locator('#no-stun')).toHaveCount(0);
});
// Only the STUN server in use learns the address. 192.0.2.1 is reserved for documentation and never
// answers, a connection with it would wait ICE_TIMEOUT in src/core.ts. The probe passes it over
// once, later connections go straight to the one that answered, until it stops.
test(`stun: ${name} uses the first STUN server that answers, the next once it stops`, async () => {
const page = await open(name);
const first = await fakeStun();
const servers = [
'stun:192.0.2.1:3478',
...[first, stun].map((socket) => `stun:${LOCAL_ADDRESS}:${socket.address().port}`),
];
await page.click('#servers summary');
await page.fill('#stun-servers', servers.join('\n'));
await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1)));
await page.click('#send-manual summary');
// The offer's SDP, how long it took and the STUN servers of the page's open connection.
const offer = async () => {
const start = Date.now();
await page.click('#create-offer');
await expect(page.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
return {
sdp: Buffer.from(await page.inputValue('#offer'), 'base64').toString(),
ms: Date.now() - start,
servers: await page.evaluate(() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers
.filter((pc) => pc.signalingState !== 'closed')
.flatMap((pc) => pc.getConfiguration().iceServers!.flatMap(({ urls }) => urls)),
),
};
};
const probed = await offer();
expect(probed.ms).toBeGreaterThanOrEqual(PROBE_TIMEOUT);
expect(probed.sdp).toContain(`${PUBLIC_ADDRESS} `);
expect(probed.servers).toEqual([servers[1]]);
const known = await offer();
expect(known.ms).toBeLessThan(PROBE_TIMEOUT);
expect(known.servers).toEqual([servers[1]]);
first.close();
const stopped = await offer();
expect(stopped.sdp).not.toContain(`${PUBLIC_ADDRESS} `);
const next = await offer();
expect(next.sdp).toContain(`${PUBLIC_ADDRESS} `);
expect(next.servers).toEqual([servers[2]]);
});
test(`update: ${name} receives after sw.js changed`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
const source = await payload(randomBytes(SIZE));
await updateWorker(receiver);
await expect.poll(() => updated(receiver)).toBe(true);
await transfer('offline', sender, receiver, source, SIZE);
});
test(`update: ${name} keeps a running download when sw.js changes`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
const source = await payload(randomBytes(HELD_SIZE));
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
// Paused at the window, so the transfer is guaranteed to still run during the update.
await expect.poll(() => received(receiver)).toBe(WINDOW);
await updateWorker(receiver);
// The update has to wait instead of replacing the worker that feeds the download.
await expect
.poll(() =>
receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting),
)
.toBe(true);
expect(await updated(receiver)).toBe(false);
await release(receiver);
});
// Released once the download is complete, so the update takes over.
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));
await withLogs(sender, receiver, async () => {
const { download } = await start('offline', sender, receiver, source);
await download.cancel();
// A transfer that already finished would report no failure.
expect(await download.failure()).toBe('canceled');
await expect(receiver.locator('#log')).toContainText('download cancelled');
await expect(receiver.locator('[data-phase=stopped] #receive-status')).toHaveText('Download cancelled');
await expect(receiver.locator('iframe')).toHaveCount(0);
expect(await log(receiver)).not.toContain('download complete');
// The window keeps the sender from having sent everything before it hears about the cancel.
await expect(sender.locator('#send-error')).toHaveText('receiver stopped: download cancelled');
expect(await log(sender)).not.toMatch(/ sent$/m);
await expectClosed(sender);
await expectClosed(receiver);
});
});
test(`progress: ${name} follows the shared file, not a later pick`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
const source = await payload(randomBytes(100_000));
await withLogs(sender, receiver, async () => {
await start('offline', sender, receiver, source);
await expect(sender.locator('#log')).toContainText('delivered');
await expect(sender.locator('#send-file')).toHaveCount(0);
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(200_000) };
await sender.setInputFiles('input[type=file]', other);
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
// The status names the file it belongs to, not the one picked now.
await expect(sender.locator('#send-file')).toHaveText('payload.bin');
await expect(sender.locator('#send-status')).toHaveText('Delivered');
});
});
// The edges of the chunking and the window, and a name the Content-Disposition header has to encode.
for (const [what, file, size] of [
// Read whole before the browser takes the download, see DOWNLOAD_GRACE in src/download.ts.
['an empty file', 'empty.bin', 0],
['a one byte file', 'one.bin', 1],
// Firefox would save a % as _.
['a file one byte past the window', "l'été (1) 🚀.bin", WINDOW + 1],
] as const) {
test(`boundary: ${name} sends ${what}`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
await transfer('offline', sender, receiver, await payload(randomBytes(size), file), size);
});
}
// When the browser takes a download is beyond the test, how long the frame stays is not: on the
// paused clock the download's frame stays, so the download has to arrive, and goes after exactly
// DOWNLOAD_GRACE. The frame holding the worker goes right away, it would block an update.
test(`boundary: ${name} keeps a finished download's frame for DOWNLOAD_GRACE`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
await withLogs(sender, receiver, async () => {
await connect('offline', sender, receiver, await payload(Buffer.alloc(0), 'empty.bin'));
await sender.click('#confirm');
await receiver.click('#confirm');
await expect(receiver.locator('#incoming')).toContainText('empty.bin');
await receiver.clock.pauseAt(await receiver.evaluate(() => Date.now() + 1));
const started = downloadStarts(receiver);
await receiver.click('#download');
await expect(receiver.locator('#log')).toContainText('download complete');
const frames = receiver.locator('iframe');
await expect(frames).toHaveCount(1);
await expect(frames).toHaveAttribute('src', /^download\/./);
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(test.info().outputPath('empty.bin')));
await receiver.clock.runFor(DOWNLOAD_GRACE - 1);
await expect(frames).toHaveCount(1);
await receiver.clock.runFor(1);
await expect(frames).toHaveCount(0);
});
});
test(`copy: ${name} selects the text when the browser blocks the clipboard`, async () => {
const sender = await open(name, {
init: () => {
navigator.clipboard.writeText = () => Promise.reject(new DOMException('blocked', 'NotAllowedError'));
},
});
await withLogs(sender, sender, async () => {
await sender.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#send-manual summary');
await sender.click('#create-offer');
await expect(sender.locator('#offer')).toHaveValue(/.+/);
await sender.click('#copy-offer');
await expect(sender.locator('#copy-offer')).toHaveText('Copy failed');
await expect(sender.locator('#send-manual [role=alert]')).toHaveText(
'The browser blocked copying. The offer is selected, copy it yourself.',
);
const offer = sender.locator('#offer');
expect(await offer.evaluate((area: HTMLTextAreaElement) => area.selectionEnd - area.selectionStart)).toBe(
(await offer.inputValue()).length,
);
});
});
// Share, Receive and the manual exchange each start a session, a new one ends the one before.
test(`session: ${name} a new operation ends the previous one`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
const source = await payload(randomBytes(100_000));
await withLogs(sender, receiver, async () => {
for (const page of [sender, receiver]) await page.uncheck('#stun');
await sender.setInputFiles('input[type=file]', source);
await sender.click('#share');
await expect(sender.locator('#send-code')).toHaveText(/.+/);
const first = await sender.locator('#send-code').textContent();
await sender.click('#share');
await expect(sender.locator('#send-code')).not.toHaveText(first!);
await receiver.fill('#receive-code', 'nobodyhere0');
await receiver.click('#receive');
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
// The log tells the sessions apart.
await expect(sender.locator('#log')).toContainText(
/--- share payload\.bin via tracker ---[\s\S]*--- share payload/,
);
await expect(receiver.locator('#log')).toContainText('--- receive via tracker ---');
// Closes all of the above, transfer checks that.
await transfer('offline', sender, receiver, source, 100_000);
await expect(sender.locator('#send-code')).toHaveCount(0);
});
});
// While a session runs, the screen stays on and the browser asks before a reload or a closed tab
// ends it. Hidden, the page loses the wake lock and gets a new one once visible again.
test(`awake: ${name} keeps the screen on and asks before leaving while busy`, async () => {
const [sender, receiver] = await Promise.all([
open(name, { init: fakeWakeLock }),
open(name, { init: fakeWakeLock }),
]);
const source = await payload(randomBytes(100_000));
await withLogs(sender, receiver, async () => {
for (const page of [sender, receiver]) expect(await awake(page)).toEqual({ locks: 0, asks: false });
await connect('offline', sender, receiver, source);
for (const page of [sender, receiver]) await expect.poll(() => awake(page)).toEqual({ locks: 1, asks: true });
await setHidden(sender, true);
await expect.poll(() => awake(sender)).toEqual({ locks: 0, asks: true });
await setHidden(sender, false);
await expect.poll(() => awake(sender)).toEqual({ locks: 1, asks: true });
await expect(sender.locator('#log')).toContainText(/keeping the screen on[\s\S]*keeping the screen on/);
await sender.click('#confirm');
await receiver.click('#confirm');
await receiver.click('#download');
await expect(sender.locator('[data-phase=done] #send-status')).toHaveText('Delivered');
await expect(receiver.locator('[data-phase=done] #receive-status')).toHaveText('Download complete');
for (const page of [sender, receiver]) await expect.poll(() => awake(page)).toEqual({ locks: 0, asks: false });
});
});
// The proofs hold even against a man in the middle that opens and seals the signaling. They are
// genuine, made with the right key, only the real certificates' fingerprints they cover give the man
// in the middle away. Whoever verifies first ends its connection, the other side may never get the
// proof then, but neither passes. Without the code, sealing keeps it out, see src/core.test.ts.
test(`check: ${name} both sides reject a man in the middle that relays the proofs`, async () => {
const [sender, receiver, middle] = await Promise.all([open(name), open(name), open(name, { init: middleman })]);
const [toSender, toReceiver] = await Promise.all([announces(sender), announces(receiver)]);
await withLogs(sender, receiver, async () => {
for (const page of [sender, receiver]) await page.uncheck('#stun');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.click('#share');
const code = (await sender.locator('#send-code').textContent())!;
await receiver.fill('#receive-code', code);
await receiver.click('#receive');
await interpose(middle, code, toSender, toReceiver);
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 15_000 });
await expect(receiver.locator('#log')).toContainText('looking again', { timeout: 15_000 });
expect(await relayed(middle)).toBeGreaterThan(0);
expect(`${await log(sender)}${await log(receiver)}`).toContain(
'security check failed, the peer does not know the code',
);
for (const page of [sender, receiver]) {
expect(await log(page)).not.toContain('security check passed');
await expect(page.locator('#check-local')).toHaveCount(0);
}
expect(await log(sender)).not.toContain('offered');
});
});
// A man in the middle of the manual exchange hands the receiver an offer of its own, claiming the
// certificate the sender would name beside its own one, see HIDDEN. However the browser takes that,
// the receiver never shows the sender's code: it doesn't connect, or its code covers the middle's
// certificate. Where it connects, the browser accepted the middle's, so without the check the
// middle would get the file.
for (const [variant, { connects, place }] of Object.entries(HIDDEN)) {
test(`check: ${name} manual exchange shows other codes for a certificate claimed in ${variant}`, async () => {
const [middle, receiver] = await Promise.all([open(name), open(name)]);
const claimed = `sha-256 ${Array.from(randomBytes(32), (byte) => byte.toString(16).padStart(2, '0')).join(':')}`;
await withLogs(middle, receiver, async () => {
for (const page of [middle, receiver]) await page.uncheck('#stun');
await middle.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await middle.click('#send-manual summary');
await middle.click('#create-offer');
await expect(middle.locator('#offer')).toHaveValue(/.+/);
const sdp = Buffer.from(await middle.inputValue('#offer'), 'base64').toString();
const tampered = sdp.replace(/^a=fingerprint:[^\r\n]*/gm, (line) =>
place(line, `a=fingerprint:${claimed.toUpperCase()}`),
);
expect(tampered).not.toBe(sdp);
await receiver.click('#receive-manual summary');
await receiver.fill('#offer-input', Buffer.from(tampered).toString('base64'));
await receiver.click('#create-answer');
const remote = receiver.locator('#check-remote');
const failed = (page: Page) => page.locator('#send-error, #receive-error').filter({ hasText: /.+/ });
await expect(receiver.locator('#answer').or(failed(receiver))).toBeVisible({ timeout: 15_000 });
if (!(await failed(receiver).count())) {
await middle.fill('#answer-input', await receiver.inputValue('#answer'));
await middle.click('#accept-answer');
// The middle may take the answer or not, the receiver connects or not.
const settled = async () =>
(await remote.count()) + (await failed(receiver).count()) + (await failed(middle).count());
await expect.poll(settled, { timeout: 15_000 }).toBeGreaterThan(0);
}
if (connects) await expect(remote).toBeVisible();
if (await remote.count()) await expect(remote).not.toHaveText(manualCode([claimed]));
});
});
}
test(`protocol: ${name} manual exchange reports a broken offer and answer`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await sender.uncheck('#stun');
await sender.click('#send-manual summary');
await sender.click('#create-offer');
await expect(sender.locator('#offer')).toHaveValue(/.+/);
await sender.fill('#answer-input', 'not an answer');
await sender.click('#accept-answer');
await expect(sender.locator('#send-error')).toHaveText(/^not a valid answer/);
await receiver.click('#receive-manual summary');
await receiver.fill('#offer-input', btoa('v=0 but nothing else'));
await receiver.click('#create-answer');
await expect(receiver.locator('#receive-error')).toHaveText('not a valid offer, copy all of it');
await expectClosed(receiver);
});
// A share takes the salt of the window its code ends with, or that and the own salt, trimmed and
// NFC: a search with the same code and salt announces the same info_hash. A code made late in a
// window still lasts 6 minutes. The salt stays as it is while a share runs, a search lets it be
// fixed for the next Receive. src/core.test.ts checks the info_hash against the protocol.
test(`salt: ${name} a share takes the clock's salt or the own one, which stays while it runs`, async () => {
const sender = await open(name);
const hashes: string[] = [];
await mockTrackers(sender, (msg) => {
if (msg.event === 'started') hashes.push(msg.info_hash as string);
return { action: 'announce', interval: 120, info_hash: msg.info_hash };
});
const label = sender.locator('label[for=send-code]');
const valid = /^\s*Code, give this to the receiver, valid until .+:\s*$/;
// The time as the label writes it, in the page's locale and time zone.
const time = (at: number) =>
sender.evaluate(
(at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'),
at,
);
// The info_hash a click on Share or Receive announces. A search finds no seeder on the mocks, one
// tracker keeps it to one announcement.
const announced = async (button: string) => {
const count = hashes.length;
await sender.click(button);
await expect.poll(() => hashes.length).toBe(count + 1);
return hashes.at(-1);
};
const share = async () => ({
hash: await announced('#share'),
code: (await sender.locator('#send-code').textContent())!,
});
const search = async (code: string) => {
await sender.fill('#receive-code', code);
return announced('#receive');
};
await withLogs(sender, sender, async () => {
await sender.click('#servers summary');
await sender.fill('#trackers', 'wss://tracker.test');
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
const first = await share();
await expect(label).toHaveText(valid);
// toHaveText takes a no-break space for any space, the text itself has to have it.
expect(await label.textContent()).toMatch(new RegExp(`${UNTIL}:`));
expect(await search(first.code)).toBe(first.hash);
// 12:05:30, half a minute before the window ends. Still valid for 6 minutes, until 12:11.
await sender.clock.fastForward('05:29');
const late = await share();
expect(late.code.at(-1)).toBe(first.code.at(-1));
await expect(label).toHaveText(valid);
expect(await label.textContent()).toContain(`until ${await time(Date.UTC(2026, 0, 1, 12, 11, 30))}:`);
await sender.clock.fastForward('06:00');
await expect(label).toHaveText('Code, no longer valid:');
const next = await share();
expect(next.code.at(-1)).not.toBe(first.code.at(-1));
// The switch, and the salt with Generate while it's on.
const locked = async (disabled: boolean) => {
const ids = (await sender.isChecked('#own-salt')) ? ['#own-salt', '#salt', '#generate-salt'] : ['#own-salt'];
for (const id of ids) await expect(sender.locator(id)).toBeEnabled({ enabled: !disabled });
};
await locked(true);
await sender.clock.fastForward('06:00');
await expect(label).toHaveText('Code, no longer valid:');
await locked(false);
await sender.check('#own-salt');
await expect(sender.locator('#share')).toBeDisabled();
await sender.fill('#salt', ' ');
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'true');
await expect(sender.locator('#share')).toBeDisabled();
// ü decomposed, u and a combining diaeresis.
await sender.fill('#salt', ' Gru\u0308ße ');
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'false');
const own = await share();
await expect(label).toHaveText(/^\s*Code, give this and your salt to the receiver, valid until .+:\s*$/);
await locked(true);
// 16 of the code's characters.
await sender.clock.fastForward('06:00');
await locked(false);
await sender.click('#generate-salt');
const generated = await sender.inputValue('#salt');
expect(generated).toMatch(/^[0-9a-zA-Z]{16}$/);
const resalted = await share();
// What can't be a code is told right away, that search is over.
await sender.fill('#receive-code', 'abcdefghij');
await sender.click('#receive');
await expect(sender.locator('#receive-error')).toHaveText('a code has 11 letters and digits, check it');
await locked(false);
expect(await search(resalted.code)).toBe(resalted.hash);
await locked(false);
// ü composed, without the spaces.
await sender.fill('#salt', 'Grüße');
expect(await search(own.code)).toBe(own.hash);
await sender.uncheck('#own-salt');
expect(await search(own.code)).not.toBe(own.hash);
});
});
// On the sender until the transfer is over. The receiver's search is over once connected, so its
// salt can always change.
test(`salt: ${name} stays on the sender while the peers are connected`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(name), open(name)]);
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
await page.check('#own-salt');
await page.fill('#salt', 'salt');
}
const locked = (pages: Page[], disabled: boolean) =>
Promise.all(
pages.flatMap((page) =>
['#own-salt', '#salt', '#generate-salt'].map((id) =>
expect(page.locator(id)).toBeEnabled({ enabled: !disabled }),
),
),
);
await withLogs(sender, receiver, async () => {
await connect('tracker', sender, receiver, await payload(randomBytes(1000)));
await expect(sender.locator('#send-status')).toHaveText('Waiting for the receiver to download');
await expect(receiver.locator('#receive-status')).toHaveText('Click Download to save the file');
await locked([sender], true);
await locked([receiver], false);
const started = downloadStarts(receiver);
await receiver.click('#download');
await started;
await expect(sender.locator('#send-status')).toHaveText('Delivered');
await expect(receiver.locator('#receive-status')).toHaveText('Download complete');
await locked([sender, receiver], false);
});
});
// Between networks a side without a public address connects nobody. Chromium never fails such a
// connection, the timeouts end it. The sender has one from the fake STUN server, the receiver has
// STUN off.
test(`hint: ${name} manual exchange names the side without a public address`, async () => {
const [sender, receiver] = await apart(name);
await withLogs(sender, receiver, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await MODES.manual!(sender, receiver);
// The timeout starts once the answer is set.
await expect
.poll(() =>
sender.evaluate(() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.some((pc) => pc.signalingState === 'stable'),
),
)
.toBe(true);
await sender.clock.fastForward(CONNECT_TIMEOUT);
await expect(sender.locator('#send-error')).toHaveText(`could not connect: the receiver ${NO_PUBLIC}`);
await receiver.clock.fastForward('06:00');
await expect(receiver.locator('#receive-error')).toHaveText(`could not connect: this side ${NO_PUBLIC}`);
await expectClosed(sender);
await expectClosed(receiver);
});
});
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
const source = await payload(Buffer.alloc(RUNNING_SIZE));
await withLogs(sender, receiver, async () => {
const { download } = await start('offline', sender, receiver, source);
await sender.context().close();
// Chromium only notices once the connection counts as failed, after ~16 s.
await expect(receiver.locator('#receive-error')).toHaveText('download failed: connection lost', {
timeout: 30_000,
});
await expect(receiver.locator('iframe')).toHaveCount(0);
// Firefox leaves the download stalled instead of failing it, see TODO.md.
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
});
});
// 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
// sends, on the socket it came from. They don't show up in sockets.
async function mockTrackers(page: Page, reply: (msg: Record<string, unknown>, ws: WebSocketRoute) => object) {
await page.routeWebSocket(/^wss:/, (ws) => {
ws.onMessage((data) => ws.send(JSON.stringify(reply(JSON.parse(String(data)), ws))));
});
}
type Middle = {
// Proofs that passed through.
relayed: number;
answer: (sdp: string) => Promise<string>;
offer: () => Promise<string>;
accept: (sdp: string) => Promise<void>;
};
// Init script for a man in the middle, driven by interpose: it answers the receiver's offer and
// offers to the sender itself, with its own certificate towards each, and relays every message
// between the two. It runs in the hidden frames too, only the app's own window counts.
function middleman() {
if (window !== window.top) return;
type Side = 'sender' | 'receiver';
const channels: Partial<Record<Side, RTCDataChannel>> = {};
// What waits for that side's channel to open.
const queues: Record<Side, string[]> = { sender: [], receiver: [] };
const flush = (side: Side) => {
const channel = channels[side];
while (channel?.readyState === 'open' && queues[side].length) channel.send(queues[side].shift()!);
};
const attach = (side: Side, channel: RTCDataChannel, to: Side) => {
channels[side] = channel;
channel.addEventListener('message', ({ data }) => {
if (String(data).includes('"proof"')) middle.relayed++;
queues[to].push(data);
flush(to);
});
channel.addEventListener('open', () => flush(side));
flush(side);
};
const localSdp = async (pc: RTCPeerConnection) => {
await pc.setLocalDescription();
while (pc.iceGatheringState !== 'complete') {
await new Promise((resolve) => pc.addEventListener('icegatheringstatechange', resolve, { once: true }));
}
return pc.localDescription!.sdp;
};
let toSender: RTCPeerConnection;
const middle: Middle = {
relayed: 0,
async answer(sdp) {
const pc = new RTCPeerConnection();
pc.ondatachannel = ({ channel }) => attach('receiver', channel, 'sender');
await pc.setRemoteDescription({ type: 'offer', sdp });
return localSdp(pc);
},
offer() {
toSender = new RTCPeerConnection();
attach('sender', toSender.createDataChannel('hellcon/1'), 'receiver');
return localSdp(toSender);
},
accept: (sdp) => toSender.setRemoteDescription({ type: 'answer', sdp }),
};
(window as unknown as { middle: Middle }).middle = middle;
}
const relayed = (page: Page) => page.evaluate(() => (window as unknown as { middle: Middle }).middle.relayed);
// biome-ignore lint/suspicious/noExplicitAny: raw tracker messages, the test reads nested fields as it needs them
type Announce = { msg: Record<string, any>; ws: WebSocketRoute };
// Mocks the page's trackers and keeps what it announces, with the socket to answer on.
async function announces(page: Page) {
const announced: Announce[] = [];
await mockTrackers(page, (msg, ws) => {
announced.push({ msg, ws });
return { action: 'announce', interval: 120, info_hash: msg.info_hash };
});
return announced;
}
// The first announcement that matches, once there is one.
async function first(announced: Announce[], match: (msg: Announce['msg']) => unknown) {
await expect.poll(() => announced.some(({ msg }) => match(msg))).toBe(true);
return announced.find(({ msg }) => match(msg))!;
}
// Puts the middleman page between the sender and the receiver on their mocked trackers, as a tracker
// that knows the code could: it opens and seals the signaling, only the proofs can give it away.
async function interpose(middle: Page, code: string, toSender: Announce[], toReceiver: Announce[]) {
const key = signalingKey(code);
const binary = () => randomBytes(20).toString('latin1');
const peerId = binary();
type Hosting = { middle: Middle };
const toward = await first(toReceiver, (msg) => msg.offers);
const [{ offer, offer_id }] = toward.msg.offers;
const sdp = await middle.evaluate(
(sdp) => (window as unknown as Hosting).middle.answer(sdp),
unseal(key, 'offer', offer.sdp),
);
const answer = { type: 'answer', sdp: seal(key, 'answer', sdp) };
toward.ws.send(
JSON.stringify({ action: 'announce', info_hash: toward.msg.info_hash, peer_id: peerId, offer_id, answer }),
);
const { msg, ws } = await first(toSender, (msg) => msg.event === 'started');
const own = {
type: 'offer',
sdp: seal(key, 'offer', await middle.evaluate(() => (window as unknown as Hosting).middle.offer())),
};
ws.send(
JSON.stringify({ action: 'announce', info_hash: msg.info_hash, peer_id: peerId, offer_id: binary(), offer: own }),
);
const { msg: reply } = await first(toSender, (msg) => msg.answer);
await middle.evaluate(
(sdp) => (window as unknown as Hosting).middle.accept(sdp),
unseal(key, 'answer', reply.answer.sdp),
);
}
// 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/1 ${new Date(TEST_TIME).toISOString().slice(0, 16)}`, 600_000, 32, 'sha256');
return Buffer.from(hkdfSync('sha256', master, '', 'signaling', 32));
}
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with key.
function seal(key: Buffer, type: 'offer' | 'answer', sdp: string) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv).setAAD(Buffer.from(type));
return Buffer.concat([iv, cipher.update(sdp), cipher.final(), cipher.getAuthTag()]).toString('base64');
}
function unseal(key: Buffer, type: 'offer' | 'answer', sealed: string) {
const bytes = Buffer.from(sealed, 'base64');
const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12));
decipher.setAAD(Buffer.from(type)).setAuthTag(bytes.subarray(-16));
return Buffer.concat([decipher.update(bytes.subarray(12, -16)), decipher.final()]).toString();
}
const NO_PUBLIC = 'has no public address, between different networks both sides need STUN';
// A sender and a receiver as if on different networks, with the servers open.
// Only the sender has a public address, from the fake STUN server, it answers nobody though.
async function apart(name: string) {
const pages = await Promise.all([open(name, { init: dropHosts }), open(name, { init: dropHosts })]);
for (const page of pages) await page.click('#servers summary');
await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`);
await pages[1]!.uncheck('#stun');
return pages as [Page, Page];
}
// Init script: drops the local addresses from every description the peer sends, as if it were on
// another network. It runs in the hidden frames too, only the app's own window counts.
function dropHosts() {
if (window !== window.top) return;
const set = RTCPeerConnection.prototype.setRemoteDescription as (
this: RTCPeerConnection,
description: RTCSessionDescriptionInit,
) => Promise<void>;
RTCPeerConnection.prototype.setRemoteDescription = function (
this: RTCPeerConnection,
description: RTCSessionDescriptionInit,
) {
const lines = description.sdp?.split('\r\n').filter((line) => !/^a=candidate:.* typ host\b/.test(line));
return set.call(this, { ...description, sdp: lines?.join('\r\n') });
};
}
for (const name of Object.keys(BROWSERS)) {
test(`large: ${name} survives a 40 s stall`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(120_000);
const [sender, receiver] = await Promise.all([open(name), open(name, { init: holdReads })]);
const source = await payload(randomBytes(HELD_SIZE));
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
await expect.poll(() => received(receiver)).toBe(WINDOW);
// Past the 30 s after which Firefox stops a service worker without events.
await receiver.waitForTimeout(40_000);
await release(receiver);
});
});
test(`large: ${name} sends 2.5 GiB`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(300_000);
// Sparse file with a random block every 64 MiB, so the hash catches lost or reordered chunks.
const source = test.info().outputPath('large.bin');
const file = await openFile(source, 'w');
await file.truncate(LARGE_SIZE);
for (let at = 0; at < LARGE_SIZE; at += 64 * 2 ** 20) await file.write(randomBytes(16384), 0, 16384, at);
await file.close();
// Real profiles on disk like normal users have; downloads go there too instead of the temp dir.
const profiles = await Promise.all(
['sender', 'receiver'].map((profile) =>
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
downloadsPath: test.info().outputPath('downloads'),
permissions: PERMISSIONS[name],
}),
),
);
try {
const [sender, receiver] = await Promise.all(profiles.map((profile) => profile.newPage()));
for (const page of [sender!, receiver!]) {
sockets.set(page, []);
page.on('pageerror', (error) => errors.push(`${name}: ${error.message}`));
await page.addInitScript(trackPeers);
await page.addInitScript(failOnCsp);
}
await Promise.all([sender!.goto(url), receiver!.goto(url)]);
await transfer('offline', sender!, receiver!, source, LARGE_SIZE);
} finally {
await Promise.all(profiles.map((profile) => profile.close()));
}
});
}