AtlatestRepositorysigil-http3
sigil-http3 / tree / spikes / webrtcwindow.mjs
1
// Private Linux operator/controller. This never changes the firewall itself.2
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';3
import { BlockList, isIP } from 'node:net';4
import { hostname, networkInterfaces } from 'node:os';5
import { basename, dirname, join, resolve } from 'node:path';6
import { fileURLToPath } from 'node:url';7
import { identity, sameIdentity, stopRun } from '../../scripts/echo-lifecycle.mjs';8
import { preparePunchFirewall } from '../../scripts/punch-firewall.mjs';9
import { validateRendezvous } from '../../scripts/punch-prime.mjs';10
import { icePorts, startPeer } from './peer.mjs';12
const check = (value, message) => { if (!value) throw new Error(message); };13
const pause = ms => new Promise(done => setTimeout(done, ms));14
function json(path) {15
const info = lstatSync(path);16
check(info.isFile() && info.size <= 65536, 'Expected bounded JSON file');17
return JSON.parse(readFileSync(path, 'utf8'));18
}19
function privateJson(path, value, exclusive = false) {20
const target = exclusive ? path : path + '.next';21
writeFileSync(target, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: exclusive ? 'wx' : 'w' });22
if (!exclusive) renameSync(target, path);23
}24
function owned(path, directory = false) {25
const info = lstatSync(path);26
check((directory ? info.isDirectory() : info.isFile()) && info.uid === process.getuid() && !(info.mode & 0o077),27
'Expected private owned operator artifact');28
}29
function rootJson(path) {30
if (!existsSync(path)) return null;31
const info = lstatSync(path);32
check(info.isFile() && info.uid === 0 && !(info.mode & 0o022) && info.size <= 4096, 'Expected root-owned firewall proof');33
return json(path);34
}35
export function validOpenProof(opened, state, now = Date.now()) {36
return opened?.schema === 1 && opened.address === state.bindAddress &&37
opened.minPort === icePorts[0] && opened.maxPort === icePorts[1] &&38
opened.supervisorPID === state.supervisor.pid && opened.supervisorStart === state.supervisor.start &&39
opened.openedEpoch * 1000 >= Date.parse(state.startedAt) - 1000 &&40
opened.openedEpoch * 1000 <= now && opened.expiresEpoch * 1000 > now &&41
opened.expiresEpoch - opened.openedEpoch <= 4500;42
}43
function rootWindow(directory, state) {44
if (rootJson(join(directory, 'firewall/closed.json'))?.verifiedAbsent) return false;45
return validOpenProof(rootJson(join(directory, 'firewall/opened.json')), state);46
}47
export function validateArm(request, bindAddress, now = Date.now()) {48
check(request.schema === 1 && ['cellular', 'wifi'].includes(request.arm), 'Expected cellular or wifi arm');49
if (request.arm === 'cellular') return validateRendezvous(request.rendezvous, bindAddress, now);50
const value = request.rendezvous;51
const observed = Date.parse(value?.observedAt);52
check(value?.wifiOnly === true && isIP(value.phoneIPv6) === 6 && Number.isFinite(observed) &&53
observed <= now && now - observed <= 600000, 'Need a current Wi-Fi-only IPv6 observation');54
const home = new BlockList(); home.addSubnet(bindAddress, 64, 'ipv6');55
check(home.check(value.phoneIPv6, 'ipv6'), 'Wi-Fi arm must stay inside the home /64');56
return value.phoneIPv6;57
}58
export function requestArm(directory, rendezvousPath, arm) {59
owned(directory, true); owned(join(directory, 'state.json')); owned(rendezvousPath);60
const state = json(join(directory, 'state.json'));61
check(state.schema === 1 && state.kind === 'webrtc-phone' && state.phase === 'ready' &&62
Date.parse(state.expiresAt) > Date.now() && sameIdentity(state.supervisor, identity(state.supervisor.pid)), 'Controller not ready');63
check(rootWindow(directory, state), 'Fresh root allowance proof is not active');64
const request = { schema: 1, arm, rendezvous: json(rendezvousPath), requestedAt: new Date().toISOString() };65
validateArm(request, state.bindAddress);66
privateJson(join(directory, 'arm-request.json'), request, true);67
return { requested: true, arm, privateSessionPath: join(directory, 'session.json') };68
}70
async function run(checkOnly = false) {72
const job = basename(dirname(process.cwd()));73
check(/^[a-z0-9][a-z0-9-]{0,63}$/.test(job), 'Invalid workspace name');74
const bindAddress = networkInterfaces()[process.env.HTTP3_INTERFACE]?.find(a => a.family === 'IPv6' && /^[23]/.test(a.address) && !a.internal)?.address;75
check(bindAddress, 'No global IPv6 on configured physical interface');76
const directory = resolve('build/webrtc-phone'); mkdirSync(directory, { mode: 0o700 });77
const supervisor = identity(process.pid); check(supervisor?.uid === process.getuid(), 'Cannot admit exact controller');78
const seconds = checkOnly ? 30 : 3600;79
const state = { schema: 1, kind: 'webrtc-phone', phase: 'preparing', bindAddress, supervisor,80
startedAt: new Date().toISOString(), expiresAt: new Date(Date.now() + seconds * 1000).toISOString(),81
sourceRevision: process.env.HTTP3_SOURCE_REVISION, icePorts, signalPort: 47880 };82
preparePunchFirewall(join(directory, 'firewall'), { bindAddress, interfaceName: process.env.HTTP3_INTERFACE, supervisor,83
ruleComment: checkOnly ? 'sigil-http3-webrtc-phone-999' : 'sigil-' + job, webrtc: true });84
const save = () => privateJson(join(directory, 'state.json'), state);85
let app, stop = false, failure;86
const stopHandler = () => { stop = true; state.reason ??= 'operator-stop'; };87
process.on('SIGTERM', stopHandler); process.on('SIGINT', stopHandler);88
try {89
save();90
app = await startPeer({ scope: 'phone', bindAddress, directory: join(directory, 'peer'),91
lifetimeSeconds: seconds, signalPort: checkOnly ? 0 : 47880, admit: () => rootWindow(directory, state) });92
state.signalPort = app.server.address().port;93
state.phase = 'awaiting-firewall'; save();94
privateJson(join(directory, 'parameters.json'), { page: process.env.HTTP3_PAGE_URL ?? 'https://example.com/wt-spike/webrtc.html',95
token: 'issued privately only after fresh root proof and current phone rendezvous',96
expiresAt: state.expiresAt, signalPort: state.signalPort, icePorts,97
openCommand: `sudo bash ${directory}/firewall/open.sh`, closeCommand: `sudo bash ${directory}/firewall/close.sh` });98
console.log('RESULT webrtc-window-ready awaiting-root=true token-issued=false');99
while (!stop && Date.now() < Date.parse(state.expiresAt)) {100
if (app.fatal) throw app.fatal;101
if (!app.server.listening) { state.reason = 'peer-helper-ended'; break; }102
if (rootJson(join(directory, 'firewall/closed.json'))?.verifiedAbsent) { state.reason = 'root-closed'; break; }103
const active = rootWindow(directory, state);104
if (state.phase === 'awaiting-firewall' && active) { state.phase = 'ready'; save(); console.log('RESULT webrtc-root-ready'); }105
if (state.phase === 'ready' && !active) { state.reason = 'root-window-ended'; break; }106
const requestPath = join(directory, 'arm-request.json');107
if (existsSync(requestPath)) {108
owned(requestPath);109
const request = json(requestPath);110
check(active, 'Cannot arm without root proof');111
const address = validateArm(request, bindAddress);112
const session = app.armSession({ name: request.arm, address, homePrefix: request.arm === 'wifi' });113
privateJson(join(directory, 'session.json'), { ...session, arm: request.arm });114
renameSync(requestPath, join(directory, session.id + '-arm.json'));115
console.log('RESULT webrtc-session-armed arm=' + request.arm + ' private-url=build/webrtc-phone/session.json ttl=300');116
}117
await pause(100);118
}119
state.reason ??= 'controller-expired';120
} catch (error) { failure = error; }121
finally {122
try { if (app) state.peer = await app.close(); } catch (error) { failure ??= error; }123
process.off('SIGTERM', stopHandler); process.off('SIGINT', stopHandler);124
Object.assign(state, { phase: 'finished', endedAt: new Date().toISOString(), error: failure?.message,125
socketsClosed: state.peer?.socketsClosed === true }); save();126
console.log('RESULT webrtc-window-finished sockets-closed=' + state.socketsClosed);127
}128
if (failure) throw failure;129
}131
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {132
try {133
const [command, directory, rendezvous, arm] = process.argv.slice(2);134
if (command === 'run' || command === 'check-run') await run(command === 'check-run');135
else if (command === 'arm') console.log(JSON.stringify(requestArm(resolve(directory), resolve(rendezvous), arm)));136
else if (command === 'stop') console.log(JSON.stringify(stopRun(resolve(directory))));137
else throw new Error('Use run | arm DIR PRIVATE_RENDEZVOUS cellular|wifi | stop DIR');138
} catch (error) { console.error('RESULT webrtc-window-error ' + error.message); process.exitCode = 1; }139
}