// 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() { 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('',''); 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}); }