AtlatestRepositorysigil-http3
sigil-http3 / tree / scriptscontinuous-punch-window.mjs
1
// Bounded UDP experiment for an explicitly configured page.2
import { createHash, randomBytes } from 'node:crypto';3
import { isIP } from 'node:net';4
import { copyFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';5
import { hostname, networkInterfaces } from 'node:os';6
import { basename, dirname, join, resolve } from 'node:path';7
import { fileURLToPath } from 'node:url';8
import { identity, inspectPlan, runTest, sameIdentity, stopRun } from './echo-lifecycle.mjs';9
import { preparePunchFirewall } from './punch-firewall.mjs';10
import { punchPorts, validateRendezvous } from './punch-prime.mjs';12
const page = process.env.HTTP3_PAGE_URL ?? 'https://example.com/wt-spike/phone.html';13
const pause = ms => new Promise(done => setTimeout(done, ms));14
const digest = path => createHash('sha256').update(readFileSync(path)).digest('hex');15
function check(value, message) { if (!value) throw new Error(message); }16
function json(path) {17
check(lstatSync(path).size <= 65536, 'JSON receipt exceeds limit');18
return JSON.parse(readFileSync(path, 'utf8'));19
}20
function privateJson(path, value) {21
writeFileSync(path + '.next', JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });22
renameSync(path + '.next', path);23
}24
function rootJson(path) {25
if (!existsSync(path)) return null;26
const info = lstatSync(path);27
check(info.isFile() && info.uid === 0 && !(info.mode & 0o022) && info.size <= 4096, 'Expected root-owned firewall proof');28
return json(path);29
}30
export function requestPrime(directory, rendezvousPath, controlFailed) {31
const info = lstatSync(directory);32
check(info.isDirectory() && info.uid === process.getuid() && !(info.mode & 0o077), 'Expected private owned run');33
check(controlFailed, 'control confirmation and failed valid control are required');34
const state = json(join(directory, 'state.json'));35
check(state.phase === 'control-ready' && Date.parse(state.expiresAt) > Date.now(), 'Control not active');36
const rendezvous = json(rendezvousPath);37
validateRendezvous(rendezvous, state.bindAddress);38
writeFileSync(join(directory, 'prime-request.json'), JSON.stringify({ schema: 1, confirmedControlFailed: true,39
requestedAt: new Date().toISOString(), rendezvous }, null, 2) + '\n', { flag: 'wx', mode: 0o600 });40
return { requested: true, seconds: 180, ports: punchPorts, sameListeningSocket: true };41
}43
async function run() {45
const jobId = basename(dirname(process.cwd()));46
check(/^[a-z0-9][a-z0-9-]{0,63}$/.test(jobId), 'Invalid workspace name');47
const bindAddress = process.env.HTTP3_IPV6_ADDRESS;48
check(isIP(bindAddress) === 6 && /^[23][0-9a-f:]+$/i.test(bindAddress), 'Expected current global /128');49
check(networkInterfaces()[process.env.HTTP3_INTERFACE]?.some(a => a.family === 'IPv6' && a.address === bindAddress && !a.internal),50
'configured /128 not assigned on expected physical interface');51
const input = json('build/punch-input-proof.json'), receipt = json('build/browser/capabilities.json');52
const original = resolve('tools/interop/build/native/bin/http3-preflight');53
check(input.continuous && input.job === (process.env.HTTP3_INPUT_JOB ?? 'http3-example') && input.binarySha256 === digest(original) &&54
receipt.binarySha256 === input.binarySha256 && receipt.quicRevision === readFileSync('quic.rev', 'utf8').trim() &&55
receipt.spikeSdkRevision === readFileSync('spike-sdk.rev', 'utf8').trim(), 'Continuous binary provenance mismatch');56
check(['ready', 'bidirectionalEcho', 'unidirectionalEcho', 'datagramEcho', 'chromeReaped', 'serverReaped']57
.every(key => receipt[key] === true) && receipt.traceProbe?.newTuple && receipt.traceProbe?.dropRecorded &&58
receipt.traceProbe?.connectionStillOpen && receipt.phonePageChecks?.offlineGate && receipt.phonePageChecks?.onlineRecovery,59
'Fresh exact-certificate browser/trace/offline gate missing');60
const directory = resolve('build/phone-punch'), native = join(directory, 'native-punch');61
mkdirSync(directory, { mode: 0o700 }); mkdirSync(native, { mode: 0o700 });62
const certificateDirectory = join(directory, 'certificate'); mkdirSync(certificateDirectory, { mode: 0o700 });63
for (const name of ['cert.pem', 'cert.der', 'key.pem', 'private.raw', 'certificate.json']) {64
copyFileSync(join('build/browser', name), join(certificateDirectory, name));65
chmodSync(join(certificateDirectory, name), 0o600);66
}67
const binary = join(directory, 'echo-server'); copyFileSync(original, binary); chmodSync(binary, 0o700);68
privateJson(join(directory, 'interop.json'), receipt);69
const supervisor = identity(process.pid); check(supervisor?.uid === process.getuid(), 'Cannot admit controller');70
const lifetimeSeconds = 3600;71
const deadline = Date.now() + lifetimeSeconds * 1000;72
const state = { schema: 1, kind: 'continuous-ipv6-punch', phase: 'preparing', supervisor,73
bindAddress, port: 43443, startedAt: new Date().toISOString(), expiresAt: new Date(deadline).toISOString(),74
binarySha256: input.binarySha256, sourceRevision: process.env.HTTP3_SOURCE_REVISION, binarySourceRevision: input.sourceRevision };75
const statePath = join(directory, 'state.json'), firewall = join(directory, 'firewall');76
preparePunchFirewall(firewall, { bindAddress, interfaceName: process.env.HTTP3_INTERFACE, supervisor, ruleComment: 'sigil-' + jobId });77
const cancellation = new AbortController();78
const stop = () => cancellation.abort();79
process.on('SIGTERM', stop); process.on('SIGINT', stop);80
const timer = setTimeout(stop, lifetimeSeconds * 1000);81
const save = () => privateJson(statePath, state);82
function rootWindow() {83
if (rootJson(join(firewall, 'closed.json'))?.verifiedAbsent) return false;84
const opened = rootJson(join(firewall, 'opened.json'));85
return opened?.schema === 1 && opened.address === bindAddress && opened.port === 43443 &&86
opened.supervisorPID === supervisor.pid && opened.supervisorStart === supervisor.start &&87
opened.openedEpoch * 1000 >= Date.parse(state.startedAt) - 1000 && opened.expiresEpoch * 1000 > Date.now();88
}89
let serverDone, ended = false, failure;90
const previousPunchDirectory = process.env.HTTP3_PUNCH_DIRECTORY;91
const previousTestScope = process.env.HTTP3_PUNCH_TEST_LOOPBACK;92
try {93
save();94
const config = { schema: 1, testId: 'phone-continuous-' + jobId, expectedHost: hostname(), scope: 'ipv6-direct',95
bindAddress, port: 43443, binary, binarySha256: input.binarySha256, certificateDirectory,96
authority: `[${bindAddress}]:43443`, origins: [new URL(page).origin], interopReceipt: join(directory, 'interop.json'),97
runDirectory: join(directory, 'server'), lifetimeSeconds };98
const configPath = join(directory, 'config.json'); privateJson(configPath, config);99
const plan = inspectPlan(configPath); check(plan.ready, plan.blockers.join('; '));100
process.env.HTTP3_PUNCH_DIRECTORY = native;101
delete process.env.HTTP3_PUNCH_TEST_LOOPBACK;102
serverDone = runTest(configPath, { signal: cancellation.signal }).then(() => { ended = true; }, error => { ended = true; failure = error; });103
const readyUntil = Date.now() + 12000;104
while (!ended && !cancellation.signal.aborted && Date.now() < readyUntil) {105
const path = join(directory, 'server/state.json');106
if (existsSync(path) && json(path).phase === 'ready') { state.child = json(path).child; break; }107
await pause(50);108
}109
check(state.child && !ended && !cancellation.signal.aborted, 'Native control readiness failed');110
const phoneURL = page + '?' + new URLSearchParams({ host: bindAddress, port: '43443', hash: receipt.certificateSha256 });111
privateJson(join(directory, 'parameters.json'), { phoneURL, port: 43443, hash: receipt.certificateSha256,112
expiresAt: state.expiresAt, primePorts: punchPorts, primeSeconds: 180, maximumPrimePackets: 540,113
sameListeningSocket: true, openCommand: `sudo bash ${firewall}/open.sh`, closeCommand: `sudo bash ${firewall}/close.sh` });114
state.phase = 'awaiting-firewall'; save();115
console.log('RESULT continuous-control-listener-ready parameters=build/phone-punch/parameters.json awaiting-root-open');116
while (!ended && !cancellation.signal.aborted) {117
if (rootJson(join(firewall, 'closed.json'))?.verifiedAbsent) { state.reason = 'firewall-closed'; break; }118
if (state.phase === 'awaiting-firewall' && rootWindow()) {119
state.phase = 'control-ready'; state.controlReadyAt = new Date().toISOString(); save();120
console.log('RESULT continuous-control-ready no-prime=true');121
}122
if (state.phase !== 'awaiting-firewall' && !rootWindow()) { state.reason = 'firewall-window-ended'; break; }123
const requestPath = join(directory, 'prime-request.json');124
if (state.phase === 'control-ready' && existsSync(requestPath)) {125
const request = json(requestPath);126
check(request.schema === 1 && request.confirmedControlFailed, 'Missing control confirmation/control confirmation');127
const phone = validateRendezvous(request.rendezvous, bindAddress);128
check(rootWindow() && sameIdentity(state.child, identity(state.child.pid)), 'Root window/child identity changed');129
const log = readFileSync(join(directory, 'server/stdout.log'), 'utf8');130
check(!log.includes('event=udp-in') && !log.includes('HTTP3-AUTHENTICATED ') && !log.includes('event=trace-exhausted'),131
'Control has ingress; inspect rather than classifying/priming');132
privateJson(join(directory, 'control-result.json'), { failedOnPhoneConfirmed: true, ingress: 0,133
capturedAt: new Date().toISOString(), logSha256: digest(join(directory, 'server/stdout.log')), child: state.child });134
const nonce = randomBytes(16).toString('hex');135
writeFileSync(join(native, 'command.scm.next'), `(1 "${nonce}" "${phone}" 180)\n`, { flag: 'wx', mode: 0o600 });136
renameSync(join(native, 'command.scm.next'), join(native, 'command.scm'));137
state.phase = 'priming-starting'; state.primeNonce = nonce; state.primeRequestedAt = new Date().toISOString(); save();138
}139
if (state.phase === 'priming-starting') {140
check(Date.now() - Date.parse(state.primeRequestedAt) < 5000, 'Native prime acknowledgement deadline');141
const startedPath = join(native, 'started.json');142
if (existsSync(startedPath)) {143
const started = json(startedPath);144
const log = readFileSync(join(directory, 'server/stdout.log'), 'utf8');145
check(started.nonce === state.primeNonce && started.sourceHost === bindAddress && started.sourcePort === 43443 &&146
started.seconds === 180 && sameIdentity(state.child, identity(state.child.pid)), 'Native prime source/identity mismatch');147
if (/HTTP3-PUNCH .*event=send .*result=8/.test(log)) {148
state.phase = 'primed-ready'; state.primedReadyAt = new Date().toISOString();149
state.primingDeadline = new Date(Date.parse(state.primeRequestedAt) + 185000).toISOString(); save();150
console.log('RESULT continuous-PRIMED-READY same-listening-socket=true seconds<=180 ports=40000,40001,40002');151
}152
}153
}154
const finishedPath = join(native, 'finished.json');155
if (['priming-starting', 'primed-ready'].includes(state.phase) && existsSync(finishedPath)) {156
const finished = json(finishedPath);157
check(finished.nonce === state.primeNonce && finished.packets <= 540 && finished.elapsedMs <= 185000, 'Invalid native finish receipt');158
check(finished.reason === 'window-expired', 'Priming stopped early: ' + finished.reason);159
state.phase = 'priming-finished'; state.primeFinishedAt = new Date().toISOString(); save();160
console.log('RESULT continuous-priming-finished packets=' + finished.packets);161
}162
if (state.phase === 'primed-ready') check(Date.now() < Date.parse(state.primingDeadline), 'Native priming hard deadline exceeded');163
await pause(100);164
}165
if (failure) throw failure;166
} catch (error) { failure ??= error; }167
finally {168
clearTimeout(timer);169
writeFileSync(join(native, 'stop'), 'controller teardown\n', { mode: 0o600 });170
cancellation.abort();171
await serverDone;172
process.off('SIGTERM', stop); process.off('SIGINT', stop);173
if (previousPunchDirectory === undefined) delete process.env.HTTP3_PUNCH_DIRECTORY;174
else process.env.HTTP3_PUNCH_DIRECTORY = previousPunchDirectory;175
if (previousTestScope === undefined) delete process.env.HTTP3_PUNCH_TEST_LOOPBACK;176
else process.env.HTTP3_PUNCH_TEST_LOOPBACK = previousTestScope;177
const serverState = existsSync(join(directory, 'server/state.json')) ? json(join(directory, 'server/state.json')) : null;178
Object.assign(state, { phase: 'finished', endedAt: new Date().toISOString(), childReaped: serverState?.childReaped === true,179
error: failure?.message }); save();180
console.log('RESULT continuous-window-finished child-reaped=' + state.childReaped);181
}182
if (failure) throw failure;183
}184
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {185
try {186
const [command, directory, rendezvous, confirmation] = process.argv.slice(2);187
if (command === 'run') await run();188
else if (command === 'stop') console.log(JSON.stringify(stopRun(resolve(directory))));189
else if (command === 'prime') console.log(JSON.stringify(requestPrime(resolve(directory), resolve(rendezvous), confirmation === '--control-failed')));190
else throw new Error('Usage: continuous-punch-window.mjs run | stop DIR | prime DIR RENDEZVOUS --control-failed');191
} catch (error) { console.error('RESULT continuous-punch-error ' + error.message); process.exitCode = 1; }192
}