Translate everything to typescript

This commit is contained in:
Schluffe committed 2026-10-09 14:17:36 +02:00
1 parent c3ca3e1752
commit e9818aaeda
27 files changed
+901 -552

No files matched your search

-175
View File
@@ -1,175 +0,0 @@
// Dependency-free Chromium integration check. Run after `bun run build`.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
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 provider = process.argv.includes('--default-network') ? 'google' : 'none';
const turn = process.argv.includes('--turn');
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
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 = pathname.startsWith('/src/lib/') ? root : join(root, 'dist');
const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname));
if (!path.startsWith(base + '/')) throw new Error('Invalid path');
const types = { '.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 origin = `http://127.0.0.1:${server.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'] });
let stderr = '', nextId = 0, buffer = '';
const pending = new Map();
const browserErrors = [];
browser.stderr.on('data', data => { stderr += data; });
browser.stdio[3].on('error', () => {}); browser.stdio[4].on('error', () => {});
browser.stdio[4].on('data', data => {
buffer += data;
let end;
while ((end = buffer.indexOf('\0')) !== -1) {
const message = 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, params = {}, sessionId) {
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); });
browser.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
});
}
async function evaluate(session, expression) {
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
}
async function wait(session, expression) {
return evaluate(session, `(async () => { for (let n = 0; n < 1800; n++) { if (${expression}) return true; await new Promise(r => setTimeout(r, 20)); } throw new Error('UI condition timed out: ' + ${JSON.stringify(expression)} + '\\n' + document.body.innerText); })()`);
}
async function page() {
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);
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `
window.__peers = [];
const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC {
constructor(config) { super({ ...config, iceTransportPolicy: 'relay' }); window.__peers.push(this); }
setConfiguration(config) {
const iceServers = config.iceServers.filter(s => s.username).map(s => ({ ...s,
urls: (Array.isArray(s.urls) ? s.urls : [s.urls]).filter(url => url.endsWith('transport=${transport}'))
}));
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
}
};
` }, sessionId);
await call('Page.navigate', { url: origin }, sessionId);
for (let n = 0; n < 100; n++) {
try { if (await evaluate(sessionId, `location.origin === ${JSON.stringify(origin)} && document.readyState === 'complete'`)) break; }
catch (err) { if (!err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20));
}
await wait(sessionId, "!!document.querySelector('#stun-provider')");
return sessionId;
}
const click = (session, label) => evaluate(session, `(() => { const b = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === ${JSON.stringify(label)}); if (!b || b.disabled) throw new Error('Unavailable button: ' + ${JSON.stringify(label)}); b.click(); })()`);
const input = (session, selector, value) => evaluate(session, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); el.value = ${JSON.stringify(value)}; el.dispatchEvent(new Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })); })()`);
const enableTurn = session => evaluate(session, `(() => { const checkbox = document.querySelector('.checkbox input'); if (!checkbox.checked) checkbox.click(); })()`);
async function connect(sender, receiver, size) {
await evaluate(sender, `(() => { const input = document.querySelector('#file-input'); const files = new DataTransfer(); files.items.add(new File([new Uint8Array(${size}).fill(123)], 'browser-test.bin')); input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true })); })()`);
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, "document.querySelector('#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, "document.querySelector('#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, "document.querySelector('#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, "document.querySelector('#output-code')?.value"), offer);
assert.equal(await evaluate(sender, "document.querySelector('#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, `(async () => {
for (let attempt = 0; attempt < 50; attempt++) {
const stats = await window.__peers.at(-1).getStats();
const transport = [...stats.values()].find(s => s.type === 'transport' && s.selectedCandidatePairId);
const pair = transport && stats.get(transport.selectedCandidatePairId);
if (pair) return [stats.get(pair.localCandidateId)?.candidateType, stats.get(pair.remoteCandidateId)?.candidateType];
await new Promise(resolve => setTimeout(resolve, 100));
}
throw new Error('No selected ICE candidate pair in WebRTC statistics');
})()`);
assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates');
}
}
}
try {
const sender = await page(), receiver = await page();
await click(receiver, 'Receive');
assert.equal(await evaluate(sender, "document.querySelector('.checkbox input').checked"), false);
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, "document.querySelector('[role=status]').textContent.includes('confirmed the complete file')");
const data = await evaluate(receiver, `(async () => { const response = await fetch(document.querySelector('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 });
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.');
await click(sender, 'Reset'); await click(receiver, 'Reset');
assert.equal(await evaluate(sender, "document.querySelector('[role=status]').textContent"), 'Choose a file to start.');
assert.equal(await evaluate(receiver, "document.querySelector('[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, `window.__aborted = false; window.showSaveFilePicker = async () => ({ createWritable: async () => ({ write() { return new Promise(resolve => { window.__releaseWrite = resolve; }); }, async close() {}, async abort() { window.__aborted = true; window.__releaseWrite?.(); } }) });`);
await connect(sender, receiver, 2 * 1024 * 1024);
await click(receiver, 'Choose destination & receive to disk');
await wait(receiver, '!!window.__releaseWrite');
await click(sender, 'Receive');
await wait(receiver, 'window.__aborted === true');
assert.equal(await evaluate(receiver, "!!document.querySelector('a.download')"), false);
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
await click(sender, 'Send'); await click(receiver, 'Reset');
await connect(sender, receiver, 2048);
await click(receiver, 'Receive in memory (up to 64 MiB)');
await wait(sender, "document.querySelector('[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) resolve(); else browser.once('exit', resolve); });
await new Promise(resolve => server.close(resolve));
await vite?.close();
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
}
+189
View File
@@ -0,0 +1,189 @@
// 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, readFile, rm } from 'node:fs/promises';
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 provider = process.argv.includes('--default-network') ? 'google' : 'none';
const turn = process.argv.includes('--turn');
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
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 {
'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() {
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 (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url: origin }, sessionId);
for (let n = 0; n < 100; n++) {
try { if (await evaluate(sessionId, (expected: string) => location.origin === expected && document.readyState === 'complete', origin)) break; }
catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20));
}
await wait(sessionId, () => !!document.querySelector('#stun-provider'));
return sessionId;
}
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) {
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);
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 {
const sender = await page(), receiver = await page();
await click(receiver, 'Receive');
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.checkbox input').checked), false);
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
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 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 });
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.');
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 click(sender, 'Receive');
await wait(receiver, () => window.__hellcon.aborted);
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
await click(sender, 'Send'); 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<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 });
}
+103
View File
@@ -0,0 +1,103 @@
// These functions are serialized into isolated browser pages by the checks.
// Keep their dependencies inside the function or on window.__hellcon.
export function installBrowserContext() {
function element<E extends Element>(selector: string): E {
const value = document.querySelector<E>(selector);
if (!value) throw new Error(`Missing element: ${selector}`);
return value;
}
const context = {
element,
peers: [] as RTCPeerConnection[],
aborted: false,
releaseWrite: undefined as (() => void) | undefined,
click(label: string) {
const button = [...document.querySelectorAll('button')].find(button => button.textContent?.trim() === label);
if (!button || button.disabled) throw new Error(`Unavailable button: ${label}`);
button.click();
},
input(selector: string, value: string) {
const input = element<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(selector);
input.value = value;
input.dispatchEvent(new Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
},
chooseFile(size: number, name: string) {
const input = element<HTMLInputElement>('#file-input');
const files = new DataTransfer();
files.items.add(new File([new Uint8Array(size).fill(123)], name));
input.files = files.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
},
async wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>> {
const deadline = Date.now() + 36000;
while (Date.now() < deadline) {
const value = await check();
if (value) return value;
await new Promise<void>(resolve => setTimeout(resolve, 20));
}
throw new Error('UI condition timed out: ' + document.body.innerText);
},
};
window.__hellcon = context;
}
declare global {
interface Window {
__hellcon: {
element<E extends Element>(selector: string): E;
peers: RTCPeerConnection[];
aborted: boolean;
releaseWrite?: () => void;
click(label: string): void;
input(selector: string, value: string): void;
chooseFile(size: number, name: string): void;
wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>>;
};
}
}
export function forceRelay(transport: 'udp' | 'tcp') {
const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC {
constructor(config?: RTCConfiguration) {
super({ ...config, iceTransportPolicy: 'relay' });
window.__hellcon.peers.push(this);
}
override setConfiguration(config: RTCConfiguration) {
const iceServers = (config.iceServers ?? []).filter(server => server.username).map(server => ({
...server,
urls: (Array.isArray(server.urls) ? server.urls : [server.urls]).filter(url => url.endsWith(`transport=${transport}`)),
}));
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
}
};
}
export async function relayCandidateTypes() {
for (let attempt = 0; attempt < 50; attempt++) {
const pc = window.__hellcon.peers.at(-1);
if (!pc) throw new Error('No peer connection');
const stats = await pc.getStats();
const transport = [...stats.values()].find((entry: RTCStats) => entry.type === 'transport') as RTCTransportStats | undefined;
const pair = transport?.selectedCandidatePairId ? stats.get(transport.selectedCandidatePairId) as RTCIceCandidatePairStats | undefined : undefined;
if (pair) {
const local = stats.get(pair.localCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
const remote = stats.get(pair.remoteCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
return [local?.candidateType, remote?.candidateType];
}
await new Promise<void>(resolve => setTimeout(resolve, 100));
}
throw new Error('No selected ICE candidate pair in WebRTC statistics');
}
export function simulateSlowDisk() {
window.__hellcon.aborted = false;
// Only the methods used by the app are implemented by this browser test double.
window.showSaveFilePicker = async () => ({
createWritable: async () => ({
write() { return new Promise<void>(resolve => { window.__hellcon.releaseWrite = resolve; }); },
async close() {},
async abort() { window.__hellcon.aborted = true; window.__hellcon.releaseWrite?.(); },
}),
});
}
-117
View File
@@ -1,117 +0,0 @@
// Exercises the built Vue app in separate Brave and Firefox processes.
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const state = {};
const profiles = [];
const children = [];
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
const reversed = process.argv.includes('--reverse');
const driver = `
const role = new URL(location.href).searchParams.get('role');
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
const post = async (key, value) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
const get = async key => (await fetch('/.test/' + key)).json();
const wait = async fn => { const deadline=Date.now()+36000; while(Date.now()<deadline){ const value = await fn(); if(value) return value; const error=document.querySelector('[role=alert]'); if(error) throw new Error(error.textContent); await pause(20); } throw new Error('Timed out: '+document.querySelector('[role=status]')?.textContent); };
const click = text => { const button=[...document.querySelectorAll('button')].find(b=>b.textContent.trim()===text); if(!button || button.disabled)throw new Error('Unavailable: '+text); button.click(); };
const input = (selector,value) => { const el=document.querySelector(selector); el.value=value; el.dispatchEvent(new Event(el.tagName==='SELECT'?'change':'input',{bubbles:true})); };
const stage = async text => post(role+'Stage', text);
const peers=[]; const NativePC=window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC { constructor(...args){super(...args);peers.push(this);} };
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
try {
await wait(()=>document.querySelector('#stun-provider'));
if(role==='receiver'){click('Receive');await pause(20);}
if(role==='sender'){
const files=new DataTransfer();files.items.add(new File([new Uint8Array(2*1024*1024+7).fill(123)],'cross-browser.bin'));
const el=document.querySelector('#file-input');el.files=files.files;el.dispatchEvent(new Event('change',{bubbles:true}));await pause(20);
}
input('#stun-provider',${JSON.stringify(provider)});await pause(20);
if(role==='sender'){
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
await post('offer',document.querySelector('#output-code').value);
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
}else{
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
await post('answer',document.querySelector('#output-code').value);
}
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
await post(role+'Fingerprints',fps);
const other=await wait(()=>get((role==='sender'?'receiver':'sender')+'Fingerprints'));
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
click('Both fingerprints match — confirm');
if(role==='receiver'){
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
await stage('receiving');await wait(()=>document.querySelector('a.download'));
await wait(()=>get('senderResult'));
await pause(250);
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
await stage('checking downloaded bytes');
const bytes=new Uint8Array(await (await fetch(document.querySelector('a.download').href)).arrayBuffer());
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
}else{
await stage('waiting for receipt');await wait(()=>document.querySelector('[role=status]').textContent.includes('confirmed the complete file'));
}
await post(role+'Result',{ok:true});
}catch(error){
await post(role+'Result',{ok:false,error:error.message,peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
}
`;
let finish;
const result = new Promise(resolve => { finish = resolve; });
const server = createServer(async (req,res) => {
try {
const pathname=new URL(req.url,'http://localhost').pathname;
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
if(pathname.startsWith('/.test/')){
const key=pathname.slice('/.test/'.length);
if(req.method==='POST'){
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
const previous=state[key];
state[key]=JSON.parse(body);
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
if(key.endsWith('Result')){
console.log(key+': '+JSON.stringify(state[key]));
if(!state[key].ok||(state.senderResult&&state.receiverResult))finish();
}
}
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
}
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
let body=await readFile(path);
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
res.setHeader('Content-Type',({'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'})[extname(path)]||'application/octet-stream');res.end(body);
}catch{res.statusCode=404;res.end();}
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const origin='http://127.0.0.1:'+server.address().port;
let timer;
try{
for(const name of ['brave','firefox']){
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
const role=(name==='brave')!==reversed?'sender':'receiver';
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
child.on('error',err=>{console.error(name,err.message);finish();});
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
}
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
await result;
if(!state.senderResult?.ok||!state.receiverResult?.ok)process.exitCode=1;
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
}finally{
clearTimeout(timer);
for(const child of children)child.kill();
await Promise.all(children.map(child=>new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit',resolve);})));
server.closeAllConnections();await new Promise(resolve=>server.close(resolve));
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
}
+72
View File
@@ -0,0 +1,72 @@
// Exercises the built Vue app in separate Brave and Firefox processes.
import { installBrowserContext } from './browser-context.ts';
import { crossBrowserDriver } from './cross-browser-driver.ts';
import { isRecord } from '../src/lib/validation.ts';
import { createServer } from 'node:http';
import { spawn, type ChildProcess } from 'node:child_process';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';
const types: Record<string, string> = {'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'};
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const state: Record<string, unknown> = {};
const profiles: string[] = [];
const children: ChildProcess[] = [];
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
const reversed = process.argv.includes('--reverse');
const driver = `(${installBrowserContext.toString()})(); (${crossBrowserDriver.toString()})(${JSON.stringify(provider)});`;
let finish: () => void = () => {};
const result = new Promise<void>(resolve => { finish = resolve; });
const server = createServer(async (req,res) => {
try {
const pathname=new URL(req.url ?? '/','http://localhost').pathname;
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
if(pathname.startsWith('/.test/')){
const key=pathname.slice('/.test/'.length);
if(req.method==='POST'){
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
const previous=state[key];
state[key]=JSON.parse(body);
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
if(key.endsWith('Result')){
console.log(key+': '+JSON.stringify(state[key]));
if(!isRecord(state[key]) || !state[key].ok ||(state.senderResult&&state.receiverResult))finish();
}
}
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
}
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
let body: string | Buffer = await readFile(path);
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
res.setHeader('Content-Type',types[extname(path)]||'application/octet-stream');res.end(body);
}catch{res.statusCode=404;res.end();}
});
await new Promise<void>(resolve=>server.listen(0,'127.0.0.1',resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Missing server address');
const origin='http://127.0.0.1:'+address.port;
let timer: ReturnType<typeof setTimeout> | undefined;
try{
for(const name of ['brave','firefox']){
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
const role=(name==='brave')!==reversed?'sender':'receiver';
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
child.on('error',err=>{console.error(name,err.message);finish();});
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
}
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
await result;
if(!isRecord(state.senderResult) || !state.senderResult.ok || !isRecord(state.receiverResult) || !state.receiverResult.ok)process.exitCode=1;
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
}finally{
clearTimeout(timer);
for(const child of children)child.kill();
await Promise.all(children.map(child=>new Promise<void>(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit', () => resolve());})));
server.closeAllConnections();await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
}
+61
View File
@@ -0,0 +1,61 @@
import type {} from './browser-context.ts';
interface Exchange {
offer: string;
answer: string;
senderFingerprints: string[];
receiverFingerprints: string[];
senderResult: { ok: boolean };
}
// Serialized by the runner; all runtime dependencies live in this function or window.
export async function crossBrowserDriver(provider: string) {
const role = new URL(location.href).searchParams.get('role');
if (role !== 'sender' && role !== 'receiver') throw new Error('Invalid role');
const { click, input, wait, element } = window.__hellcon;
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
const post = async (key: string, value: unknown) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
const get = async <K extends keyof Exchange>(key: K): Promise<Exchange[K] | null> => (await fetch('/.test/' + key)).json();
const stage = async (text: string) => post(role+'Stage', text);
const peers: RTCPeerConnection[] = []; const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC { constructor(config?: RTCConfiguration) { super(config); peers.push(this); } };
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
try {
await wait(()=>document.querySelector('#stun-provider'));
if(role==='receiver'){click('Receive');await pause(20);}
if(role==='sender'){
window.__hellcon.chooseFile(2*1024*1024+7, 'cross-browser.bin'); await pause(20);
}
input('#stun-provider',provider);await pause(20);
if(role==='sender'){
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
await post('offer',element<HTMLTextAreaElement>('#output-code').value);
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
}else{
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
await post('answer',element<HTMLTextAreaElement>('#output-code').value);
}
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
await post(role+'Fingerprints',fps);
const other=await wait(()=>get(role === 'sender' ? 'receiverFingerprints' : 'senderFingerprints'));
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
click('Both fingerprints match — confirm');
if(role==='receiver'){
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
await stage('receiving');await wait(()=>document.querySelector('a.download'));
await wait(()=>get('senderResult'));
await pause(250);
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
await stage('checking downloaded bytes');
const bytes=new Uint8Array(await (await fetch(element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
}else{
await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file'));
}
await post(role+'Result',{ok:true});
}catch(error){
await post(role+'Result',{ok:false,error:error instanceof Error ? error.message : String(error),peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
}
}
@@ -7,6 +7,6 @@ try {
{ flag: 'wx', mode: 0o600 });
console.log('Created .env.development with a private development TURN secret.');
} catch (error) {
if (error.code !== 'EEXIST') throw error;
if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
console.log('.env.development already exists; left unchanged. See .env.example for required settings.');
}