Offers and answers now go through the HC1 codec: the sender creates a ref per session and the answer must echo it, so pasting an offer as the answer or an answer for another code is rejected with a specific message while the live offer stays usable. Pasted input may be a full link. webrtc.ts drops its Base64 JSON signaling and exchanges validated SDP only; identity hellos travel in the code envelope. Tests, the browser check, compare-ice and the docs follow the new format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
641 lines
48 KiB
TypeScript
641 lines
48 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 { CODE_PREFIX, decodeCode } from '../src/lib/codes.ts';
|
||
import assert from 'node:assert/strict';
|
||
import { spawn } from 'node:child_process';
|
||
import { createServer } from 'node:http';
|
||
import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
||
import { createReadStream } from 'node:fs';
|
||
import { tmpdir } from 'node:os';
|
||
import { dirname, extname, join, resolve } from 'node:path';
|
||
import { fileURLToPath } 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 connections = process.argv.includes('--connections');
|
||
const screenshotDirectory = process.env.BROWSER_SCREENSHOT_DIR || (process.argv.includes('--screenshots') ? join(tmpdir(), 'hellcon-layout') : '');
|
||
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 {
|
||
'Emulation.setDeviceMetricsOverride': object;
|
||
'Emulation.setFocusEmulationEnabled': object;
|
||
'Page.captureScreenshot': { data: string };
|
||
'Page.bringToFront': object;
|
||
'Input.dispatchKeyEvent': object;
|
||
'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);
|
||
// Background tabs otherwise skip focus/blur events, which the name editor relies on.
|
||
await call('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId);
|
||
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
|
||
// The native picker would block headless runs; simulateSlowDisk installs a test double where needed.
|
||
await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId);
|
||
// Without streaming downloads the app falls back to memory, whose bytes the default checks read in-page.
|
||
if (!streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: "Object.defineProperty(navigator, 'serviceWorker', { value: 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);
|
||
assert.ok(offer.startsWith(CODE_PREFIX));
|
||
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', offer); await click(sender, 'Connect');
|
||
await wait(sender, () => document.querySelector('[role=alert]')?.textContent?.includes('not an answer'));
|
||
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) {
|
||
// The receiver still trusts the unchanged sender and verifies automatically;
|
||
// the sender must compare manually and is not offered a silent replacement.
|
||
assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the paired device')));
|
||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Replace the paired device'))?.querySelector('input')?.checked), false);
|
||
await wait(receiver, () => document.body.textContent?.includes('Verification submitted'));
|
||
await click(sender, 'Both fingerprints match — confirm');
|
||
} else {
|
||
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');
|
||
}
|
||
}
|
||
}
|
||
async function verifySavedFile(path: string, size: number) {
|
||
const deadline = Date.now() + 30000;
|
||
while (true) {
|
||
try { if ((await stat(path)).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(path)) {
|
||
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
|
||
bytes += (chunk as Buffer).length;
|
||
}
|
||
assert.equal(bytes, size);
|
||
await rm(path);
|
||
}
|
||
try {
|
||
// Received files land in the throwaway profile instead of the user's Downloads.
|
||
const downloads = join(profile, 'downloads');
|
||
await mkdir(downloads);
|
||
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
|
||
if (connections) {
|
||
const sender = await page(), receiver = await page(origin.replace('127.0.0.1', 'localhost'));
|
||
const selectConnection = (session: string, name: string) => evaluate(session, (name: string) => {
|
||
const button = [...document.querySelectorAll<HTMLButtonElement>('.connection-link')].find(item => item.querySelector('.connection-name')?.textContent === name);
|
||
if (!button) throw new Error('Missing connection: ' + name);
|
||
button.click();
|
||
}, name);
|
||
const screenshot = async (session: string, name: string) => {
|
||
if (!screenshotDirectory) return;
|
||
await mkdir(screenshotDirectory, { recursive: true });
|
||
await call('Page.bringToFront', {}, session);
|
||
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
|
||
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64'));
|
||
};
|
||
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
|
||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
|
||
await checkAccessibility(sender, 'Connections desktop');
|
||
await screenshot(sender, 'connections-desktop');
|
||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
||
await input(sender, '#connection-name', 'Work laptop');
|
||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur());
|
||
await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop');
|
||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
||
await input(sender, '#connection-name', ' ');
|
||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur());
|
||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').value), 'Work laptop');
|
||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
||
await input(sender, '#connection-name', 'Work laptop ');
|
||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender);
|
||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender);
|
||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').value), 'Work laptop');
|
||
assert.equal(await evaluate(sender, () => document.activeElement?.id === 'connection-name'), false);
|
||
await click(receiver, 'Receive');
|
||
await connect(sender, receiver, 4097);
|
||
const fingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent));
|
||
await click(sender, 'Add connection');
|
||
await wait(sender, () => document.querySelector('.title-line h1')?.textContent === 'Con 2');
|
||
assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false);
|
||
await click(receiver, 'Accept file');
|
||
await wait(sender, () => document.querySelector('.connection-link .connection-preview')?.textContent === 'browser-test.bin');
|
||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0, 'Hidden session activity must stay in its own slot');
|
||
await selectConnection(sender, 'Work laptop');
|
||
await wait(sender, () => document.querySelector('.session-badge')?.textContent?.includes('Connected'));
|
||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)), fingerprints);
|
||
await evaluate(sender, () => window.__hellcon.chooseFile(1234, 'after-switch.bin'));
|
||
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin'));
|
||
await click(receiver, 'Accept file');
|
||
await wait(sender, () => document.querySelectorAll('.activity-item').length === 2);
|
||
const received = await evaluate(receiver, async () => {
|
||
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||
return { size: bytes.length, valid: bytes.every(byte => byte === 123) };
|
||
});
|
||
assert.deepEqual(received, { size: 1234, valid: true });
|
||
await click(sender, 'Disconnect'); await click(sender, 'Reset');
|
||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 2, 'Reset must preserve slot history');
|
||
await checkAccessibility(sender, 'Connections with history');
|
||
await screenshot(sender, 'connections-history');
|
||
await selectConnection(sender, 'Con 2');
|
||
await evaluate(sender, () => window.__hellcon.chooseFile(10, 'draft.bin'));
|
||
await selectConnection(sender, 'Work laptop'); await selectConnection(sender, 'Con 2');
|
||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.panel li')].some(item => item.textContent?.includes('draft.bin'))), true, 'Selected file state survives slot switching');
|
||
await call('Page.navigate', { url: origin }, sender);
|
||
await wait(sender, () => document.querySelectorAll('.activity-item').length === 2);
|
||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Work laptop');
|
||
assert.equal(await evaluate(sender, () => document.querySelector('.session-badge')?.textContent), 'Ready to connect');
|
||
await selectConnection(sender, 'Con 2');
|
||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
|
||
assert.equal(await evaluate(sender, () => document.querySelector<HTMLInputElement>('#file-input')?.files?.length), 0, 'File contents must not persist after reload');
|
||
console.log('PASS: connections retain names and separate histories across reload; switching preserves live transfers and drafts; Reset preserves history.');
|
||
|
||
const other = await page();
|
||
await Promise.all([click(sender, 'Add connection'), click(other, 'Add connection')]);
|
||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 4);
|
||
await wait(other, () => document.querySelectorAll('.connection-link').length === 4);
|
||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Work laptop', 'Con 2', 'Con 3', 'Con 4']);
|
||
console.log('PASS: concurrent tabs add distinct connection slots and synchronize their sidebars.');
|
||
|
||
await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, sender);
|
||
await selectConnection(sender, 'Work laptop');
|
||
await checkAccessibility(sender, 'Connections mobile');
|
||
assert.equal(await evaluate(sender, () => document.documentElement.scrollWidth <= innerWidth), true, 'Mobile workspace must not overflow horizontally');
|
||
await screenshot(sender, 'connections-mobile');
|
||
await click(sender, 'Remove');
|
||
await wait(sender, () => !!document.querySelector('dialog[open]'));
|
||
await checkAccessibility(sender, 'Removal dialog mobile');
|
||
await screenshot(sender, 'connections-mobile-dialog');
|
||
await click(sender, 'Close dialog');
|
||
await wait(sender, () => !document.querySelector('dialog[open]'));
|
||
await click(sender, 'Show connections');
|
||
await checkAccessibility(sender, 'Connections mobile sidebar');
|
||
assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'flex');
|
||
await screenshot(sender, 'connections-mobile-sidebar');
|
||
await selectConnection(sender, 'Con 2');
|
||
assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'none');
|
||
console.log('PASS: mobile navigation opens and closes, fits the viewport, and passes accessibility checks.');
|
||
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
|
||
await selectConnection(sender, 'Work laptop');
|
||
await click(receiver, 'Reset');
|
||
await connect(sender, receiver, 1024);
|
||
await selectConnection(sender, 'Con 2');
|
||
await selectConnection(other, 'Work laptop');
|
||
await evaluate(other, () => window.__hellcon.element<HTMLButtonElement>('.header-action').focus());
|
||
await click(other, 'Remove');
|
||
await wait(other, () => !!document.querySelector('dialog[open]'));
|
||
assert.equal(await evaluate(other, () => document.activeElement?.textContent?.trim()), 'Keep connection', 'Dialog starts on its non-destructive action');
|
||
await checkAccessibility(other, 'Remove connection confirmation');
|
||
await screenshot(other, 'connections-remove-dialog');
|
||
for (let i = 0; i < 5; i++) {
|
||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }, other);
|
||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }, other);
|
||
assert.equal(await evaluate(other, () => !!document.querySelector('dialog[open]')?.contains(document.activeElement)), true, 'Tab stays within the modal');
|
||
}
|
||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other);
|
||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other);
|
||
await wait(other, () => !document.querySelector('dialog[open]'));
|
||
assert.equal(await evaluate(other, () => document.activeElement?.classList.contains('header-action')), true, 'Dialog restores focus to the opener');
|
||
await click(other, 'Remove');
|
||
await click(other, 'Keep connection');
|
||
assert.equal(await evaluate(other, () => document.querySelectorAll('.connection-link').length), 4);
|
||
await click(other, 'Remove'); await click(other, 'Remove connection');
|
||
await wait(other, () => document.querySelectorAll('.connection-link').length === 3);
|
||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 3);
|
||
await wait(receiver, () => !document.querySelector('.incoming'));
|
||
await call('Page.navigate', { url: origin }, sender);
|
||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Work laptop')), false);
|
||
for (let count = 3; count > 0; count--) {
|
||
const oldName = await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent);
|
||
await click(sender, 'Remove'); await click(sender, 'Remove connection');
|
||
await wait(sender, () => !document.querySelector('dialog[open]'));
|
||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.connection-link').length), Math.max(1, count - 1));
|
||
assert.notEqual(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), oldName);
|
||
}
|
||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
|
||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
|
||
await call('Page.navigate', { url: origin }, sender);
|
||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Con 1']);
|
||
console.log('PASS: removal can be cancelled, persists across reload, closes cached sessions in other tabs, and replaces the last slot with a fresh Con 1.');
|
||
assert.deepEqual(browserErrors, []);
|
||
} else if (streaming) {
|
||
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, 'Accept file');
|
||
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/);
|
||
await verifySavedFile(join(downloads, 'browser-test.bin'), size);
|
||
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');
|
||
}
|
||
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, 'Accept file');
|
||
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 });
|
||
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
|
||
await verifySavedFile(join(downloads, 'browser-test.bin'), 2 * 1024 * 1024 + 7);
|
||
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; memory fallback saves to Downloads automatically.');
|
||
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, 'Accept file');
|
||
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, 'Accept file');
|
||
await click(receiver, 'Accept file');
|
||
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, 'Accept file');
|
||
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 evaluate(receiver, () => { window.showSaveFilePicker = undefined; });
|
||
await connect(sender, receiver, 2048);
|
||
await click(receiver, 'Accept file');
|
||
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 receiverOrigin = origin.replace('127.0.0.1', 'localhost');
|
||
const identityReceiver = await page(receiverOrigin);
|
||
await click(identityReceiver, 'Receive');
|
||
const pairedKey = (session: string) => evaluate(session, () => document.querySelector('.device-settings code')?.textContent || '');
|
||
// Clears the paired device directly in storage, so this tab is not notified.
|
||
const forgetQuietly = (session: string) => evaluate(session, async () => {
|
||
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-connections', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
|
||
await new Promise<void>((resolve, reject) => {
|
||
const tx = db.transaction('connections', 'readwrite'), store = tx.objectStore('connections'), request = store.getAll();
|
||
request.onsuccess = () => { for (const record of request.result) store.put({ ...record, peerKey: '' }); };
|
||
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
|
||
}); db.close();
|
||
});
|
||
for (const session of [identitySender, identityReceiver]) {
|
||
await evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered device'); 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>('#remember-device')?.checked);
|
||
}
|
||
await connect(identitySender, identityReceiver, 2048);
|
||
for (const session of [identitySender, identityReceiver]) {
|
||
await wait(session, () => document.body.textContent?.includes('Remembered for Con 1'));
|
||
await wait(session, () => !!document.querySelector('.device-settings code'));
|
||
}
|
||
await checkAccessibility(identitySender, 'remembered identity');
|
||
await click(identityReceiver, 'Accept file');
|
||
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 paired connections.
|
||
for (const [session, url] of [[identitySender, origin], [identityReceiver, receiverOrigin]]) {
|
||
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('.device-settings code'));
|
||
assert.equal(await evaluate(session, () => !!document.querySelector('#remember-device')), false, 'A paired connection shows its device instead of the opt-in');
|
||
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.ok((await decodeCode(offer)).identity);
|
||
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('Paired device authenticated')));
|
||
await click(identityReceiver, 'Accept file');
|
||
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 paired connections persist across reload; fresh mutual proofs authenticate the paired device 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]) {
|
||
await forgetQuietly(forgottenSide);
|
||
assert.ok(await pairedKey(forgottenSide), 'Original tab still shows the stale paired device before connection setup');
|
||
|
||
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-device.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 pairedKey(forgottenSide), '', 'Connection setup re-reads the forgotten pairing');
|
||
assert.equal(await evaluate(forgottenSide, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Remember this device for Con 1'))?.querySelector('input')?.checked), true);
|
||
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 wait(forgottenSide, () => !!document.querySelector('.device-settings code'));
|
||
await click(identityReceiver, 'Accept file');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
await click(identitySender, 'Disconnect');
|
||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||
}
|
||
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and pairs the connection 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 paired device.');
|
||
|
||
const senderPaired = await pairedKey(identitySender);
|
||
await evaluate(identityReceiver, () => {
|
||
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'));
|
||
label?.querySelector<HTMLInputElement>('input')?.click();
|
||
});
|
||
await click(identityReceiver, 'Delete device identity');
|
||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity'));
|
||
await click(identityReceiver, 'Create device identity');
|
||
await wait(identityReceiver, () => !!document.querySelector('.device-settings code'));
|
||
await connect(identitySender, identityReceiver, 512, true);
|
||
await click(identityReceiver, 'Accept file');
|
||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('This device was not remembered.')));
|
||
assert.equal(await pairedKey(identitySender), senderPaired, 'Changed identity must not replace the paired device automatically');
|
||
console.log('PASS: replaced peer identity requires manual comparison and preserves the paired device.');
|
||
await click(identitySender, 'Disconnect');
|
||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||
const stale = await page();
|
||
await wait(stale, () => !!document.querySelector('.device-settings code'));
|
||
await click(stale, 'Forget device');
|
||
await wait(stale, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
|
||
await wait(identitySender, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
|
||
console.log('PASS: Forget device keeps the per-connection opt-in and reaches other tabs.');
|
||
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 evaluate(stale, () => [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'))?.querySelector<HTMLInputElement>('input')?.click());
|
||
await click(stale, 'Delete device identity');
|
||
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: { publicKey: 'broken' }, revision: 'broken' }, 'state'); tx.oncomplete = () => resolve(); }); db.close();
|
||
});
|
||
await call('Page.navigate', { url: origin }, stale);
|
||
await wait(stale, () => document.body.textContent?.includes('Invalid device identity'));
|
||
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 identity 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((await decodeCode(temporary)).identity, undefined);
|
||
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 });
|
||
}
|