import { createHash, randomBytes } from 'node:crypto'; 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'; // Runs against the real public trackers and STUN servers from src/main.ts. const BROWSERS: Record = { chromium, 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 updates sw.js, cancels or disconnects. const RUNNING_SIZE = 100_000_000; // WINDOW in src/main.ts. const WINDOW = 8 * 2 ** 20; // Each mode connects a sender page that already picked a file to a receiver page. const MODES: Record Promise> = { async manual(sender, receiver) { await sender.click('#create-offer'); await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 }); 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'); } }, // 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.evaluate((path) => import(path).then((core) => core.STUN_SERVERS.push('stun:192.0.2.1:3478')), '/src/main.ts'); } 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(/^\d{8}$/); 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; const browsers: Browser[] = []; // Appended to sw.js, so raising it makes the browser see an update, like a deploy. let swVersion = 0; 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]!; }); test.afterAll(async () => { await Promise.all(browsers.map((browser) => browser.close())); await server.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()).newPage(); page.on('websocket', (ws) => sockets.push(ws.url())); if (init) await page.addInitScript(init); await page.goto(url); return page; } 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 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); }; } // 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. function recordChannels() { const page = window as unknown as { channels: RTCDataChannel[] }; page.channels = []; const create = RTCPeerConnection.prototype.createDataChannel; RTCPeerConnection.prototype.createDataChannel = function (this: RTCPeerConnection, ...args) { const channel = create.apply(this, args); page.channels.push(channel); return channel; }; } 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()); // 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) { 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. async function connect(mode: string, sender: Page, receiver: Page, source: string) { await sender.setInputFiles('input[type=file]', source); await MODES[mode]!(sender, receiver); const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent(); await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, { 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'); } } // Resolves with the download, which starts on its own as soon as the file is announced, 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) })); // Connects and confirms the security check on both sides. async function start(mode: string, sender: Page, receiver: Page, source: string) { await connect(mode, sender, receiver, source); const started = downloadStarts(receiver); 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'); 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, ) { 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'); // Removed hidden pages release the service worker for updates. await expect(receiver.locator('iframe')).toHaveCount(0); }); } 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)); await transfer(mode, sender, receiver, source, SIZE); if (mode !== 'tracker') { expect(sockets.filter((socket) => !socket.startsWith(url.replace('http', 'ws')))).toEqual([]); } }); } } } for (const name of Object.keys(BROWSERS)) { 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)); 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, [], holdReads)]); const source = test.info().outputPath('payload.bin'); await writeFile(source, randomBytes(RUNNING_SIZE)); await transfer('offline', sender!, receiver!, source, RUNNING_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(`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)); 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'); // 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); }); }); 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)); await transfer('offline', sender!, receiver!, source, RUNNING_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!); }); }); 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)); await withLogs(sender!, receiver!, async () => { let downloads = 0; 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"); // 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'); expect(downloads).toBe(0); const started = downloadStarts(receiver!); await receiver!.click('#confirm'); 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'); 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)); 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'); const { download } = await started; expect(await hash(await download.path())).toBe(await hash(source)); await expect(sender!.locator('#log')).toContainText('delivered'); }); }); 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)); 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'); 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)); 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', { 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(); }); }); } 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)); await transfer('offline', sender!, receiver!, source, RUNNING_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 contexts = await Promise.all( ['sender', 'receiver'].map((profile) => BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), { downloadsPath: test.info().outputPath('downloads'), }), ), ); try { const [sender, receiver] = await Promise.all(contexts.map((context) => context.newPage())); 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())); } }); }