Commit29e47162Recorded18 Oct 2026Repositorysigil-http3

Configure phone echo targets with validated IPv6 query links

Changed
 scripts/browser-preflight.mjs        |  6 ++++--
 scripts/check-page-certificate.mjs   | 10 ++++++++--
 scripts/check-phone-page.mjs         | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
 scripts/phantom-phone-query-check.sh | 34 ++++++++++++++++++++++++++++++++++
 scripts/phone-page-host.mjs          |  4 +++-
 test/test-phone-page-host.mjs        |  3 +++
 web/phone.html                       | 52 +++++++++++++++++++++++++++++++++++++++++++++++++---
 7 files changed, 162 insertions(+), 11 deletions(-)
Diff
scripts/browser-preflight.mjsmodified
@@ -13,6 +13,7 @@ const directory = resolve('build/browser');
13
const certificate = JSON.parse(readFileSync(join(directory, 'certificate.json'), 'utf8'));
14
const abort = new AbortController();
15
const httpsPage = process.env.HTTP3_PREFLIGHT_HTTPS_PAGE === '1';
+16
const queryTarget = process.env.HTTP3_PREFLIGHT_QUERY === '1';
17
const deadline = setTimeout(() => abort.abort(new Error('Browser preflight overall deadline')), httpsPage ? 60000 : 45000);
18
process.once('SIGTERM', () => abort.abort(new Error('Preflight received SIGTERM')));
19
process.once('SIGINT', () => abort.abort(new Error('Preflight received SIGINT')));
@@ -139,6 +140,7 @@ const requireEcho = process.env.HTTP3_PREFLIGHT_REQUIRE_ECHO !== '0';
140
const binary = resolve('tools/interop/build/native/bin/http3-preflight');
141
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';
142
const receipt = { schema: 1, mode: requireEcho ? 'webtransport-echo' : 'capability-preflight',
+143
targetConfiguration: queryTarget ? 'query-host-port-hash' : 'fragment-url-hash',
144
chromePath, certificate: { ...certificate, bytes: undefined }, candidateProfile,
145
sourceRevision: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
146
quicRevision: readFileSync('quic.rev', 'utf8').trim(),
@@ -209,7 +211,7 @@ try {
211
if (httpsPage) {
212
const wrong = new URLSearchParams(configuration);
213
wrong.set('hash', (parseInt(certificate.sha256.slice(0, 2), 16) ^ 1).toString(16).padStart(2, '0') + certificate.sha256.slice(2));
−212
receipt.pageTrust = await navigatePhonePage(cdp, pageUrl, wrong, sessionId, abort.signal, true);
+214
receipt.pageTrust = await navigatePhonePage(cdp, pageUrl, wrong, sessionId, abort.signal, true, queryTarget);
215
const negative = await pageResult(cdp, sessionId, abort.signal, 6000);
216
receipt.wrongCertificateHash = { page: negative, rejected: negative.kind === 'failed' };
217
if (!receipt.wrongCertificateHash.rejected || !negative.secureContext)
@@ -221,7 +223,7 @@ try {
223
writeFileSync(join(directory, 'server-negative.stderr'), serverError());
224
await startProbe(port);
225
}
−224
const trust = await navigatePhonePage(cdp, pageUrl, configuration, sessionId, abort.signal, httpsPage);
+226
const trust = await navigatePhonePage(cdp, pageUrl, configuration, sessionId, abort.signal, httpsPage, queryTarget);
227
if (!receipt.pageTrust) receipt.pageTrust = trust;
228
receipt.page = await pageResult(cdp, sessionId, abort.signal, 21000);
229
receipt.authenticated = serverOutput().includes('HTTP3-AUTHENTICATED');
scripts/check-page-certificate.mjsmodified
@@ -2,8 +2,14 @@
2
// This never installs trust or changes browser-wide certificate validation.
3
const pause = ms => new Promise(done => setTimeout(done, ms));
4
export async function navigatePhonePage(cdp, pageUrl, configuration, sessionId, signal,
−5
continuePageWarning = false) {
−6
const navigation = await cdp('Page.navigate', { url: `${pageUrl}#${configuration}` }, sessionId);
+5
continuePageWarning = false, queryTarget = false) {
+6
const configuredPage = new URL(pageUrl);
+7
if (queryTarget) {
+8
const target = new URL(configuration.get('url'));
+9
configuredPage.search = new URLSearchParams({ host: target.hostname, port: target.port || '443',
+10
hash: configuration.get('hash'), autoconnect: configuration.get('autoconnect') || '0' }).toString();
+11
} else configuredPage.hash = configuration.toString();
+12
const navigation = await cdp('Page.navigate', { url: configuredPage.href }, sessionId);
13
if (navigation.errorText && (!continuePageWarning || navigation.errorText !== 'net::ERR_CERT_AUTHORITY_INVALID'))
14
throw new Error(`Phone page navigation: ${navigation.errorText}`);
15
const receipt = { origin: new URL(pageUrl).origin, continued: false,
scripts/check-phone-page.mjsmodified
@@ -4,7 +4,9 @@
4
const simulatedTransport = `(() => {
5
window.__phoneTransports = [];
6
window.WebTransport = class {
−7
constructor() {
+7
constructor(url, options) {
+8
this.target = { url, hash: Array.from(options.serverCertificateHashes[0].value,
+9
byte => byte.toString(16).padStart(2, '0')).join('') };
10
window.__phoneTransports.push(this);
11
this.ready = Promise.resolve();
12
this.closed = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; });
@@ -75,7 +77,10 @@ export async function checkPhonePage(cdp, pageUrl, configuration) {
77
pathStatus: text('path-status'), pathLog: text('path-log'), graph: text('graph-summary'),
78
graphStreamPoints: document.getElementById('rtt-graph')?.dataset.streamPoints,
79
graphDatagramPoints: document.getElementById('rtt-graph')?.dataset.datagramPoints,
−78
transports: window.__phoneTransports?.length, page: window.__result };
+80
transports: window.__phoneTransports?.length, page: window.__result,
+81
location: location.href, documentReady: document.readyState,
+82
target: text('target'), transportTarget: window.__phoneTransports?.at(-1)?.target,
+83
injectedElements: document.querySelectorAll('img, script[src]').length };
84
})()`;
85
const waitFor = async (predicate, label) => {
86
const deadline = Date.now() + 7000;
@@ -135,9 +140,62 @@ export async function checkPhonePage(cdp, pageUrl, configuration) {
140
{ type: 'peer', seq: 0, serverTime: '2026-10-18T10:00:01Z', peer: '192.0.2.20:52000' }
141
])`);
142
await waitFor(value => value.state === 'failed', 'out-of-order server observation rejection');
+143
const queryHash = 'ab'.repeat(32);
+144
const validLinks = [
+145
{ host: 'localhost', port: '443', expected: 'https://localhost/echo' },
+146
{ host: '127.0.0.1', port: '54433', expected: 'https://127.0.0.1:54433/echo' },
+147
{ host: '2001:db8::1', port: '54433', expected: 'https://[2001:db8::1]:54433/echo' },
+148
{ host: '[2001:db8::1]', port: '65535', expected: 'https://[2001:db8::1]:65535/echo' },
+149
];
+150
const queryLink = values => {
+151
const link = new URL(pageUrl);
+152
link.search = new URLSearchParams(values).toString();
+153
link.hash = '';
+154
return link.href;
+155
};
+156
for (const { host, port, expected } of validLinks) {
+157
await pause(175); // Leave room for favicon requests within the host budget.
+158
const link = queryLink({ host, port, hash: queryHash.toUpperCase() });
+159
await cdp('Page.navigate', { url: link }, sessionId);
+160
const configured = await waitFor(value => value.location === link && value.documentReady === 'complete' &&
+161
value.target === expected, 'query target display');
+162
if (configured.transports !== 0 || configured.state !== 'idle')
+163
throw new Error('A query link connected before the user could disable VPN');
+164
await evaluate("document.getElementById('connect').click()");
+165
const opened = await waitFor(value => value.state === 'open', 'manual query target connection');
+166
if (opened.transportTarget.url !== expected || opened.transportTarget.hash !== queryHash)
+167
throw new Error('Query target or certificate hash did not reach WebTransport unchanged');
+168
await evaluate("document.getElementById('stop').click()");
+169
}
+170
const invalidLinks = [
+171
{ host: '2001:::1' }, { host: 'user@example.test' }, { host: 'https://example.test/path' },
+172
{ host: '<img src=x onerror=alert(1)>' }, { host: 'example.test/path' },
+173
{ host: 'fe80::1%eth0' }, { host: '127.1' }, { host: '' },
+174
{ port: '0' }, { port: '65536' }, { port: '1e3' }, { port: '1.5' }, { port: '443\n' },
+175
{ host: '2001:db8::1\n' }, { host: 'localhost\n' },
+176
{ hash: queryHash + '\n' }, { hash: 'ab:'.repeat(31) + 'ab' }, { hash: '<script>alert(1)</script>' },
+177
{ autoconnect: 'yes' },
+178
].map(invalid => queryLink({ host: 'localhost', port: '54433', hash: queryHash, ...invalid }));
+179
invalidLinks.push(queryLink({ host: 'localhost', port: '54433' }));
+180
invalidLinks.push(queryLink({ host: 'localhost', port: '54433', hash: queryHash }) + '&host=other.test');
+181
for (const link of invalidLinks) {
+182
await pause(175);
+183
await cdp('Page.navigate', { url: link }, sessionId);
+184
const rejected = await waitFor(value => value.location === link && value.documentReady === 'complete' &&
+185
value.state === 'failed' && value.page?.kind === 'failed', 'invalid query rejection');
+186
if (rejected.transports !== 0 || rejected.injectedElements !== 0 || rejected.target !== 'Not configured')
+187
throw new Error('Invalid query created a transport, injected markup or retained a target');
+188
}
+189
const autoLink = queryLink({ host: '::1', port: '54433', hash: queryHash, autoconnect: '1' });
+190
await cdp('Page.navigate', { url: autoLink }, sessionId);
+191
await waitFor(value => value.location === autoLink && value.state === 'open' && value.transports === 1,
+192
'explicit query autoconnect');
+193
await evaluate("document.getElementById('stop').click()");
194
return { mode: 'simulated-page-controls-not-protocol', passed: true, pings,
195
noAutomaticReconnect: failed.transports === 1, manualReconnect: reopened.sessions,
196
uniEcho: true, invalidHashRejected: true, liveRttGraph: true,
−141
pathEvents: paths.pathStatus, oversizedObservationRejected: true, outOfOrderObservationRejected: true };
+197
pathEvents: paths.pathStatus, oversizedObservationRejected: true, outOfOrderObservationRejected: true,
+198
queryLinks: { valid: validLinks.length, rejected: invalidLinks.length,
+199
manualUntilRequested: true, explicitAutoconnect: true, safeTargetDisplay: true } };
200
} finally { await cdp('Target.closeTarget', { targetId: target.targetId }); }
201
}
scripts/phantom-phone-query-check.shadded
@@ -0,0 +1,34 @@
+1
#!/usr/bin/env bash
+2
set -euo pipefail
+3
cd "$(dirname "$0")/.."
+4
mkdir -p build
+5
record_result() {
+6
local job_rc=$?
+7
printf 'RESULT phone-query-job rc=%s\n' "$job_rc" | tee -a build/phone-query-result.txt
+8
}
+9
trap record_result EXIT
+10
printf 'RESULT phone-query-loopback-only no-live-phone-listener\n' | tee build/phone-query-result.txt
+11
+12
# This page-only check reuses a measured native binary without recompiling it.
+13
# Verify its exact hash, QUIC pin and completed real-echo/reaping receipt first.
+14
node --input-type=module <<'VERIFY'
+15
import { readFileSync, mkdirSync, copyFileSync, chmodSync } from 'node:fs';
+16
import { createHash } from 'node:crypto';
+17
const job = process.env.HTTP3_PREBUILT_JOB;
+18
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(job ?? '')) throw new Error('Expected an admitted prebuilt job');
+19
const root = ((process.env.HTTP3_WORKSPACE_ROOT ?? (process.cwd() + '/build/workspaces')) + '/') + job + '/src';
+20
const receipt = JSON.parse(readFileSync(root + '/build/browser/capabilities.json'));
+21
const source = root + '/tools/interop/build/native/bin/http3-preflight';
+22
const hash = createHash('sha256').update(readFileSync(source)).digest('hex');
+23
if (receipt.mode !== 'webtransport-echo' || receipt.binarySha256 !== hash ||
+24
receipt.quicRevision !== readFileSync('quic.rev', 'utf8').trim() ||
+25
!['ready', 'bidirectionalEcho', 'unidirectionalEcho', 'datagramEcho', 'chromeReaped', 'serverReaped']
+26
.every(key => receipt[key] === true)) throw new Error('Prebuilt real-echo provenance mismatch');
+27
mkdirSync('tools/interop/build/native/bin', { recursive: true });
+28
copyFileSync(source, 'tools/interop/build/native/bin/http3-preflight');
+29
chmodSync('tools/interop/build/native/bin/http3-preflight', 0o700);
+30
console.log('RESULT verified-prebuilt-sha256=' + hash);
+31
VERIFY
+32
bash scripts/phantom-lifecycle-check.sh
+33
HTTP3_PREFLIGHT_PREBUILT=1 HTTP3_PREFLIGHT_HTTPS_PAGE=1 HTTP3_PREFLIGHT_QUERY=1 \
+34
bash scripts/phantom-browser-preflight.sh
scripts/phone-page-host.mjsmodified
@@ -57,7 +57,9 @@ export async function startPhonePage(config) {
57
if (request.headers.host !== new URL(origin).host || (request.url?.length ?? 0) > 2048) return reply(400);
58
let url;
59
try { url = new URL(request.url, origin); } catch { return reply(400); }
−60
if (url.origin !== origin || !['/', '/phone.html'].includes(url.pathname) || url.search) return reply(404);
+60
if (url.origin !== origin || !['/', '/phone.html'].includes(url.pathname) ||
+61
[...url.searchParams.keys()].some(name => !['host', 'port', 'hash', 'autoconnect'].includes(name)))
+62
return reply(404);
63
response.writeHead(200, { ...headers, 'Content-Type': 'text/html; charset=utf-8',
64
'Content-Length': page.length, 'Content-Security-Policy': "frame-ancestors 'none'; base-uri 'none'" });
65
response.end(request.method === 'HEAD' ? undefined : page);
test/test-phone-page-host.mjsmodified
@@ -44,6 +44,9 @@ test('verified HTTPS serves the exact page only and validates method, host and p
44
assert.equal(page.status, 200);
45
assert.equal(page.body, readFileSync(config.page, 'utf8'));
46
assert.equal(page.headers['cache-control'], 'no-store');
+47
const configured = await get(host, '/phone.html?host=%3A%3A1&port=54433&hash=' + 'ab'.repeat(32));
+48
assert.equal(configured.status, 200);
+49
assert.equal(configured.body, page.body, 'Query parameters select no other file and enter no server HTML');
50
const head = await get(host, '/', { method: 'HEAD' });
51
assert.equal(head.status, 200);
52
assert.equal(head.body, '');
web/phone.htmlmodified
@@ -31,6 +31,7 @@
31
<button id="uni" type="button" disabled>Test unidirectional echo</button>
32
<button id="download" type="button">Save log</button>
33
</form>
+34
<p>Configured target: <output id="target">Not configured</output></p>
35
<dl aria-live="polite">
36
<dt>Session state</dt><dd id="state">idle</dd>
37
<dt>Connect attempts / reconnect attempts</dt><dd id="attempts">0 / 0</dd>
@@ -69,6 +70,46 @@
70
element('url').value = options.get('url') ?? '';
71
element('hash').value = options.get('hash') ?? '';
72
if (options.get('datagrams') === '0') element('datagrams').checked = false;
+73
const query = new URLSearchParams(location.search);
+74
let queryError;
+75
const queryTarget = ['host', 'port', 'hash'].some(name => query.has(name));
+76
if (queryTarget) {
+77
// A partial or ambiguous query never falls back to fragment credentials.
+78
element('url').value = '';
+79
element('hash').value = '';
+80
try {
+81
if (!['host', 'port', 'hash'].every(name => query.getAll(name).length === 1))
+82
throw new Error('Supply exactly one host, port and hash query parameter');
+83
const host = query.get('host');
+84
const port = query.get('port');
+85
const hash = query.get('hash');
+86
if (!/^[0-9]{1,5}$/.test(port) || String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)
+87
throw new Error('Target port must be an integer from 1 to 65535');
+88
if (hash.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hash))
+89
throw new Error('Certificate SHA-256 must be 64 hex digits');
+90
if (!host || host.length > 253) throw new Error('Invalid target host');
+91
let authorityHost = host;
+92
if (host.includes(':')) {
+93
const literal = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
+94
if (!literal || /[^0-9a-fA-F:.]/.test(literal)) throw new Error('Invalid IPv6 target');
+95
authorityHost = `[${literal}]`;
+96
} else if (/[^a-zA-Z0-9.-]/.test(host) || !host.split('.').every(label =>
+97
/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(label))) {
+98
throw new Error('Invalid target host');
+99
}
+100
// URL parses IPv6 syntax; the allowlist above rejects credentials,
+101
// zone identifiers, paths, query/fragment delimiters and HTML characters.
+102
const target = new URL(`https://${authorityHost}:${Number(port)}/echo`);
+103
if (!host.includes(':') && target.hostname !== host.toLowerCase())
+104
throw new Error('Use a canonical hostname or IPv4 address');
+105
if (query.getAll('autoconnect').length > 1 ||
+106
(query.has('autoconnect') && !['0', '1'].includes(query.get('autoconnect'))))
+107
throw new Error('Autoconnect must be 0 or 1');
+108
element('url').value = target.href;
+109
element('hash').value = hash.toLowerCase();
+110
} catch (error) { queryError = error; }
+111
}
+112
element('target').textContent = element('url').value || 'Not configured';
113
114
function event(kind, details = {}) {
115
const entry = { utc: new Date().toISOString(), elapsedMs: +(performance.now() - baseline).toFixed(1), kind, ...details };
@@ -328,8 +369,9 @@
369
if (!('WebTransport' in window)) throw new Error('This browser does not expose WebTransport');
370
const url = new URL(element('url').value);
371
if (url.protocol !== 'https:' || url.hash || url.username || url.password) throw new Error('Use an HTTPS URL without credentials or a fragment');
−331
const hash = element('hash').value.replace(/[:\s]/g, '');
−332
if (!/^[0-9a-fA-F]{64}$/.test(hash)) throw new Error('Certificate SHA-256 must be 64 hex digits');
+372
const hash = element('hash').value;
+373
if (hash.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hash)) throw new Error('Certificate SHA-256 must be 64 hex digits');
+374
element('target').textContent = url.href;
375
pendingConnect = true;
376
const transport = new WebTransport(url.href, { serverCertificateHashes: [{ algorithm: 'sha-256',
377
value: Uint8Array.from(hash.match(/../g), byte => parseInt(byte, 16)) }] });
@@ -425,7 +467,11 @@
467
element('support').textContent = `Secure context: ${isSecureContext}; WebTransport: ${'WebTransport' in window}. No automatic reconnect.`;
468
network();
469
setInterval(render, 250);
−428
if (options.get('autoconnect') === '1') void connect();
+470
if (queryError) {
+471
state('failed');
+472
event('configuration-error', { detail: queryError.message });
+473
reportPage('failed', baseline, { name: queryError.name, message: queryError.message });
+474
} else if ((queryTarget ? query.get('autoconnect') : options.get('autoconnect')) === '1') void connect();
475
})();
476
</script>
477
</html>