Files
HellCon/scripts/compare-ice.mjs
T
2026-10-16 12:01:43 +02:00

88 lines
5.2 KiB
JavaScript

import { createServer } from 'node:http';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { execFileSync, spawn } from 'node:child_process';
import { stripTypeScriptTypes } from 'node:module';
import { createSocket } from 'node:dgram';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
// A controlled ICE experiment, not a cross-device transfer test. Reads the
// original signaling helpers from git without checking out or editing files.
const root = fileURLToPath(new URL('..', import.meta.url));
const legacy = execFileSync('git', ['show', 'd198332:src/lib/webrtc.js'], { cwd: root, encoding: 'utf8' });
const current = stripTypeScriptTypes(await readFile(root + '/src/lib/webrtc.ts', 'utf8'));
const validation = stripTypeScriptTypes(await readFile(root + '/src/lib/validation.ts', 'utf8'));
const udp = createSocket('udp4');
await new Promise(resolve => udp.bind(0, '127.0.0.1', resolve));
const stunUrl = process.argv.includes('--slow-stun') ? 'stun:127.0.0.1:' + udp.address().port : null;
const rewritePorts = !process.argv.includes('--normal-candidates');
const browserCode = String.raw`
import * as old from '/old.js';
import * as current from '/current.js';
async function run(mode) {
const api = mode === 'original' ? old : current;
const start = performance.now();
const events = [];
const log = (event) => events.push([Math.round(performance.now()-start),event]);
const {stunUrl,rewritePorts} = await (await fetch('/config')).json();
const a = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
const b = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
if(mode !== 'original') { a.setConfiguration(current.iceConfiguration({stunUrl})); b.setConfiguration(current.iceConfiguration({stunUrl})); }
let received = false;
for(const [role,pc] of [['sender',a],['receiver',b]]) {
pc.oniceconnectionstatechange = () => log(role + ' ICE ' + pc.iceConnectionState);
pc.onconnectionstatechange = () => {
log(role + ' PC ' + pc.connectionState);
if(mode === 'current' && pc.connectionState === 'failed') pc.close();
};
}
const dc = a.createDataChannel('file');
dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); };
b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; };
try {
const offer = await api.createOfferCode(a);
let sdp = api.decodeSignal(offer);
// Deliberately unusable advertised ports: only sender-initiated checks
// after the answer can discover the real sender. No host firewall changes.
if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{
if(!l.startsWith('a=candidate:'))return l;
const fields=l.split(' '); fields[5]='9'; return fields.join(' ');
}).join('\r\n');
log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates'));
const answer = await api.createAnswerCode(b, api.encodeSignal(sdp));
log('answer ready');
await new Promise(r=>setTimeout(r,20000));
log('apply answer');
await api.acceptAnswerCode(a,answer);
await new Promise(r=>setTimeout(r,12000));
return {mode,received,events};
} catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; }
finally {a.close();b.close();}
}
const results = await Promise.all(['original','current','current-keep'].map(run));
await fetch('/result',{method:'POST',body:JSON.stringify(results)});
`;
let done;
const finished = new Promise(resolve=>done=resolve);
const server = createServer(async(req,res)=>{
if(req.url === '/config') { res.setHeader('Content-Type','application/json');res.end(JSON.stringify({stunUrl,rewritePorts}));return; }
if(req.url === '/result') {let body=''; for await(const part of req)body+=part; console.log(body);res.end('ok');done();return;}
res.setHeader('Content-Type',req.url==='/'?'text/html':'text/javascript');
res.end(({'/':'<script type="module" src="/run.js"></script>','/old.js':legacy,'/current.js':current,'/validation.ts':validation,'/run.js':browserCode})[req.url] || '');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const profile=await mkdtemp(join(tmpdir(), 'hellcon-ice-comparison-'));
const name=process.argv[2] || 'firefox';
const url='http://127.0.0.1:'+server.address().port;
const args=name==='firefox'?['--headless','--no-remote','--profile',profile,url]:['--headless','--no-sandbox','--disable-gpu','--no-first-run','--user-data-dir='+profile,url];
const child=spawn('/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});
child.on('error',()=>{console.error('Could not launch browser');process.exitCode=1;done();});
let errors='';child.stderr.on('data',chunk=>errors+=chunk);
const timer=setTimeout(()=>{console.log('Comparison timed out');process.exitCode=1;done();},85000);
try {await finished;} finally {
clearTimeout(timer);child.kill();
if(child.pid && child.exitCode===null && child.signalCode===null) await new Promise(resolve=>child.once('exit',resolve));
server.closeAllConnections();server.close();udp.close();
await rm(profile,{recursive:true,force:true,maxRetries:3});
}