AtlatestRepositorysigil-http3
sigil-http3 / tree / scriptsbrowser-preflight.mjs
1
// Linux real browser echo acceptance, with separate simulated UI checks.2
import { execFileSync, spawn } from 'node:child_process';3
import { createHash } from 'node:crypto';4
import { createServer } from 'node:http';5
import { createSocket } from 'node:dgram';6
import { constants, accessSync, readFileSync, writeFileSync, existsSync, unlinkSync } from 'node:fs';7
import { hostname } from 'node:os';8
import { join, resolve } from 'node:path';9
import { checkPhonePage } from './check-phone-page.mjs';10
import { startPhonePage } from './phone-page-host.mjs';11
import { navigatePhonePage, pageResult } from './check-page-certificate.mjs';13
const directory = resolve('build/browser');14
const certificate = JSON.parse(readFileSync(join(directory, 'certificate.json'), 'utf8'));15
const abort = new AbortController();16
const httpsPage = process.env.HTTP3_PREFLIGHT_HTTPS_PAGE === '1';17
const queryTarget = process.env.HTTP3_PREFLIGHT_QUERY === '1';18
const bindAddress = process.env.HTTP3_PREFLIGHT_HOST ?? '127.0.0.1';19
const authorityHost = bindAddress.includes(':') ? `[${bindAddress}]` : bindAddress;20
const deadline = setTimeout(() => abort.abort(new Error('Browser preflight overall deadline')), httpsPage ? 60000 : 45000);21
process.once('SIGTERM', () => abort.abort(new Error('Preflight received SIGTERM')));22
process.once('SIGINT', () => abort.abort(new Error('Preflight received SIGINT')));23
const pause = ms => new Promise(resolvePause => setTimeout(resolvePause, ms));24
const chromeCandidates = [process.env.HTTP3_CHROME, ...['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']25
.flatMap(name => (process.env.PATH ?? '').split(':').map(path => join(path, name)))].filter(Boolean);26
const chromePath = chromeCandidates.find(path => {27
try { accessSync(path, constants.X_OK); return true; } catch { return false; }28
});29
if (!chromePath) throw new Error('No Chrome/Chromium binary found; set HTTP3_CHROME to its path');31
function launch(binary, args, options = {}) {32
const child = spawn(binary, args, options);33
const state = { child, closed: false, code: null, signal: null, error: null };34
state.done = new Promise(resolveDone => {35
child.once('error', error => { state.error = error; });36
child.once('close', (code, signal) => {37
Object.assign(state, { closed: true, code, signal });38
resolveDone();39
});40
});41
return state;42
}44
function capture(stream) {45
let text = '';46
stream?.on('data', bytes => { if (text.length < 2097152) text += bytes.toString(); });47
return () => text;48
}50
function identity(pid) {51
try {52
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');53
const fields = stat.slice(stat.lastIndexOf(') ') + 2).split(' ');54
return { pid, parent: +fields[1], start: fields[19], state: fields[0] };55
} catch { return null; }56
}58
// Admission follows exact parent-child edges, recording start times to avoid59
// PID reuse. Cleanup never uses process-name or process-group termination.60
const admitted = new Map();61
function admitTree(pid) {62
const info = identity(pid);63
if (!info) return;64
const previous = admitted.get(pid);65
if (previous && previous.start !== info.start) return;66
admitted.set(pid, info);67
let children;68
try { children = readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8').trim().split(/\s+/).filter(Boolean); }69
catch { return; }70
for (const child of children) {71
const candidate = identity(+child);72
if (candidate?.parent === pid) admitTree(+child);73
}74
}75
function signalAdmitted(signal) {76
for (const info of [...admitted.values()].reverse()) {77
const current = identity(info.pid);78
if (current?.start === info.start && current.state !== 'Z') {79
try { process.kill(info.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }80
}81
}82
}83
async function waitClosed(state, milliseconds) {84
return Promise.race([state.done.then(() => true), pause(milliseconds).then(() => false)]);85
}86
async function stopChild(state) {87
if (!state || state.closed) return;88
state.child.kill('SIGTERM'); // This exact PID was returned by our spawn.89
if (!await waitClosed(state, 2000)) state.child.kill('SIGKILL');90
if (!await waitClosed(state, 2000)) throw new Error(`Failed to reap admitted PID ${state.child.pid}`);91
}93
function protocol(state) {94
let sequence = 0;95
let pending = '';96
const requests = new Map();97
state.child.stdio[4].on('data', bytes => {98
pending += bytes.toString();99
for (;;) {100
const end = pending.indexOf('\0');101
if (end < 0) break;102
const message = JSON.parse(pending.slice(0, end));103
pending = pending.slice(end + 1);104
const request = requests.get(message.id);105
if (request) {106
clearTimeout(request.timer);107
requests.delete(message.id);108
if (message.error) request.reject(new Error(JSON.stringify(message.error)));109
else request.resolve(message.result);110
}111
}112
});113
state.child.stdio[3].on('error', () => {});114
state.done.then(() => {115
for (const request of requests.values()) {116
clearTimeout(request.timer);117
request.reject(new Error('Chrome closed its DevTools pipe'));118
}119
requests.clear();120
});121
return (method, params = {}, sessionId) => new Promise((resolveRequest, reject) => {122
const id = ++sequence;123
const timer = setTimeout(() => {124
requests.delete(id);125
reject(new Error(`DevTools timeout: ${method}`));126
}, 8000);127
requests.set(id, { resolve: resolveRequest, reject, timer });128
state.child.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');129
});130
}132
let server;133
let browser;134
let http;135
let securePage;136
let cdp;137
let admissionTimer;138
let serverOutput = () => '';139
let serverError = () => '';140
let browserError = () => '';141
let failure;142
const requireEcho = process.env.HTTP3_PREFLIGHT_REQUIRE_ECHO !== '0';143
const binary = resolve('tools/interop/build/native/bin/http3-preflight');144
const candidateProfile = 'draft02: SETTINGS_ENABLE_WEBTRANSPORT=0x2b603742:1; H3_DATAGRAM=0x33:1; ENABLE_CONNECT_PROTOCOL=8:1; sec-webtransport-http3-draft=draft02; RFC9297 quarter-stream-ID datagrams';145
const receipt = { schema: 1, mode: requireEcho ? 'webtransport-echo' : 'capability-preflight',146
targetConfiguration: queryTarget ? 'query-host-port-hash' : 'fragment-url-hash',147
chromePath, certificate: { ...certificate, bytes: undefined }, candidateProfile,148
sourceRevision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),149
quicRevision: readFileSync('quic.rev', 'utf8').trim(),150
spikeSdkRevision: process.env.HTTP3_SPIKE_SDK_JOB ? readFileSync('spike-sdk.rev', 'utf8').trim() : undefined,151
binarySha256: createHash('sha256').update(readFileSync(binary)).digest('hex'),152
certificateSha256: certificate.sha256, ready: false,153
bidirectionalEcho: false, unidirectionalEcho: false, datagramEcho: false,154
server: { configurableBind: false, retry: false, boundedAdmission: false,155
peerAddressLogging: false, pathChangeLogging: false, cidChangeLogging: true, echoOnly: true } };156
try {157
const page = readFileSync(resolve('web/phone.html'), 'utf8');158
writeFileSync(join(directory, 'preflight.html'), page);159
let pageUrl;160
if (httpsPage) {161
securePage = await startPhonePage({ schema: 1, scope: 'test-loopback', expectedHost: hostname(),162
bindAddress: '127.0.0.1', port: 0, lifetimeSeconds: 65,163
page: resolve('web/phone.html'), certificateDirectory: directory });164
pageUrl = securePage.url;165
} else {166
http = createServer((request, response) => {167
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });168
response.end(page);169
});170
await new Promise(resolveListen => http.listen(0, '127.0.0.1', resolveListen));171
pageUrl = `http://127.0.0.1:${http.address().port}/`;172
}173
receipt.pageOrigin = new URL(pageUrl).origin;174
const startProbe = async selectedPort => {175
if (existsSync(join(directory, 'port'))) unlinkSync(join(directory, 'port'));176
server = launch(binary, [], {177
env: { ...process.env, HTTP3_PREFLIGHT_DIR: directory, HTTP3_PREFLIGHT_ORIGIN: receipt.pageOrigin,178
HTTP3_PREFLIGHT_PORT: String(selectedPort) }, stdio: ['ignore', 'pipe', 'pipe'],179
});180
serverOutput = capture(server.child.stdout);181
serverError = capture(server.child.stderr);182
const readyDeadline = Date.now() + 10000;183
while (!existsSync(join(directory, 'port'))) {184
if (server.closed || abort.signal.aborted || Date.now() >= readyDeadline)185
throw new Error(`Probe did not become ready: ${server.error ?? serverError()}`);186
await pause(50);187
}188
const actual = Number(readFileSync(join(directory, 'port'), 'utf8'));189
if (!Number.isInteger(actual) || actual < 1 || actual > 65535 || (selectedPort && selectedPort !== actual))190
throw new Error('Invalid admitted UDP port');191
return actual;192
};193
const port = await startProbe(0);194
receipt.udpPort = port;195
const url = `https://${authorityHost}:${port}/echo`;196
browser = launch(chromePath, [197
'--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run', '--no-default-browser-check',198
'--disable-background-networking', '--disable-breakpad', '--disable-crash-reporter',199
'--remote-debugging-pipe', `--user-data-dir=${join(directory, 'profile')}`, '--enable-quic',200
`--origin-to-force-quic-on=${authorityHost}:${port}`, `--log-net-log=${join(directory, 'netlog.json')}`,201
'--net-log-capture-mode=Default',202
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });203
browserError = capture(browser.child.stderr);204
admitTree(browser.child.pid);205
admissionTimer = setInterval(() => admitTree(browser.child.pid), 100);206
cdp = protocol(browser);207
receipt.version = await cdp('Browser.getVersion');208
receipt.browser = receipt.version.product;209
const target = await cdp('Target.createTarget', { url: 'about:blank' });210
const { sessionId } = await cdp('Target.attachToTarget', { targetId: target.targetId, flatten: true });211
await cdp('Page.enable', {}, sessionId);212
await cdp('Emulation.setDeviceMetricsOverride',213
{ width: 430, height: 932, deviceScaleFactor: 1, mobile: true }, sessionId);214
const configuration = new URLSearchParams({ url, hash: certificate.sha256, autoconnect: '1' });215
if (httpsPage) {216
const wrong = new URLSearchParams(configuration);217
wrong.set('hash', (parseInt(certificate.sha256.slice(0, 2), 16) ^ 1).toString(16).padStart(2, '0') + certificate.sha256.slice(2));218
receipt.pageTrust = await navigatePhonePage(cdp, pageUrl, wrong, sessionId, abort.signal, true, queryTarget);219
const negative = await pageResult(cdp, sessionId, abort.signal, 6000);220
receipt.wrongCertificateHash = { page: negative, rejected: negative.kind === 'failed' };221
if (!receipt.wrongCertificateHash.rejected || !negative.secureContext)222
throw new Error('HTTPS page did not reject a wrong WebTransport certificate hash in a secure context');223
await cdp('Page.navigate', { url: 'about:blank' }, sessionId);224
await stopChild(server);225
receipt.wrongCertificateHash.serverReaped = server.closed;226
writeFileSync(join(directory, 'server-negative.log'), serverOutput());227
writeFileSync(join(directory, 'server-negative.stderr'), serverError());228
await startProbe(port);229
}230
const trust = await navigatePhonePage(cdp, pageUrl, configuration, sessionId, abort.signal, httpsPage, queryTarget);231
if (!receipt.pageTrust) receipt.pageTrust = trust;232
receipt.page = await pageResult(cdp, sessionId, abort.signal, 21000);233
receipt.authenticated = serverOutput().includes('HTTP3-AUTHENTICATED');234
receipt.server.retry = serverOutput().includes('HTTP3-RETRY-VALIDATED');235
receipt.clientSettings = serverOutput().split('\n').filter(line => line.includes('HTTP3-CLIENT-SETTINGS'));236
if (!receipt.authenticated || receipt.clientSettings.length === 0) {237
throw new Error('Chrome did not reach authenticated h3 peer SETTINGS; inspect probe/netlog evidence');238
}239
receipt.ready = receipt.page.kind === 'ready';240
if (requireEcho) {241
if (!receipt.server.retry) throw new Error('Real echo acceptance requires the validated Retry factory');242
if (!receipt.ready) throw new Error(`Real WebTransport.ready failed: ${JSON.stringify(receipt.page)}`);243
const evaluate = async expression => {244
const result = await cdp('Runtime.evaluate', { expression, returnByValue: true }, sessionId);245
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));246
return result.result?.value;247
};248
await evaluate("document.getElementById('uni').click()");249
const echoDeadline = Date.now() + 5000;250
while (Date.now() < echoDeadline && !abort.signal.aborted) {251
receipt.echo = await evaluate(`(() => {252
const text = id => document.getElementById(id).textContent;253
return { state: text('state'), stream: text('stream'), datagram: text('datagram'),254
uni: text('unidirectional'), sessions: text('sessions'), attempts: text('attempts'),255
rtt: text('rtt'), datagramRtt: text('datagram-rtt'), log: text('log'),256
pathStatus: text('path-status'), serverObservations: text('path-log'),257
graphStreamPoints: document.getElementById('rtt-graph').dataset.streamPoints,258
graphDatagramPoints: document.getElementById('rtt-graph').dataset.datagramPoints };259
})()`);260
receipt.bidirectionalEcho = parseInt(receipt.echo.stream) >= 4;261
receipt.datagramEcho = parseInt(receipt.echo.datagram) >= 4;262
receipt.unidirectionalEcho = parseInt(receipt.echo.uni) >= 1;263
if (receipt.echo.state !== 'open') throw new Error(`Real echo session ended: ${JSON.stringify(receipt.echo)}`);264
if (receipt.bidirectionalEcho && receipt.datagramEcho && receipt.unidirectionalEcho) break;265
await pause(100);266
}267
if (!receipt.bidirectionalEcho || !receipt.datagramEcho || !receipt.unidirectionalEcho)268
throw new Error(`Real stream/uni/datagram echo deadline: ${JSON.stringify(receipt.echo)}`);269
if (receipt.echo.sessions !== '1 / 0' || receipt.echo.attempts !== '1 / 0')270
throw new Error('Real echo acceptance must use one session without reconnect');271
if (!(Number(receipt.echo.graphStreamPoints) >= 4) || !(Number(receipt.echo.graphDatagramPoints) >= 4))272
throw new Error('Real echo samples are missing from the live RTT graph');273
if (!receipt.echo.serverObservations)274
throw new Error('Real server observation channel did not deliver its status');275
if (process.env.HTTP3_SPIKE_SDK_JOB) {276
const contract = serverOutput().split('\n').find(line => line.startsWith('HTTP3-SERVER-CONTRACT ')) ?? '';277
const observed = receipt.echo.serverObservations;278
if (!serverOutput().includes('HTTP3-PEER ') || !observed.includes('"status":"available"') ||279
!observed.includes('"type":"peer"') || !observed.includes('"localCid":') || !observed.includes('"peerCid":'))280
throw new Error('Configured endpoint did not deliver actual peer/CID observations');281
// These flags combine actual echo/peer evidence with the reviewed driver282
// contract. They assert logging support, not that migration occurred.283
Object.assign(receipt.server, { configurableBind: contract.includes('configurable-bind=true'),284
antiAmplification: contract.includes('anti-amplification=true'),285
boundedAdmission: contract.includes('admissions=8') && contract.includes('step-delay-ms=10'),286
peerAddressLogging: true, pathChangeLogging: serverOutput().includes('path-events=available') });287
receipt.pathChangeObserved = serverOutput().includes('HTTP3-PATH-CHANGE ');288
}289
receipt.profile = candidateProfile;290
if (process.env.HTTP3_SPIKE_TRACE_PROBE === '1') {291
if (!['127.0.0.1', '::1'].includes(bindAddress)) throw new Error('Trace probe is loopback only');292
const probe = createSocket(bindAddress === '::1' ? 'udp6' : 'udp4');293
try {294
await new Promise((done, reject) => { probe.once('error', reject); probe.bind(0, bindAddress, done); });295
const probePort = probe.address().port;296
for (const bytes of [Buffer.from([0xc0]), Buffer.from([0x40, ...Array(31).fill(0xf1)])])297
await new Promise((done, reject) => probe.send(bytes, port, bindAddress, error => error ? reject(error) : done()));298
await pause(500);299
const trace = serverOutput();300
const ingress = trace.split('\n').filter(line => line.includes('event=udp-in') && line.includes(`port ${probePort} `));301
if (ingress.length !== 2 || !ingress.some(line => line.includes('new-tuple #t')) ||302
!trace.includes('reason malformed-header-or-unowned-dcid') || trace.includes('event=trace-exhausted'))303
throw new Error('Bounded extra-tuple/drop trace probe failed');304
const after = await evaluate("({state:document.getElementById('state').textContent,stream:document.getElementById('stream').textContent})");305
if (after.state !== 'open') throw new Error('Diagnostic noise changed the real connection state');306
receipt.traceProbe = { packets: 2, port: probePort, newTuple: true, dropRecorded: true, connectionStillOpen: true };307
} finally { await new Promise(done => probe.close(done)); }308
}309
const { cssContentSize } = await cdp('Page.getLayoutMetrics', {}, sessionId);310
const screenshot = await cdp('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true,311
clip: { x: 0, y: 0, width: cssContentSize.width, height: Math.min(cssContentSize.height, 2400), scale: 1 } }, sessionId);312
writeFileSync(join(directory, 'phone-page.png'), Buffer.from(screenshot.data, 'base64'));313
await evaluate("document.getElementById('stop').click()");314
}315
// This separate target checks page logic with a simulated transport. Its316
// result cannot satisfy the real WebTransport session/echo acceptance gate.317
receipt.phonePageChecks = await checkPhonePage(cdp, pageUrl, configuration);318
} catch (error) {319
failure = error;320
receipt.error = String(error.stack ?? error);321
} finally {322
if (browser) {323
try { await cdp?.('Browser.close'); } catch {}324
if (!await waitClosed(browser, 3000)) {325
admitTree(browser.child.pid);326
signalAdmitted('SIGTERM');327
if (!await waitClosed(browser, 2000)) signalAdmitted('SIGKILL');328
}329
await stopChild(browser);330
// Normally Browser.close shuts down and reaps its renderers. Retire any331
// still-running, previously admitted child explicitly by PID if needed.332
const live = () => [...admitted.values()].filter(info => {333
const current = identity(info.pid);334
return current?.start === info.start && current.state !== 'Z';335
});336
if (live().length) {337
signalAdmitted('SIGTERM');338
await pause(250);339
if (live().length) signalAdmitted('SIGKILL');340
await pause(250);341
}342
receipt.chromeReaped = browser.closed && live().length === 0;343
receipt.admittedChromePids = [...admitted.keys()];344
if (!receipt.chromeReaped && !failure) failure = new Error('Chrome cleanup incomplete');345
}346
clearInterval(admissionTimer);347
await stopChild(server);348
if (http) await new Promise(resolveClose => http.close(resolveClose));349
if (securePage) await securePage.close();350
receipt.pageHostClosed = true;351
clearTimeout(deadline);352
writeFileSync(join(directory, 'server.log'), serverOutput());353
writeFileSync(join(directory, 'server.stderr'), serverError());354
writeFileSync(join(directory, 'chrome.stderr'), browserError());355
receipt.serverReaped = server?.closed ?? false;356
writeFileSync(join(directory, 'capabilities.json'), JSON.stringify(receipt, null, 2) + '\n');357
}358
console.log(JSON.stringify(receipt, null, 2));359
if (failure) throw failure;360
console.log(`RESULT preflight-complete authenticated=${receipt.authenticated} webtransport-ready=${receipt.ready} bidi-echo=${receipt.bidirectionalEcho} uni-echo=${receipt.unidirectionalEcho} datagram-echo=${receipt.datagramEcho} chrome-reaped=${receipt.chromeReaped}`);