AtlatestRepositorysigil-http3

sigil-http3 / tree / scriptspunch-window.mjs

1// operator-configured, manual-rendezvous two-arm IPv6 experiment. No router writes.
2import { createHash } from 'node:crypto';
3import { createServer, isIP } from 'node:net';
4import { copyFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
5import { hostname, networkInterfaces } from 'node:os';
6import { join, resolve } from 'node:path';
7import { fileURLToPath } from 'node:url';
8import { identity, inspectPlan, runTest, stopRun } from './echo-lifecycle.mjs';
9import { startPhonePage } from './phone-page-host.mjs';
10import { preparePunchFirewall } from './punch-firewall.mjs';
11import { primeSocket, punchPorts, validateRendezvous } from './punch-prime.mjs';
13const pause = ms => new Promise(done => setTimeout(done, ms));
14const digest = path => createHash('sha256').update(readFileSync(path)).digest('hex');
15function check(value, message) { if (!value) throw new Error(message); }
16function json(path) { check(lstatSync(path).size <= 65536, 'JSON receipt exceeds limit'); return JSON.parse(readFileSync(path, 'utf8')); }
17function privateJson(path, value) {
18 writeFileSync(path + '.next', JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
19 renameSync(path + '.next', path);
21function privateDirectory(path) {
22 const info = lstatSync(path);
23 check(info.isDirectory() && info.uid === process.getuid() && (info.mode & 0o077) === 0, 'Expected owned private run directory');
25function rootJson(path) {
26 if (!existsSync(path)) return null;
27 const info = lstatSync(path);
28 check(info.isFile() && info.uid === 0 && (info.mode & 0o022) === 0 && info.size <= 4096, 'Expected root-owned bounded firewall receipt');
29 return json(path);
31async function pagePort() {
32 const server = createServer();
33 await new Promise((done, reject) => { server.once('error', reject); server.listen(0, (process.env.HTTP3_IPV4_ADDRESS ?? '127.0.0.1'), done); });
34 const port = server.address().port;
35 await new Promise(done => server.close(done));
36 return port;
39export function requestPrime(directory, rendezvousPath, controlFailed) {
40 check(controlFailed, 'Explicit failed no-prime control confirmation is required');
41 privateDirectory(directory);
42 const state = json(join(directory, 'state.json'));
43 check(state.phase === 'control-ready' && Date.parse(state.expiresAt) > Date.now(), 'Control is not ready/active');
44 const rendezvous = json(rendezvousPath);
45 validateRendezvous(rendezvous, state.bindAddress);
46 writeFileSync(join(directory, 'prime-request.json'), JSON.stringify({ schema: 1, action: 'prime',
47 confirmedControlFailed: true, requestedAt: new Date().toISOString(), rendezvous }, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
48 return { requested: true, ports: punchPorts, packets: 6 };
51async function run() {
53 const bindAddress = process.env.HTTP3_IPV6_ADDRESS;
54 check(isIP(bindAddress) === 6 && /^[23]/i.test(bindAddress), 'Choose configured global IPv6');
55 const device = Object.entries(networkInterfaces()).find(([, addresses]) => addresses?.some(address =>
56 address.family === 'IPv6' && address.address === bindAddress && !address.internal));
57 check(device && device[0] === process.env.HTTP3_INTERFACE, 'configured /128 is not assigned on the expected physical interface');
58 const input = json('build/punch-input-proof.json');
59 const receipt = json('build/browser/capabilities.json');
60 const originalBinary = resolve('tools/interop/build/native/bin/http3-preflight');
61 check(input.job === (process.env.HTTP3_INPUT_JOB ?? 'http3-example') && input.binarySha256 === digest(originalBinary) &&
62 receipt.binarySha256 === input.binarySha256 && receipt.quicRevision === readFileSync('quic.rev', 'utf8').trim() &&
63 receipt.spikeSdkRevision === readFileSync('spike-sdk.rev', 'utf8').trim(), 'Reused traced artifact proof mismatch');
64 check(['ready', 'bidirectionalEcho', 'unidirectionalEcho', 'datagramEcho', 'chromeReaped', 'serverReaped'].every(key => receipt[key] === true) &&
65 receipt.traceProbe?.newTuple && receipt.traceProbe?.dropRecorded && receipt.traceProbe?.connectionStillOpen,
66 'Fresh certificate/browser trace gate missing');
67 const directory = resolve('build/phone-punch');
68 mkdirSync(directory, { mode: 0o700 });
69 const certificateDirectory = join(directory, 'certificate');
70 mkdirSync(certificateDirectory, { mode: 0o700 });
71 for (const file of ['cert.pem', 'cert.der', 'key.pem', 'private.raw', 'certificate.json']) {
72 copyFileSync(resolve('build/browser', file), join(certificateDirectory, file));
73 chmodSync(join(certificateDirectory, file), 0o600);
74 }
75 const binary = join(directory, 'echo-server');
76 copyFileSync(originalBinary, binary); chmodSync(binary, 0o700);
77 privateJson(join(directory, 'interop.json'), receipt);
78 const supervisor = identity(process.pid);
79 check(supervisor && supervisor.uid === process.getuid(), 'Cannot admit punch controller');
80 const deadline = Date.now() + 3600000;
81 const state = { schema: 1, kind: 'phone-ipv6-punch', phase: 'preparing', supervisor, bindAddress, port: 43443,
82 startedAt: new Date().toISOString(), expiresAt: new Date(deadline).toISOString(), binarySha256: input.binarySha256,
83 sourceRevision: process.env.HTTP3_SOURCE_REVISION, tracedSourceRevision: input.sourceRevision };
84 const statePath = join(directory, 'state.json');
85 const firewall = join(directory, 'firewall');
86 preparePunchFirewall(firewall, { bindAddress, interfaceName: device[0], supervisor });
87 const cancellation = new AbortController();
88 const stop = () => cancellation.abort();
89 const timer = setTimeout(stop, 3600000);
90 process.on('SIGTERM', stop); process.on('SIGINT', stop);
91 let page, arm, failure;
92 const rootWindow = () => {
93 const closed = rootJson(join(firewall, 'closed.json'));
94 if (closed?.verifiedAbsent) return false;
95 const opened = rootJson(join(firewall, 'opened.json'));
96 return opened?.schema === 1 && opened.port === 43443 && opened.address === bindAddress &&
97 opened.supervisorPID === supervisor.pid && opened.supervisorStart === supervisor.start &&
98 opened.openedEpoch * 1000 >= Date.parse(state.startedAt) - 1000 && opened.expiresEpoch * 1000 > Date.now();
99 };
100 async function stopArm() {
101 if (!arm) return;
102 arm.cancel.abort();
103 await arm.done;
104 check(json(join(arm.directory, 'state.json')).childReaped, 'Native arm child was not reaped before handoff');
105 }
106 async function startArm(name, origin) {
107 cancellation.signal.throwIfAborted();
108 const runDirectory = join(directory, 'server-' + name);
109 const config = { schema: 1, testId: 'phone-punch-' + name, expectedHost: hostname(), scope: 'ipv6-direct',
110 bindAddress, port: 43443, binary, binarySha256: input.binarySha256, certificateDirectory,
111 authority: `[${bindAddress}]:43443`, origins: [origin],
112 interopReceipt: join(directory, 'interop.json'), runDirectory,
113 lifetimeSeconds: Math.max(1, Math.floor((deadline - Date.now()) / 1000)) };
114 const path = join(directory, name + '-config.json');
115 privateJson(path, config);
116 const plan = inspectPlan(path);
117 check(plan.ready, plan.blockers.join('; '));
118 arm = { name, directory: runDirectory, cancel: new AbortController(), ended: false };
119 const current = arm;
120 current.done = runTest(path, { signal: current.cancel.signal }).then(
121 result => { current.ended = true; return result; },
122 error => { current.ended = true; current.error = error; });
123 const readyUntil = Date.now() + 12000;
124 while (!current.ended && !cancellation.signal.aborted && Date.now() < readyUntil) {
125 const path = join(runDirectory, 'state.json');
126 if (existsSync(path)) {
127 const serverState = json(path);
128 if (serverState.phase === 'ready') { state.child = serverState.child; state.arm = name; return; }
129 }
130 await pause(50);
131 }
132 throw current.error ?? new Error('Native ' + name + ' readiness deadline');
133 }
134 try {
135 privateJson(statePath, state);
136 const port = await pagePort();
137 page = await startPhonePage({ schema: 1, scope: 'vpn', expectedHost: hostname(), bindAddress: (process.env.HTTP3_IPV4_ADDRESS ?? '127.0.0.1'),
138 port, lifetimeSeconds: 3600, page: resolve('web/phone.html'), certificateDirectory });
139 page.closed.then(stop);
140 await startArm('control', new URL(page.url).origin);
141 const query = new URLSearchParams({ host: bindAddress, port: '43443', hash: receipt.certificateSha256 });
142 const parameters = { scope: 'ipv6-punch', phoneURL: `${page.url}?${query}`, host: bindAddress, port: 43443,
143 hash: receipt.certificateSha256, pagePort: port, expiresAt: state.expiresAt,
144 primePorts: punchPorts, maximumPrimePackets: 6, openCommand: `sudo bash ${firewall}/open.sh`,
145 closeCommand: `sudo bash ${firewall}/close.sh`, rendezvous: 'manual-current-cellular-ipv6' };
146 privateJson(join(directory, 'parameters.json'), parameters);
147 state.phase = 'awaiting-firewall'; privateJson(statePath, state);
148 console.log('RESULT punch-page-and-control-listener-ready parameters=build/phone-punch/parameters.json awaiting-root-open');
149 while (!cancellation.signal.aborted && !arm.ended) {
150 if (rootJson(join(firewall, 'closed.json'))?.verifiedAbsent) { state.reason = 'firewall-closed'; break; }
151 if (state.phase === 'awaiting-firewall' && rootWindow()) {
152 state.phase = 'control-ready'; state.controlReadyAt = new Date().toISOString(); privateJson(statePath, state);
153 console.log('RESULT punch-control-ready no-prime=true');
154 }
155 if (state.phase !== 'awaiting-firewall' && !rootWindow()) { state.reason = 'firewall-window-ended'; break; }
156 const requestPath = join(directory, 'prime-request.json');
157 if (state.phase === 'control-ready' && existsSync(requestPath)) {
158 const request = json(requestPath);
159 check(request.schema === 1 && request.confirmedControlFailed === true, 'No failed-control confirmation');
160 const phoneIPv6 = validateRendezvous(request.rendezvous, bindAddress);
161 check(rootWindow(), 'Fresh root allowance is required');
162 await stopArm();
163 const controlLog = readFileSync(join(arm.directory, 'stdout.log'), 'utf8');
164 check(!controlLog.includes('event=udp-in') && !controlLog.includes('HTTP3-AUTHENTICATED ') &&
165 !controlLog.includes('event=trace-exhausted'), 'No-prime control received packets; inspect instead of priming');
166 privateJson(join(directory, 'control-result.json'), { failedOnPhoneConfirmed: true, ingress: 0,
167 capturedAt: new Date().toISOString(), logSha256: digest(join(arm.directory, 'stdout.log')) });
168 state.phase = 'priming'; privateJson(statePath, state);
169 const prime = await primeSocket({ bindAddress, sourcePort: 43443, phoneIPv6, signal: cancellation.signal,
170 beforeSend: () => check(rootWindow(), 'Firewall window closed during priming'),
171 onRecord: value => privateJson(join(directory, 'priming.json'), value) });
172 check(prime.socketClosed && prime.packets.length === 6, 'Priming did not finish/release its socket');
173 await startArm('primed', new URL(page.url).origin);
174 state.phase = 'primed-ready'; state.primedReadyAt = new Date().toISOString();
175 state.primeEndedAt = prime.endedAt; privateJson(statePath, state);
176 console.log('RESULT punch-primed-ready connect-immediately=true packets=6 ports=40000,40001,40002');
177 }
178 await pause(100);
179 }
180 if (arm.error) throw arm.error;
181 } catch (error) { failure = error; }
182 finally {
183 clearTimeout(timer); cancellation.abort();
184 const results = await Promise.allSettled([stopArm(), page?.close()]);
185 process.off('SIGTERM', stop); process.off('SIGINT', stop);
186 failure ??= results.find(result => result.status === 'rejected')?.reason;
187 Object.assign(state, { phase: 'finished', endedAt: new Date().toISOString(),
188 childReaped: results[0].status === 'fulfilled', pageClosed: results[1].status === 'fulfilled', error: failure?.message });
189 privateJson(statePath, state);
190 console.log(`RESULT punch-finished child-reaped=${state.childReaped} page-closed=${state.pageClosed}`);
191 }
192 if (failure) throw failure;
195if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
196 try {
197 const [command, directory, rendezvous, confirmation] = process.argv.slice(2);
198 if (command === 'run') await run();
199 else if (command === 'stop') console.log(JSON.stringify(stopRun(resolve(directory))));
200 else if (command === 'prime') console.log(JSON.stringify(requestPrime(resolve(directory), resolve(rendezvous), confirmation === '--control-failed')));
201 else throw new Error('Usage: punch-window.mjs run | stop RUN_DIRECTORY | prime RUN_DIRECTORY RENDEZVOUS.json --control-failed');
202 } catch (error) { console.error('RESULT punch-error ' + error.message); process.exitCode = 1; }