Own each transfer in a session and harden the protocol
Every operation (share, receive, manual offer or answer) now runs as one session tied to an AbortSignal. Starting another ends it: its connections, tracker sockets and timers close, and it can no longer touch the shared security check, progress or incoming file. Finished, failed and cancelled transfers close their connections, and the sender's tracker sockets close once the download starts. - A malformed or never-connecting tracker offer no longer blocks a share - The receiver validates the file offer and rejects excess bytes and data beyond the flow control window; sw.js checks name and size too - Failures show up in the card instead of disappearing into rejected promises: bad manual codes, unreachable trackers, lost connections - Primary buttons and pink text meet 4.5:1 contrast, the STUN switch shows keyboard focus again, the tracker Copy button matches the others - Split the core into src/core.ts, src/main.ts only mounts the app, which removes the main.ts <-> App.vue import cycle - Bring back the Gitea source link, write the README - Tests reuse one browser per worker with fresh contexts, fail on page errors, check cleanup after transfers, use a local fake STUN server and cover empty files, window boundaries, odd names, malformed messages, session replacement and the production build Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bacc15baaf
commit
2abd0b504d
7 files changed
+1442
-752
No files matched your search
+464
-169
@@ -1,21 +1,45 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { createSocket, type Socket } from 'node:dgram';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
|
||||
import { chromium, expect, firefox, test, type Browser, type BrowserType, type Page } from '@playwright/test';
|
||||
import { createServer, type ViteDevServer } from 'vite';
|
||||
import { networkInterfaces } from 'node:os';
|
||||
import {
|
||||
chromium,
|
||||
expect,
|
||||
firefox,
|
||||
test,
|
||||
type Browser,
|
||||
type BrowserContext,
|
||||
type BrowserType,
|
||||
type Page,
|
||||
type WebSocket as PageSocket,
|
||||
} from '@playwright/test';
|
||||
import { build, createServer, preview, type ViteDevServer } from 'vite';
|
||||
|
||||
// Runs against the real public trackers and STUN servers, the defaults in src/main.ts.
|
||||
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: [] };
|
||||
// The live tests use the public trackers and STUN servers, the defaults in src/core.ts.
|
||||
const TRACKER = 'wss://tracker.webtorrent.dev';
|
||||
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 updates sw.js, cancels or disconnects.
|
||||
// Big enough that the transfer still runs while a test cancels or disconnects.
|
||||
const RUNNING_SIZE = 100_000_000;
|
||||
// WINDOW in src/main.ts.
|
||||
// WINDOW, CHUNK_SIZE and ICE_TIMEOUT in src/core.ts.
|
||||
const WINDOW = 8 * 2 ** 20;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
// 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>> = {
|
||||
@@ -40,18 +64,6 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
||||
expect(Buffer.from(code, 'base64').toString()).not.toContain('typ srflx');
|
||||
}
|
||||
},
|
||||
// 192.0.2.1 is reserved for documentation and never answers, without the early stop in
|
||||
// gatherIce Chromium would wait 40 s per side, with only the hard timeout still 10 s.
|
||||
async 'dead-stun'(sender, receiver) {
|
||||
for (const page of [sender, receiver]) {
|
||||
await page.click('#servers summary');
|
||||
const servers = await page.inputValue('#stun-servers');
|
||||
await page.fill('#stun-servers', `${servers}\nstun:192.0.2.1:3478`);
|
||||
}
|
||||
const start = Date.now();
|
||||
await MODES.manual!(sender, receiver);
|
||||
expect(Date.now() - start).toBeLessThan(4000);
|
||||
},
|
||||
async tracker(sender, receiver) {
|
||||
await sender.click('#share');
|
||||
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{8}$/);
|
||||
@@ -65,9 +77,16 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
|
||||
|
||||
let server: ViteDevServer;
|
||||
let url: string;
|
||||
const browsers: Browser[] = [];
|
||||
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);
|
||||
@@ -90,24 +109,62 @@ test.beforeAll(async () => {
|
||||
});
|
||||
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(browsers.map((browser) => browser.close()));
|
||||
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.
|
||||
async function open(name: string, sockets: string[], init?: () => void) {
|
||||
const browser = await BROWSERS[name]!.launch();
|
||||
browsers.push(browser);
|
||||
const page = await (await browser.newContext({ permissions: PERMISSIONS[name] })).newPage();
|
||||
page.on('websocket', (ws) => sockets.push(ws.url()));
|
||||
// init runs in the page before the app. base is the app's URL, the dev server's by default.
|
||||
async function open(name: string, { init, base = url }: { init?: () => void; base?: string } = {}) {
|
||||
const browser = await (browsers[name] ??= BROWSERS[name]!.launch());
|
||||
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
|
||||
contexts.push(context);
|
||||
const page = await context.newPage();
|
||||
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);
|
||||
if (init) await page.addInitScript(init);
|
||||
await page.goto(url);
|
||||
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);
|
||||
@@ -116,6 +173,31 @@ async function hash(path: string) {
|
||||
|
||||
const log = (page: Page) => page.locator('#log').textContent();
|
||||
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Everything the page opened for a transfer is closed again: its peer connections and tracker sockets.
|
||||
async function expectClosed(page: Page) {
|
||||
const peers = () =>
|
||||
page.evaluate(() =>
|
||||
(window as unknown as { peers: RTCPeerConnection[] }).peers.filter((pc) => pc.signalingState !== 'closed').length,
|
||||
);
|
||||
await expect.poll(peers).toBe(0);
|
||||
await expect.poll(() => sockets.get(page)!.filter((ws) => !ws.isClosed()).length).toBe(0);
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -146,9 +228,10 @@ function holdReads() {
|
||||
};
|
||||
}
|
||||
|
||||
// Init script for a sender: keeps its data channels in window.channels, so a test can send on them
|
||||
// like a peer that skips the security check.
|
||||
// Init script: keeps the page's data channels in window.channels, its own and the peer's, so a test
|
||||
// can send on them like a peer that skips the security check or breaks the protocol.
|
||||
function recordChannels() {
|
||||
if (window !== window.top) return;
|
||||
const page = window as unknown as { channels: RTCDataChannel[] };
|
||||
page.channels = [];
|
||||
const create = RTCPeerConnection.prototype.createDataChannel;
|
||||
@@ -157,8 +240,25 @@ function recordChannels() {
|
||||
page.channels.push(channel);
|
||||
return channel;
|
||||
};
|
||||
const PeerConnection = RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends PeerConnection {
|
||||
constructor(config?: RTCConfiguration) {
|
||||
super(config);
|
||||
this.addEventListener('datachannel', ({ channel }) => page.channels.push(channel));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Sends on the page's first data channel, past the app: strings as they are, a number as that many bytes.
|
||||
const inject = (page: Page, ...messages: (string | number)[]) =>
|
||||
page.evaluate((messages) => {
|
||||
const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels;
|
||||
for (const message of messages) {
|
||||
if (typeof message === 'string') channel!.send(message);
|
||||
else channel!.send(new Uint8Array(message));
|
||||
}
|
||||
}, messages);
|
||||
|
||||
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());
|
||||
|
||||
@@ -256,32 +356,59 @@ async function transfer(
|
||||
await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100);
|
||||
// Removed hidden pages release the service worker for updates.
|
||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||
await expectClosed(sender);
|
||||
await expectClosed(receiver);
|
||||
});
|
||||
}
|
||||
|
||||
for (const mode of Object.keys(MODES)) {
|
||||
for (const from of Object.keys(BROWSERS)) {
|
||||
for (const to of Object.keys(BROWSERS)) {
|
||||
test(`${mode}: ${from} sends to ${to}`, async () => {
|
||||
const sockets: string[] = [];
|
||||
const [sender, receiver] = await Promise.all([open(from, sockets), open(to, sockets)]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
// 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;
|
||||
}
|
||||
|
||||
await transfer(mode, sender, receiver, source, SIZE);
|
||||
if (mode !== 'tracker') {
|
||||
expect(sockets.filter((socket) => !socket.startsWith(url.replace('http', 'ws')))).toEqual([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
// 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 public STUN servers and trackers. 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([]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('build: chromium sends to firefox from the production build', 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 } });
|
||||
try {
|
||||
const base = site.resolvedUrls!.local[0]!;
|
||||
const [sender, receiver] = await Promise.all([open('chromium', { base }), open('firefox', { base })]);
|
||||
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 and keeps the lists over a reload`, async () => {
|
||||
const page = await open(name, []);
|
||||
const page = await open(name);
|
||||
const core = () =>
|
||||
page.evaluate((path) => import(path).then(({ settings }) => [settings.stunServers, settings.trackers]), '/src/main.ts');
|
||||
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');
|
||||
@@ -295,215 +422,379 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example');
|
||||
expect(await core()).toEqual([[], ['wss://tracker.example']]);
|
||||
|
||||
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');
|
||||
});
|
||||
}
|
||||
|
||||
for (const name of Object.keys(BROWSERS)) {
|
||||
// 192.0.2.1 is reserved for documentation and never answers. Without the early stop in gatherIce
|
||||
// Chromium would wait 40 s for it, with only the hard timeout still ICE_TIMEOUT.
|
||||
test(`gather: ${name} stops at the first STUN answer`, async () => {
|
||||
const page = await open(name);
|
||||
await page.click('#servers summary');
|
||||
await page.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}\nstun:192.0.2.1:3478`);
|
||||
await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1)));
|
||||
await page.click('#send-manual summary');
|
||||
const start = Date.now();
|
||||
await page.click('#create-offer');
|
||||
await expect(page.locator('#offer')).toHaveValue(/.+/);
|
||||
expect(Date.now() - start).toBeLessThan(ICE_TIMEOUT / 2);
|
||||
expect(Buffer.from(await page.inputValue('#offer'), 'base64').toString()).toContain(`${PUBLIC_ADDRESS} `);
|
||||
});
|
||||
|
||||
test(`update: ${name} receives after sw.js changed`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
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);
|
||||
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, [], holdReads)]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
||||
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, RUNNING_SIZE, async () => {
|
||||
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!);
|
||||
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!);
|
||||
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(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
|
||||
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 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('iframe')).toHaveCount(0);
|
||||
expect(await log(receiver!)).not.toContain('download complete');
|
||||
await expect(receiver.locator('#log')).toContainText('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('#log')).toContainText('receiver stopped: download cancelled');
|
||||
expect(await log(sender!)).not.toMatch(/ sent$/m);
|
||||
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(`flow: ${name} sender waits while the download manager reads nothing`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
||||
// Proves the sender's window: the receiver only holds back its { read } reports, its download
|
||||
// manager still reads. Memory bounds of a really slow disk are beyond what a test can observe.
|
||||
test(`flow: ${name} sender waits while the receiver reports no reads`, 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, RUNNING_SIZE, async () => {
|
||||
await expect.poll(() => received(receiver!)).toBe(WINDOW);
|
||||
await transfer('offline', sender, receiver, source, HELD_SIZE, async () => {
|
||||
await expect.poll(() => received(receiver)).toBe(WINDOW);
|
||||
// Proving that nothing more comes needs a moment, the sender fills the window in milliseconds.
|
||||
await receiver!.waitForTimeout(1000);
|
||||
expect(await received(receiver!)).toBe(WINDOW);
|
||||
await release(receiver!);
|
||||
await receiver.waitForTimeout(1000);
|
||||
expect(await received(receiver)).toBe(WINDOW);
|
||||
await release(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 = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
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');
|
||||
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(2 * SIZE) };
|
||||
await sender!.setInputFiles('input[type=file]', other);
|
||||
await expect(sender!.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await start('offline', sender, receiver, source);
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
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 edges of the chunking and the window, and a name the Content-Disposition header has to encode.
|
||||
for (const [what, file, size] of [
|
||||
['an empty file', 'empty.bin', 0],
|
||||
// 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);
|
||||
});
|
||||
}
|
||||
|
||||
// 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', 'nobody');
|
||||
await receiver.click('#receive');
|
||||
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
||||
|
||||
// Closes all of the above, transfer checks that.
|
||||
await transfer('offline', sender, receiver, source, 100_000);
|
||||
await expect(sender.locator('#send-code')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
test(`check: ${name} accepts nothing before the receiver confirmed`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, [], recordChannels), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender!, receiver!, async () => {
|
||||
await withLogs(sender, receiver, async () => {
|
||||
let downloads = 0;
|
||||
receiver!.on('download', () => downloads++);
|
||||
await connect('offline', sender!, receiver!, source);
|
||||
receiver.on('download', () => downloads++);
|
||||
await connect('offline', sender, receiver, source);
|
||||
// What a man in the middle could send without waiting for anyone's confirmation.
|
||||
await sender!.evaluate(() => {
|
||||
const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels;
|
||||
channel!.send(JSON.stringify({ name: 'injected.bin', size: 4 }));
|
||||
channel!.send(new Uint8Array(4));
|
||||
});
|
||||
await sender!.click('#confirm');
|
||||
await expect(sender!.locator('#log')).toContainText("waiting for the receiver's security check");
|
||||
await inject(sender, JSON.stringify({ name: 'injected.bin', size: 4 }), 4);
|
||||
await sender.click('#confirm');
|
||||
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
|
||||
// Proving that nothing starts needs a moment, a download would start within milliseconds.
|
||||
await receiver!.waitForTimeout(1000);
|
||||
expect(await log(receiver!)).not.toContain('receiving');
|
||||
expect(await log(sender!)).not.toContain('sending');
|
||||
await receiver.waitForTimeout(1000);
|
||||
expect(await log(receiver)).not.toContain('receiving');
|
||||
expect(await log(sender)).not.toContain('sending');
|
||||
expect(downloads).toBe(0);
|
||||
|
||||
const started = downloadStarts(receiver!);
|
||||
await receiver!.click('#confirm');
|
||||
await receiver!.click('#download');
|
||||
const started = downloadStarts(receiver);
|
||||
await receiver.click('#confirm');
|
||||
await receiver.click('#download');
|
||||
const { download } = await started;
|
||||
expect(download.suggestedFilename()).toBe('payload.bin');
|
||||
expect(await hash(await download.path())).toBe(await hash(source));
|
||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
expect(downloads).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
|
||||
test(`check: ${name} sender shares on after a mismatch`, async () => {
|
||||
const [sender, intruder, receiver] = await Promise.all([open(name, []), open(name, []), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
test(`check: ${name} offers nothing before the sender confirmed`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name, { init: recordChannels })]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender!, receiver!, async () => {
|
||||
await connect('tracker', sender!, intruder!, source);
|
||||
await receiver!.fill('#receive-code', (await sender!.locator('#send-code').textContent())!);
|
||||
await receiver!.click('#receive');
|
||||
await expect(receiver!.locator('#log')).toContainText('looking on');
|
||||
await sender!.click('#reject');
|
||||
await intruder!.context().close();
|
||||
await expect(sender!.locator('#log')).toContainText('waiting for the next receiver');
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('offline', sender, receiver, source);
|
||||
// A receiver that skips its own check and asks for the file right away.
|
||||
await inject(receiver, JSON.stringify({ ok: true }), JSON.stringify({ start: true }));
|
||||
await sender.waitForTimeout(1000);
|
||||
expect(await log(sender)).not.toContain('offered');
|
||||
|
||||
await expect(receiver!.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
||||
await expect(sender!.locator('#check-local')).toHaveText((await receiver!.locator('#check-remote').textContent())!);
|
||||
await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!);
|
||||
const started = downloadStarts(receiver!);
|
||||
await sender!.click('#confirm');
|
||||
await receiver!.click('#confirm');
|
||||
await receiver!.click('#download');
|
||||
const { download } = await started;
|
||||
expect(await hash(await download.path())).toBe(await hash(source));
|
||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
||||
await sender.click('#confirm');
|
||||
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
|
||||
// The early start counted for nothing, the sender waits for one after its offer.
|
||||
await sender.waitForTimeout(500);
|
||||
expect(await log(sender)).not.toContain('sending');
|
||||
});
|
||||
});
|
||||
|
||||
test(`check: ${name} both sides go on after the receiver rejected`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(SIZE));
|
||||
test(`protocol: ${name} receiver refuses an offer that isn't a file`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender!, receiver!, async () => {
|
||||
await connect('tracker', sender!, receiver!, source);
|
||||
const first = await receiver!.locator('#check-local').textContent();
|
||||
// Retrying still has to work for a side that already confirmed.
|
||||
await sender!.click('#confirm');
|
||||
await receiver!.click('#reject');
|
||||
await expect(receiver!.locator('#log')).toContainText('looking again');
|
||||
// The sender notices the receiver left, Chromium only once the connection counts as failed.
|
||||
await expect(sender!.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('offline', sender, receiver, source);
|
||||
await receiver.click('#confirm');
|
||||
await inject(sender, JSON.stringify({ name: 1, size: 2 }));
|
||||
await expect(receiver.locator('#receive-error')).toHaveText('the sender offered no valid file');
|
||||
await expect(receiver.locator('#download')).toHaveCount(0);
|
||||
await expectClosed(receiver);
|
||||
});
|
||||
});
|
||||
|
||||
await expect(receiver!.locator('#check-local')).toHaveText(new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), {
|
||||
timeout: 45_000,
|
||||
});
|
||||
await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!);
|
||||
const started = downloadStarts(receiver!);
|
||||
await sender!.click('#confirm');
|
||||
await receiver!.click('#confirm');
|
||||
await receiver!.click('#download');
|
||||
test(`protocol: ${name} receiver fails a download with more bytes than offered`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, { init: recordChannels }), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('offline', sender, receiver, source);
|
||||
await receiver.click('#confirm');
|
||||
await inject(sender, JSON.stringify({ name: 'twenty.bin', size: 20_000 }));
|
||||
const started = downloadStarts(receiver);
|
||||
await receiver.click('#download');
|
||||
// The download only starts with the first bytes.
|
||||
await inject(sender, 10_000);
|
||||
const { download } = await started;
|
||||
await inject(sender, 10_001);
|
||||
await expect(receiver.locator('#receive-error')).toHaveText('download failed: the sender sent more than it offered');
|
||||
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();
|
||||
await expectClosed(receiver);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
// An offer that can't be answered used to keep the share busy forever.
|
||||
test(`live tracker: ${name} sender goes on after an unusable offer`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await sender.setInputFiles('input[type=file]', source);
|
||||
await sender.click('#share');
|
||||
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
|
||||
const code = (await sender.locator('#send-code').textContent())!;
|
||||
const garbage = await announceGarbage(code);
|
||||
await expect(sender.locator('#log')).toContainText('unusable offer');
|
||||
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
||||
garbage.close();
|
||||
|
||||
await receiver.fill('#receive-code', code);
|
||||
await receiver.click('#receive');
|
||||
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
||||
const started = downloadStarts(receiver);
|
||||
await sender.click('#confirm');
|
||||
await receiver.click('#confirm');
|
||||
await receiver.click('#download');
|
||||
const { download } = await started;
|
||||
expect(await hash(await download.path())).toBe(await hash(source));
|
||||
await expect(sender!.locator('#log')).toContainText('delivered');
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
});
|
||||
});
|
||||
|
||||
// A peer that guessed the code, or got the same one by chance, takes the sender's turn first.
|
||||
test(`live check: ${name} sender shares on after a mismatch`, async () => {
|
||||
const [sender, intruder, receiver] = await Promise.all([open(name), open(name), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('tracker', sender, intruder, source);
|
||||
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||
await receiver.click('#receive');
|
||||
await expect(receiver.locator('#log')).toContainText('looking on');
|
||||
await sender.click('#reject');
|
||||
await intruder.context().close();
|
||||
await expect(sender.locator('#log')).toContainText('waiting for the next receiver');
|
||||
|
||||
await expect(receiver.locator('#check-local')).toBeVisible({ timeout: 45_000 });
|
||||
await expect(sender.locator('#check-local')).toHaveText((await receiver.locator('#check-remote').textContent())!);
|
||||
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
|
||||
const started = downloadStarts(receiver);
|
||||
await sender.click('#confirm');
|
||||
await receiver.click('#confirm');
|
||||
await receiver.click('#download');
|
||||
const { download } = await started;
|
||||
expect(await hash(await download.path())).toBe(await hash(source));
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
});
|
||||
});
|
||||
|
||||
test(`live check: ${name} both sides go on after the receiver rejected`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||
const source = await payload(randomBytes(SIZE));
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await connect('tracker', sender, receiver, source);
|
||||
const first = await receiver.locator('#check-local').textContent();
|
||||
// Retrying still has to work for a side that already confirmed.
|
||||
await sender.click('#confirm');
|
||||
await receiver.click('#reject');
|
||||
await expect(receiver.locator('#log')).toContainText('looking again');
|
||||
// The sender notices the receiver left, Chromium only once the connection counts as failed.
|
||||
await expect(sender.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 });
|
||||
|
||||
await expect(receiver.locator('#check-local')).toHaveText(new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), {
|
||||
timeout: 45_000,
|
||||
});
|
||||
await expect(sender.locator('#check-remote')).toHaveText((await receiver.locator('#check-local').textContent())!);
|
||||
const started = downloadStarts(receiver);
|
||||
await sender.click('#confirm');
|
||||
await receiver.click('#confirm');
|
||||
await receiver.click('#download');
|
||||
const { download } = await started;
|
||||
expect(await hash(await download.path())).toBe(await hash(source));
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
});
|
||||
});
|
||||
|
||||
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
|
||||
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();
|
||||
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('#log')).toContainText('download failed: connection lost', {
|
||||
await expect(receiver.locator('#receive-error')).toHaveText('download failed: connection lost', {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(receiver!.locator('iframe')).toHaveCount(0);
|
||||
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();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// What a broken or hostile receiver could announce for the code: an offer no browser can parse.
|
||||
async function announceGarbage(code: string) {
|
||||
const ws = new WebSocket(TRACKER);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.onopen = resolve;
|
||||
ws.onerror = reject;
|
||||
});
|
||||
const binary = (bytes: Buffer) => bytes.toString('latin1');
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
action: 'announce',
|
||||
info_hash: binary(createHash('sha1').update(`hellcon:${code}`).digest()),
|
||||
peer_id: binary(randomBytes(20)),
|
||||
numwant: 1,
|
||||
uploaded: 0,
|
||||
downloaded: 0,
|
||||
left: 1,
|
||||
event: 'started',
|
||||
offers: [{ offer_id: binary(randomBytes(20)), offer: { type: 'offer', sdp: 'garbage' } }],
|
||||
}),
|
||||
);
|
||||
return ws;
|
||||
}
|
||||
|
||||
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, [], holdReads)]);
|
||||
const source = test.info().outputPath('payload.bin');
|
||||
await writeFile(source, randomBytes(RUNNING_SIZE));
|
||||
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, RUNNING_SIZE, async () => {
|
||||
await expect.poll(() => received(receiver!)).toBe(WINDOW);
|
||||
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!);
|
||||
await receiver.waitForTimeout(40_000);
|
||||
await release(receiver);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -519,7 +810,7 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await file.close();
|
||||
|
||||
// Real profiles on disk like normal users have; downloads go there too instead of the temp dir.
|
||||
const contexts = await Promise.all(
|
||||
const profiles = await Promise.all(
|
||||
['sender', 'receiver'].map((profile) =>
|
||||
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
|
||||
downloadsPath: test.info().outputPath('downloads'),
|
||||
@@ -528,11 +819,15 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
),
|
||||
);
|
||||
try {
|
||||
const [sender, receiver] = await Promise.all(contexts.map((context) => context.newPage()));
|
||||
const [sender, receiver] = await Promise.all(profiles.map((profile) => profile.newPage()));
|
||||
for (const page of [sender!, receiver!]) {
|
||||
sockets.set(page, []);
|
||||
await page.addInitScript(trackPeers);
|
||||
}
|
||||
await Promise.all([sender!.goto(url), receiver!.goto(url)]);
|
||||
await transfer('offline', sender!, receiver!, source, LARGE_SIZE);
|
||||
} finally {
|
||||
await Promise.all(contexts.map((context) => context.close()));
|
||||
await Promise.all(profiles.map((profile) => profile.close()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user