Files
HellCon/scripts/browser-check.mjs
T
Schluffe 752d0cf3af fix: harden WebRTC transfers for v0.0.1
Require mutual fingerprint confirmation before sharing metadata or files.
Validate incoming messages, bound buffering, and confirm receipt before
reporting success. Add direct-to-disk saving and explicit TURN opt-in.

Fix reset and retry handling, clean up cancelled connections, and preserve
completed Firefox downloads when the sender disconnects.

Update dependencies, clarify security assumptions, and add protocol and
cross-browser regression tests. Set version 0.0.1 and document the release
in CHANGELOG.md, linked from the README.

BREAKING CHANGE: both peers must use signaling and transfer protocol v2;
older connection codes are no longer accepted.
2026-10-09 12:11:14 +02:00

139 lines
9.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
const server = createServer(async (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);
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 })); })()`);
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);
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);
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')");
}
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.');
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 rm(profile, { recursive: true, force: true, maxRetries: 3 });
}