Commitf22ea49aRecorded19 Oct 2026Repositorysigil-http3

Prepare bounded WebRTC phone window and private arm admission

Changed
 scripts/phantom-webrtc-phone.sh        |  10 ++++++++++
 scripts/phantom-webrtc-window-check.sh |  10 ++++++++++
 scripts/punch-firewall.mjs             |  11 +++++++----
 spikes/webrtc/nginx-locations.conf     |  32 ++++++++++++++++++++++++++++++++
 spikes/webrtc/peer.mjs                 |   2 ++
 spikes/webrtc/window-check.mjs         |  73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 spikes/webrtc/window.mjs               | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 273 insertions(+), 4 deletions(-)
Diff
scripts/phantom-webrtc-phone.shadded
@@ -0,0 +1,10 @@
+1
#!/usr/bin/env bash
+2
set -euo pipefail
+3
cd "$(dirname "$0")/.."
+4
umask 077
+5
mkdir -p build
+6
trap 'printf "RESULT webrtc-phone rc=%s\n" "$?"' EXIT
+7
(cd spikes/webrtc && timeout --foreground 300 npm ci --ignore-scripts --no-audit --no-fund) > build/webrtc-phone-npm-ci.log 2>&1
+8
export HTTP3_SOURCE_REVISION
+9
HTTP3_SOURCE_REVISION=$(git rev-parse HEAD)
+10
node spikes/webrtc/window.mjs run
scripts/phantom-webrtc-window-check.shadded
@@ -0,0 +1,10 @@
+1
#!/usr/bin/env bash
+2
set -euo pipefail
+3
cd "$(dirname "$0")/.."
+4
umask 077
+5
mkdir -p build
+6
trap 'printf "RESULT webrtc-window-check rc=%s\n" "$?"' EXIT
+7
node --check spikes/webrtc/window.mjs
+8
node --check spikes/webrtc/window-check.mjs
+9
(cd spikes/webrtc && timeout --foreground 300 npm ci --ignore-scripts --no-audit --no-fund) > build/webrtc-window-npm-ci.log 2>&1
+10
node spikes/webrtc/window-check.mjs
scripts/punch-firewall.mjsmodified
@@ -6,12 +6,14 @@ import { execFileSync } from 'node:child_process';
6
const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";
7
8
export function preparePunchFirewall(directory, { bindAddress, interfaceName, supervisor,
−9
ruleComment = 'sigil-http3-example' }) {
+9
ruleComment = 'sigil-http3-example', webrtc = false }) {
10
if (isIP(bindAddress) !== 6 || !/^[23][0-9a-f:]+$/i.test(bindAddress) ||
11
!/^[-a-zA-Z0-9_.]+$/.test(interfaceName) || !Number.isInteger(supervisor?.pid) ||
12
!/^[0-9]+$/.test(supervisor.start) || !Number.isInteger(supervisor.uid) ||
−13
!/^sigil-http3-ipv6-punch-[0-9]{3}$/.test(ruleComment))
+13
!(webrtc ? /^sigil-http3-webrtc-phone-[0-9]{3}$/ : /^sigil-http3-ipv6-punch-[0-9]{3}$/).test(ruleComment))
14
throw new Error('Invalid exact firewall target/controller');
+15
const destination = webrtc ? '44000:44009' : '43443';
+16
const portProof = webrtc ? '"minPort":44000,"maxPort":44009' : '"port":43443';
17
mkdirSync(directory, { mode: 0o700 });
18
const common = `#!/usr/bin/env bash
19
set -euo pipefail
@@ -19,7 +21,7 @@ set -euo pipefail
21
umask 022
22
firewall=/gnu/store/c3fa94c62chbj42q905zfi33x7z7kr9m-iptables-1.8.11/sbin/ip6tables
23
directory=${quote(directory)}
−22
rule=(-i ${quote(interfaceName)} -d ${quote(bindAddress + '/128')} -p udp --dport 43443 -m comment --comment ${quote(ruleComment)} -j ACCEPT)
+24
rule=(-i ${quote(interfaceName)} -d ${quote(bindAddress + '/128')} -p udp --dport ${destination} -m comment --comment ${quote(ruleComment)} -j ACCEPT)
25
verify_close() {
26
local result
27
"$firewall" -w 5 -S INPUT >/dev/null
@@ -47,6 +49,7 @@ controller_alive() {
49
local stat_line rest
50
local -a fields
51
[[ -r /proc/${supervisor.pid}/stat ]] || return 1
+52
[[ $(stat -c %u /proc/${supervisor.pid}) == ${supervisor.uid} ]] || return 1
53
read -r stat_line < /proc/${supervisor.pid}/stat || return 1
54
rest=\${stat_line##*) }
55
read -r -a fields <<< "$rest"
@@ -68,7 +71,7 @@ installed=1
71
"$firewall" -w 5 -C INPUT "\${rule[@]}"
72
opened=$(date +%s)
73
expires=$(( opened + 4500 ))
−71
(set -C; printf '{"schema":1,"port":43443,"address":"${bindAddress}","supervisorPID":${supervisor.pid},"supervisorStart":"${supervisor.start}","openedEpoch":%s,"expiresEpoch":%s}\\n' "$opened" "$expires" > "$directory/opened.json")
+74
(set -C; printf '{"schema":1,${portProof},"address":"${bindAddress}","supervisorPID":${supervisor.pid},"supervisorStart":"${supervisor.start}","openedEpoch":%s,"expiresEpoch":%s}\\n' "$opened" "$expires" > "$directory/opened.json")
75
printf 'Punch allowance opened; automatic close at 75 minutes or recorded controller exit. Keep this foreground guard running.\\n'
76
while (( $(date +%s) < expires )) && controller_alive && [[ ! -e "$directory/closed.json" ]]; do sleep 1; done
77
`;
spikes/webrtc/nginx-locations.confadded
@@ -0,0 +1,32 @@
+1
# Add these locations to the HTTPS server for the configured page origin.
+2
location = /wt-spike/webrtc.html {
+3
root /var/www/htdocs;
+4
try_files $uri =404;
+5
access_log off;
+6
error_log /dev/null;
+7
add_header Cache-Control "no-store" always;
+8
add_header Referrer-Policy "no-referrer" always;
+9
}
+10
+11
location = /wt-spike/signal {
+12
access_log off;
+13
error_log /dev/null;
+14
client_max_body_size 72k;
+15
client_body_buffer_size 72k;
+16
proxy_http_version 1.1;
+17
proxy_pass http://127.0.0.1:47880;
+18
proxy_set_header Host $host;
+19
proxy_set_header Origin $http_origin;
+20
proxy_set_header Authorization $http_authorization;
+21
proxy_set_header Connection "";
+22
proxy_set_header X-Forwarded-For "";
+23
proxy_set_header X-Real-IP "";
+24
proxy_request_buffering off;
+25
proxy_buffering off;
+26
proxy_cache off;
+27
proxy_intercept_errors off;
+28
proxy_connect_timeout 2s;
+29
proxy_send_timeout 12s;
+30
proxy_read_timeout 12s;
+31
add_header Cache-Control "no-store" always;
+32
}
spikes/webrtc/peer.mjsmodified
@@ -135,6 +135,7 @@ export async function startPeer(config) {
135
if (request.url !== '/wt-spike/signal') { reply(404, {}); return; }
136
if (request.method !== 'POST') { reply(405, {}); return; }
137
if (request.headers.origin !== origin || request.headers['content-type'] !== 'application/json') { reply(403, {}); return; }
+138
if (config.admit && !config.admit()) { reply(503, {}); return; }
139
const supplied = request.headers.authorization?.match(/^Bearer ([0-9a-f]{64})$/)?.[1];
140
if (!arm || arm.used || arm.expiresAt < Date.now() || !supplied ||
141
!timingSafeEqual(Buffer.from(supplied, 'hex'), arm.token)) { reply(401, {}); return; }
@@ -144,6 +145,7 @@ export async function startPeer(config) {
145
try {
146
for await (const chunk of request) { bytes += chunk.length; check(bytes <= 73728, 'Request body exceeds limit'); chunks.push(chunk); }
147
const offer = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+148
check(!config.admit || config.admit(), 'Host allowance ended before offer admission');
149
check(offer.type === 'offer', 'Expected offer');
150
writeFileSync(join(directory, arm.id + '-offer.json'), JSON.stringify(offer), { mode: 0o600, flag: 'wx' });
151
const value = candidateInventory(offer.sdp, ip => arm.allow.check(ip, 'ipv6'));
spikes/webrtc/window-check.mjsadded
@@ -0,0 +1,73 @@
+1
// Exercise the real controller without opening a firewall or arming a peer.
+2
import assert from 'node:assert/strict';
+3
import { spawn, execFileSync } from 'node:child_process';
+4
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+5
import { join, resolve } from 'node:path';
+6
import { hostname } from 'node:os';
+7
import { identity, sameIdentity, stopRun } from '../../scripts/echo-lifecycle.mjs';
+8
import { requestArm, validOpenProof, validateArm } from './window.mjs';
+9
+10
const directory = resolve('build/webrtc-phone');
+11
const now = Date.now();
+12
const sample = { bindAddress: '2001:db8:1::1', supervisor: { pid: 123, start: '456' }, startedAt: new Date(now - 1000).toISOString() };
+13
const proof = { schema: 1, address: sample.bindAddress, minPort: 44000, maxPort: 44009,
+14
supervisorPID: 123, supervisorStart: '456', openedEpoch: Math.floor(now / 1000), expiresEpoch: Math.floor(now / 1000) + 4500 };
+15
assert.equal(validOpenProof(proof, sample, now), true);
+16
for (const patch of [{ maxPort: 44010 }, { minPort: 43443 }, { supervisorStart: '457' },
+17
{ address: '2001:db8:2::1' }, { expiresEpoch: Math.floor(now / 1000) - 1 }, { expiresEpoch: proof.expiresEpoch + 1 }])
+18
assert.equal(validOpenProof({ ...proof, ...patch }, sample, now), false);
+19
assert.throws(() => validateArm({ schema: 1, arm: 'cellular', rendezvous: {
+20
cellularOnly: true, phoneIPv6: '2a02:1388:1::2', observedAt: new Date(now - 600001).toISOString() } }, '2a14:6700:1::1', now));
+21
assert.throws(() => validateArm({ schema: 1, arm: 'cellular', rendezvous: {
+22
cellularOnly: true, phoneIPv6: '2a14:6700:1::2', observedAt: new Date(now).toISOString() } }, '2a14:6700:1::1', now));
+23
assert.equal(validateArm({ schema: 1, arm: 'wifi', rendezvous: {
+24
wifiOnly: true, phoneIPv6: '2a14:6700:1::2', observedAt: new Date(now).toISOString() } }, '2a14:6700:1::1', now), '2a14:6700:1::2');
+25
const child = spawn(process.execPath, ['spikes/webrtc/window.mjs', 'check-run'], { stdio: ['ignore', 'pipe', 'pipe'] });
+26
let output = '', closed = false;
+27
child.stdout.on('data', bytes => { output += bytes; }); child.stderr.on('data', bytes => { output += bytes; });
+28
const admitted = identity(child.pid);
+29
assert.equal(admitted?.uid, process.getuid());
+30
const done = new Promise((resolve, reject) => {
+31
child.once('error', reject); child.once('close', (code, signal) => { closed = true; resolve({ code, signal }); });
+32
});
+33
const deadline = setTimeout(() => {
+34
if (!closed && sameIdentity(admitted, identity(child.pid))) child.kill('SIGTERM');
+35
}, 15000);
+36
try {
+37
const until = Date.now() + 8000;
+38
let state;
+39
while (!closed && Date.now() < until) {
+40
if (existsSync(join(directory, 'state.json'))) {
+41
state = JSON.parse(readFileSync(join(directory, 'state.json'), 'utf8'));
+42
if (state.phase === 'awaiting-firewall') break;
+43
}
+44
await new Promise(resolve => setTimeout(resolve, 50));
+45
}
+46
assert.equal(state?.phase, 'awaiting-firewall', output);
+47
assert.equal(sameIdentity(admitted, state.supervisor), true);
+48
const script = readFileSync(join(directory, 'firewall/open.sh'), 'utf8');
+49
assert.ok(script.includes('--dport 44000:44009'));
+50
assert.ok(script.includes(state.bindAddress + '/128'));
+51
assert.ok(script.includes('sigil-http3-webrtc-phone-999'));
+52
for (const name of ['open.sh', 'close.sh']) execFileSync('bash', ['-n', join(directory, 'firewall', name)]);
+53
const response = await fetch(`http://127.0.0.1:${state.signalPort}/wt-spike/signal`, { method: 'POST',
+54
headers: { Origin: 'https://example.com', 'Content-Type': 'application/json' }, body: '{}' });
+55
assert.equal(response.status, 503);
+56
const rendezvous = join(directory, 'test-rendezvous.json');
+57
writeFileSync(rendezvous, JSON.stringify({ cellularOnly: true, phoneIPv6: '2a02:1388:1::2', observedAt: new Date().toISOString() }), { mode: 0o600 });
+58
assert.throws(() => requestArm(directory, rendezvous, 'cellular'), /Controller not ready/);
+59
assert.equal(existsSync(join(directory, 'session.json')), false);
+60
assert.equal(existsSync(join(directory, 'firewall/opened.json')), false);
+61
assert.equal(stopRun(directory).stopRequested, true);
+62
assert.deepEqual(await done, { code: 0, signal: null });
+63
const finished = JSON.parse(readFileSync(join(directory, 'state.json'), 'utf8'));
+64
assert.equal(finished.phase, 'finished'); assert.equal(finished.socketsClosed, true);
+65
assert.equal(finished.peer.counters.txChecks, 0); assert.equal(finished.peer.counters.udpReceived, 0);
+66
assert.equal(identity(child.pid), null);
+67
writeFileSync('build/webrtc-window-check.json', JSON.stringify({ passed: true, controllerReaped: true,
+68
noRootRule: true, noToken: true, noUdp: true, allowanceAbsentRefused: true, scriptsParsed: true }, null, 2) + '\n', { mode: 0o600 });
+69
console.log('RESULT webrtc-window-check passed=true controller-reaped=true root-opened=false udp=0 token=false');
+70
} finally {
+71
if (!closed && sameIdentity(admitted, identity(child.pid))) child.kill('SIGTERM');
+72
await done; clearTimeout(deadline);
+73
}
spikes/webrtc/window.mjsadded
@@ -0,0 +1,139 @@
+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';
+11
+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
}
+69
+70
async function run(checkOnly = false) {
+71
+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: '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
}
+130
+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
}