482 lines
36 KiB
TypeScript
482 lines
36 KiB
TypeScript
// 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<string, string> = { '.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<void>(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<number, (message: ProtocolMessage) => 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<M extends keyof ProtocolResults>(method: M, params: Record<string, unknown> = {}, sessionId?: string): Promise<ProtocolResults[M]> {
|
||
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<T, Args extends unknown[]>(session: string, fn: (...args: Args) => T, ...args: Args): Promise<Awaited<T>> {
|
||
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<T>;
|
||
}
|
||
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<HTMLInputElement>('.checkbox input');
|
||
if (!checkbox.checked) checkbox.click();
|
||
});
|
||
async function connect(sender: string, receiver: string, size: number, changedIdentity = false) {
|
||
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<HTMLTextAreaElement>('#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<HTMLTextAreaElement>('#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<HTMLTextAreaElement>('#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<HTMLTextAreaElement>('#output-code')?.value), offer);
|
||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#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);
|
||
if (changedIdentity) assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the expected contact')));
|
||
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<HTMLSelectElement>('#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<HTMLSelectElement>('#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<HTMLAnchorElement>('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<HTMLInputElement>('.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<HTMLAnchorElement>('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<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
|
||
const diagnostics = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#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<HTMLAnchorElement>('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<HTMLAnchorElement>('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<HTMLAnchorElement>('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<HTMLInputElement>('#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<HTMLButtonElement>('button[aria-label="Remove remove-me.bin"]').click());
|
||
await click(receiver, 'Send');
|
||
assert.equal(await evaluate(receiver, () => document.activeElement?.getAttribute('aria-labelledby')), 'send-heading');
|
||
await evaluate(receiver, () => window.__hellcon.chooseFile(8193, 'return.bin'));
|
||
await click(receiver, 'Receive');
|
||
assert.equal(await evaluate(receiver, () => document.activeElement?.getAttribute('aria-labelledby')), 'receive-heading');
|
||
await click(sender, 'Receive');
|
||
assert.equal(await evaluate(sender, () => document.activeElement?.getAttribute('aria-labelledby')), 'receive-heading');
|
||
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<HTMLAnchorElement>('a.download')?.download === 'return.bin');
|
||
await wait(receiver, () => document.querySelector<HTMLAnchorElement>('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<HTMLAnchorElement>('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 live Send/Receive navigation without reconnecting.');
|
||
|
||
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<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
|
||
assert.match(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#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) {
|
||
const identitySender = await page();
|
||
const identityReceiver = await page(origin.replace('127.0.0.1', 'localhost'));
|
||
await click(identityReceiver, 'Receive');
|
||
for (const session of [identitySender, identityReceiver]) {
|
||
await evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered devices'); if (details) details.open = true; });
|
||
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
|
||
await click(session, 'Create device identity');
|
||
await wait(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')?.checked);
|
||
}
|
||
await connect(identitySender, identityReceiver, 2048);
|
||
for (const session of [identitySender, identityReceiver]) {
|
||
await wait(session, () => !!document.querySelector('#contact-name'));
|
||
await input(session, '#contact-name', 'Paired device');
|
||
await click(session, 'Remember device');
|
||
await wait(session, () => !document.querySelector('#contact-name'));
|
||
}
|
||
await checkAccessibility(identitySender, 'remembered identity');
|
||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
await click(identitySender, 'Disconnect');
|
||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reset'));
|
||
// Reload both pages to exercise persisted CryptoKeys and contacts.
|
||
for (const [session, url] of [[identitySender, origin], [identityReceiver, origin.replace('127.0.0.1', 'localhost')]]) {
|
||
await call('Page.navigate', { url }, session);
|
||
await wait(session, () => !!document.querySelector('#stun-provider'));
|
||
}
|
||
await click(identityReceiver, 'Receive');
|
||
for (const session of [identitySender, identityReceiver]) {
|
||
await wait(session, () => !!document.querySelector('#use-device-identity'));
|
||
assert.equal(await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.checked), false, 'Reload defaults to a temporary connection');
|
||
await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.click());
|
||
const key = await evaluate(session, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
|
||
await input(session, '#expected-device', key);
|
||
await input(session, '#stun-provider', 'none');
|
||
}
|
||
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
|
||
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
|
||
const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||
assert.equal(JSON.parse(atob(offer)).version, 4);
|
||
await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer');
|
||
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
|
||
const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||
await input(identitySender, '#answer-input', answer); await click(identitySender, 'Connect');
|
||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||
for (const session of [identitySender, identityReceiver]) assert.ok(await evaluate(session, () => document.body.textContent?.includes('Remembered device authenticated')));
|
||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
const rememberedBytes = await evaluate(identityReceiver, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; });
|
||
assert.deepEqual(rememberedBytes, { length: 4096, valid: true });
|
||
console.log('PASS: identities and contacts persist across reload; fresh mutual proofs authenticate remembered devices and transfer exact bytes without manual reconfirmation.');
|
||
|
||
await click(identitySender, 'Disconnect');
|
||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||
for (const forgottenSide of [identitySender, identityReceiver]) {
|
||
const editor = await page(forgottenSide === identitySender ? origin : origin.replace('127.0.0.1', 'localhost'));
|
||
await wait(editor, () => !!document.querySelector('#expected-device'));
|
||
await click(editor, 'Forget');
|
||
await wait(editor, () => document.querySelector<HTMLSelectElement>('#expected-device')?.options.length === 1);
|
||
assert.ok(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), 'Original tab still has the stale expected contact before connection setup');
|
||
|
||
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-contact.bin'));
|
||
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
|
||
const freshOffer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||
await input(identityReceiver, '#offer-input', freshOffer); await click(identityReceiver, 'Accept & create answer');
|
||
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
|
||
const freshAnswer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||
await input(identitySender, '#answer-input', freshAnswer); await click(identitySender, 'Connect');
|
||
await wait(forgottenSide, () => document.body.textContent?.includes('New device. Compare both fingerprints manually'));
|
||
assert.equal(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), '');
|
||
assert.equal(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 1);
|
||
assert.equal(await evaluate(identityReceiver, () => !!document.querySelector('.incoming')), false, 'Forgotten trust must not release file metadata');
|
||
await click(forgottenSide, 'Both fingerprints match — confirm');
|
||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
await input(forgottenSide, '#contact-name', 'Paired device'); await click(forgottenSide, 'Remember device');
|
||
await wait(forgottenSide, () => !document.querySelector('#contact-name'));
|
||
await click(identitySender, 'Disconnect');
|
||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||
const key = await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
|
||
await input(forgottenSide, '#expected-device', key);
|
||
}
|
||
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and permits pairing again.');
|
||
|
||
await evaluate(identitySender, () => { indexedDB.open = () => { throw new DOMException('Storage denied during refresh', 'SecurityError'); }; });
|
||
await evaluate(identitySender, () => window.__hellcon.chooseFile(1, 'storage-failure.bin'));
|
||
await click(identitySender, 'Create code');
|
||
await wait(identitySender, () => document.body.textContent?.includes('Storage denied during refresh'));
|
||
assert.equal(await evaluate(identitySender, () => !!document.querySelector('#output-code')), false, 'Failed storage refresh must not use cached trust');
|
||
await evaluate(identitySender, () => { Reflect.deleteProperty(indexedDB, 'open'); });
|
||
await click(identitySender, 'Reset');
|
||
console.log('PASS: unreadable storage during connection setup cannot reuse a cached identity or contact.');
|
||
|
||
await evaluate(identityReceiver, () => {
|
||
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Replace or delete'));
|
||
label?.querySelector<HTMLInputElement>('input')?.click();
|
||
});
|
||
await click(identityReceiver, 'Delete identity and contacts');
|
||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity'));
|
||
await click(identityReceiver, 'Create device identity');
|
||
await wait(identityReceiver, () => document.querySelector<HTMLInputElement>('#use-device-identity')?.checked);
|
||
await connect(identitySender, identityReceiver, 512, true);
|
||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
assert.equal(await evaluate(identitySender, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 2, 'Changed identity must not replace or append saved contacts automatically');
|
||
console.log('PASS: replaced peer identity requires manual comparison and preserves the original saved contact.');
|
||
const stale = await page();
|
||
await wait(stale, () => !!document.querySelector('#use-device-identity'));
|
||
await evaluate(stale, async () => {
|
||
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
|
||
await new Promise<void>((resolve, reject) => {
|
||
const tx = db.transaction('settings', 'readwrite'), store = tx.objectStore('settings'), request = store.get('state');
|
||
request.onsuccess = () => store.put({ ...request.result, revision: crypto.randomUUID() }, 'state');
|
||
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
|
||
}); db.close();
|
||
});
|
||
await click(stale, 'Forget');
|
||
await wait(stale, () => document.body.textContent?.includes('Device settings changed in another tab'));
|
||
await evaluate(stale, async () => {
|
||
const db = await new Promise<IDBDatabase>(resolve => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); });
|
||
await new Promise<void>(resolve => { const tx = db.transaction('settings', 'readwrite'); tx.objectStore('settings').put({ identity: null, contacts: 'broken', revision: 'broken' }, 'state'); tx.oncomplete = () => resolve(); }); db.close();
|
||
});
|
||
await call('Page.navigate', { url: origin }, stale);
|
||
await wait(stale, () => document.body.textContent?.includes('Invalid contact list'));
|
||
await evaluate(stale, () => [...document.querySelectorAll('label')].find(label => label.textContent?.includes('Delete unreadable device storage'))?.querySelector<HTMLInputElement>('input')?.click());
|
||
await click(stale, 'Clear device storage');
|
||
await wait(stale, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
|
||
console.log('PASS: stale contact edits cannot overwrite newer settings; unreadable storage can be cleared with explicit consent.');
|
||
const denied = await page();
|
||
await call('Page.addScriptToEvaluateOnNewDocument', { source: "indexedDB.open = () => { throw new DOMException('Storage denied', 'SecurityError'); };" }, denied);
|
||
await call('Page.navigate', { url: origin }, denied);
|
||
await wait(denied, () => document.body.textContent?.includes('Storage denied'));
|
||
await evaluate(denied, () => window.__hellcon.chooseFile(1, 'temporary.bin'));
|
||
await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code');
|
||
await wait(denied, () => !!document.querySelector('#output-code'));
|
||
const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||
assert.equal(JSON.parse(atob(temporary)).version, 3);
|
||
await click(denied, 'Cancel connection');
|
||
console.log('PASS: denied identity storage still allows temporary v3 connection setup.');
|
||
|
||
}
|
||
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<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });
|
||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||
await vite?.close();
|
||
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
||
}
|