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.
This commit is contained in:
1 parent
d198332c92
commit
752d0cf3af
16 files changed
+1352
-603
No files matched your search
@@ -0,0 +1,138 @@
|
||||
// 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 });
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// 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});
|
||||
}
|
||||
Reference in new issue
Block a user