// Dependency-free Chromium integration check. Run after `bun run build`. import { Readable, Writable } from 'node:stream'; import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts'; import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { createServer } from 'node:http'; import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises'; import { createReadStream } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, extname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const axeSource = await readFile(join(root, 'node_modules/axe-core/axe.min.js'), 'utf8'); const provider = process.argv.includes('--default-network') ? 'pagequit' : 'none'; const turn = process.argv.includes('--turn'); const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp'; const streaming = process.argv.includes('--stream-download'); const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null; const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-')); const server = createServer(async (req, res) => { if (vite) return vite.middlewares(req, res); try { const pathname = new URL(req.url ?? '/', 'http://localhost').pathname; const base = join(root, 'dist'); const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname)); if (!path.startsWith(base + '/')) throw new Error('Invalid path'); const types: Record = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png' }; res.setHeader('Content-Type', types[extname(path)] || 'application/octet-stream'); res.end(await readFile(path)); } catch { res.statusCode = 404; res.end(); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const address = server.address(); assert.ok(address && typeof address !== 'string'); const origin = `http://127.0.0.1:${address.port}`; const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [ '--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] }); interface ProtocolResults { 'Browser.setDownloadBehavior': object; 'Target.createTarget': { targetId: string }; 'Target.attachToTarget': { sessionId: string }; 'Runtime.enable': object; 'Page.enable': object; 'Page.navigate': object; 'Page.addScriptToEvaluateOnNewDocument': object; 'Runtime.evaluate': { exceptionDetails?: unknown; result: { value?: unknown } }; } interface ProtocolMessage { id?: number; method?: string; params?: { exceptionDetails?: unknown }; error?: unknown; result?: unknown; } const pipeIn = browser.stdio[3], pipeOut = browser.stdio[4]; assert.ok(pipeIn instanceof Writable && pipeOut instanceof Readable && browser.stderr); const commandPipe = pipeIn; let stderr = '', nextId = 0, buffer = ''; const pending = new Map void>(); const browserErrors: unknown[] = []; browser.stderr.on('data', data => { stderr += data; }); pipeIn.on('error', () => {}); pipeOut.on('error', () => {}); pipeOut.on('data', data => { buffer += data; let end; while ((end = buffer.indexOf('\0')) !== -1) { const message: ProtocolMessage = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1); if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); } if (message.method === 'Runtime.exceptionThrown') browserErrors.push(message.params?.exceptionDetails); } }); function call(method: M, params: Record = {}, sessionId?: string): Promise { return new Promise((resolve, reject) => { const id = ++nextId; const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timed out: ${method}\n${stderr.slice(-1500)}`)); }, 45000); pending.set(id, message => { clearTimeout(timer); message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result as ProtocolResults[M]); }); commandPipe.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0'); }); } async function evaluate(session: string, fn: (...args: Args) => T, ...args: Args): Promise> { const expression = `(${fn.toString()})(...${JSON.stringify(args)})`; const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session); if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails)); // CDP returns the serialized result of this exact callback. return result.result.value as Awaited; } async function wait(session: string, check: () => unknown) { const expression = `window.__hellcon.wait(${check.toString()})`; const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session); if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails)); } async function page(url = origin) { const { targetId } = await call('Target.createTarget', { url: 'about:blank' }); const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true }); await call('Runtime.enable', {}, sessionId); await call('Page.enable', {}, sessionId); await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId); if (streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId); if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId); await call('Page.navigate', { url }, sessionId); for (let n = 0; n < 100; n++) { try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url)) break; } catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; } await new Promise(resolve => setTimeout(resolve, 20)); } try { await wait(sessionId, () => !!document.querySelector('#stun-provider')); } catch (error) { throw new Error(`${url}: ${String(error)}; browser errors: ${JSON.stringify(browserErrors)}`); } return sessionId; } async function checkAccessibility(session: string, mode: string) { const injected = await call('Runtime.evaluate', { expression: axeSource }, session); assert.equal(injected.exceptionDetails, undefined, 'axe-core should load in the page'); const violations = await evaluate(session, async () => { const axe = (window as unknown as { axe: { run: (context: Document) => Promise<{ violations: Array<{ id: string; nodes: Array<{ target: string[] }> }> }> } }).axe; const results = await axe.run(document); return results.violations.map(({ id, nodes }) => ({ id, targets: nodes.map(({ target }) => target) })); }); assert.deepEqual(violations, [], `${mode} mode accessibility violations`); } const click = (session: string, label: string) => evaluate(session, (label: string) => window.__hellcon.click(label), label); const input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value); const enableTurn = (session: string) => evaluate(session, () => { const checkbox = window.__hellcon.element('.checkbox input'); if (!checkbox.checked) checkbox.click(); }); async function connect(sender: string, receiver: string, size: number) { await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size); await input(sender, '#stun-provider', provider); await input(receiver, '#stun-provider', provider); if (turn) { await enableTurn(sender); await enableTurn(receiver); } await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code')); const offer = await evaluate(sender, () => window.__hellcon.element('#output-code').value); await input(receiver, '#offer-input', 'invalid-code!'); await click(receiver, 'Accept & create answer'); await wait(receiver, () => !!document.querySelector('[role=alert]')); assert.equal(await evaluate(receiver, () => window.__hellcon.element('#offer-input').disabled), false); if (turn) await enableTurn(receiver); await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer'); await wait(receiver, () => !!document.querySelector('#output-code')); const answer = await evaluate(receiver, () => window.__hellcon.element('#output-code').value); await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect'); await wait(sender, () => !!document.querySelector('[role=alert]')); assert.equal(await evaluate(sender, () => window.__hellcon.element('#output-code')?.value), offer); assert.equal(await evaluate(sender, () => window.__hellcon.element('#answer-input').disabled), false); await input(sender, '#answer-input', answer); await click(sender, 'Connect'); await wait(sender, () => !!document.querySelector('.fingerprint')); const sf = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)); const rf = await evaluate(receiver, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)); assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0]?.split(' ').length, 32); assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false); await click(sender, 'Both fingerprints match — confirm'); await new Promise(resolve => setTimeout(resolve, 100)); assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false); await click(receiver, 'Both fingerprints match — confirm'); await wait(receiver, () => !!document.querySelector('.incoming')); if (turn) { for (const session of [sender, receiver]) { const types = await evaluate(session, relayCandidateTypes); assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates'); } } } try { if (streaming) { const downloads = join(profile, 'downloads'); await mkdir(downloads); await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); const sender = await page(), receiver = await page(); await click(receiver, 'Receive'); for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) { if (size === 0) await connect(sender, receiver, size); else { await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size); await wait(receiver, () => !!document.querySelector('.incoming')); } assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined'); await click(receiver, `Receive as download (${size === 0 ? '0 B' : (size / 1024 ** 2).toFixed(1) + ' MiB'})`); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/); const destination = join(downloads, 'browser-test.bin'); const deadline = Date.now() + 30000; while (true) { try { if ((await stat(destination)).size === size) break; } catch {} if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.'); await new Promise(resolve => setTimeout(resolve, 100)); } let bytes = 0; for await (const chunk of createReadStream(destination)) { assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match'); bytes += (chunk as Buffer).length; } assert.equal(bytes, size); await rm(destination); console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`); } assert.deepEqual(browserErrors, []); } else { const sender = await page(), receiver = await page(); if (!turn) { assert.equal(await evaluate(sender, () => document.querySelector('#stun-provider')?.value), 'pagequit'); } if (!turn) { const localUrl = pathToFileURL(join(root, 'dist/hellcon-local.html')).href; const localReceiver = await page(localUrl); assert.equal(await evaluate(localReceiver, () => document.querySelector('#stun-provider')?.value), 'pagequit'); assert.equal(await evaluate(localReceiver, () => document.querySelector('h1')?.textContent), 'HellCon'); await click(localReceiver, 'Receive'); assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true); const localSender = await page(localUrl); await connect(localSender, localReceiver, 1024); assert.equal(await evaluate(localReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent?.includes('Receive as download'))), false, 'file:// must not offer service-worker downloads'); await click(localReceiver, 'Receive in memory (up to 64 MiB)'); await wait(localReceiver, () => !!document.querySelector('a.download')); const data = await evaluate(localReceiver, async () => { const bytes = new Uint8Array(await (await fetch(document.querySelector('a.download')!.href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; }); assert.deepEqual(data, { length: 1024, valid: true }); console.log('PASS: standalone HTML opens from file:// and transfers a file between two local copies.'); } await click(receiver, 'Receive'); await checkAccessibility(sender, 'Send'); await checkAccessibility(receiver, 'Receive'); console.log('PASS: axe-core accessibility scan in initial Send and Receive modes.'); assert.equal(await evaluate(sender, () => window.__hellcon.element('.checkbox input').checked), false); await connect(sender, receiver, 2 * 1024 * 1024 + 7); await checkAccessibility(sender, 'Send during transfer'); await checkAccessibility(receiver, 'Receive before accepting a file'); await click(receiver, 'Receive in memory (up to 64 MiB)'); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); await checkAccessibility(sender, 'Send after transfer'); await checkAccessibility(receiver, 'Receive after transfer'); console.log('PASS: axe-core accessibility scan during and after transfer.'); const data = await evaluate(receiver, async () => { const response = await fetch(window.__hellcon.element('a.download').href); const bytes = new Uint8Array(await response.arrayBuffer()); return { length: bytes.length, valid: bytes.every(b => b === 123) }; }); assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true }); await wait(sender, () => window.__hellcon.element('#connection-diagnostics').value.includes('pairs=')); const diagnostics = await evaluate(sender, () => window.__hellcon.element('#connection-diagnostics').value); assert.match(diagnostics, /local code: host=\d+/); assert.match(diagnostics, /remote code: host=\d+/); assert.match(diagnostics, /requestsSent=/); assert.match(diagnostics, /transfer done/); assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/); console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.'); console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.'); const originalFingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)); for (const size of [0, 4097]) { const previousDownload = await evaluate(receiver, () => window.__hellcon.element('a.download').href); await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'another.bin'), size); await wait(receiver, () => !!document.querySelector('.incoming')); assert.equal(await evaluate(receiver, () => window.__hellcon.element('a.download').href), previousDownload); assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Waiting for the receiver to accept the file…'); assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints); await click(receiver, 'Receive in memory (up to 64 MiB)'); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); const next = await evaluate(receiver, async () => { const link = window.__hellcon.element('a.download'); const bytes = new Uint8Array(await (await fetch(link.href)).arrayBuffer()); return { name: link.download, length: bytes.length, valid: bytes.every(byte => byte === 123) }; }); assert.deepEqual(next, { name: 'another.bin', length: size, valid: true }); } console.log('PASS: consecutive files including an empty file reuse fingerprints, require acceptance, and preserve the previous download until acceptance.'); // Queue two files and send back simultaneously, on the same peer connection. await evaluate(sender, () => { const input = window.__hellcon.element('#file-input'); const files = new DataTransfer(); for (const name of ['decline-me.bin', 'queued.bin', 'remove-me.bin']) files.items.add(new File([new Uint8Array(1024).fill(123)], name)); input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true })); }); await evaluate(sender, () => window.__hellcon.element('button[aria-label="Remove remove-me.bin"]').click()); await evaluate(receiver, () => window.__hellcon.chooseFile(8193, 'return.bin')); await wait(sender, () => !!document.querySelector('.incoming')); await wait(receiver, () => !!document.querySelector('.incoming')); await click(receiver, 'Decline file'); await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('queued.bin')); await click(sender, 'Receive in memory (up to 64 MiB)'); await click(receiver, 'Receive in memory (up to 64 MiB)'); await wait(sender, () => document.querySelector('a.download')?.download === 'return.bin'); await wait(receiver, () => document.querySelector('a.download')?.download === 'queued.bin'); for (const [session, size] of [[sender, 8193], [receiver, 1024]] as const) { const received = await evaluate(session, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element('a.download').href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; }); assert.deepEqual(received, { length: size, valid: true }); await checkAccessibility(session, 'Bidirectional session'); } assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.tabs button')].every(button => (button as HTMLButtonElement).disabled)), true); assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints); console.log('PASS: simultaneous bidirectional transfers, multiple-file queue, removal, decline, exact bytes, and locked setup tabs.'); await click(sender, 'Reset'); await click(receiver, 'Reset'); assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.'); assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.'); console.log('PASS: Reset restores the ready state on both sides.'); await evaluate(receiver, simulateSlowDisk); await connect(sender, receiver, 2 * 1024 * 1024); await click(receiver, 'Choose destination & receive to disk'); await wait(receiver, () => !!window.__hellcon.releaseWrite); await evaluate(sender, () => window.__hellcon.chooseFile(1024, 'pending-at-disconnect.bin')); assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), true); await click(sender, 'Disconnect'); assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), false); await wait(receiver, () => window.__hellcon.aborted); assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false); await wait(receiver, () => window.__hellcon.element('#connection-diagnostics').value.includes('pairs=')); assert.match(await evaluate(receiver, () => window.__hellcon.element('#connection-diagnostics').value), /session failed/); console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.'); console.log('PASS: Disconnect closes the connection and aborts the receiver’s pending disk write.'); await click(sender, 'Reset'); await click(receiver, 'Reset'); await connect(sender, receiver, 2048); await click(receiver, 'Receive in memory (up to 64 MiB)'); await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.'); if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`); assert.deepEqual(browserErrors, []); } } finally { browser.kill(); await new Promise(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); }); await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); await vite?.close(); await rm(profile, { recursive: true, force: true, maxRetries: 3 }); }