AtlatestRepositorysigil-http3
sigil-http3 / tree / scriptscheck-phone-page.mjs
1
// Browser-only page checks, run on Linux by the existing admitted Chrome.2
// This transport double exercises framing/measurement/UI; it proves no QUIC3
// or WebTransport protocol interoperability.4
const simulatedTransport = `(() => {5
window.__phoneTransports = [];6
window.WebTransport = class {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; });13
this.incomingUnidirectionalStreams = new ReadableStream({ start: controller => { this.uni = controller; } });14
let datagram;15
let count = 0;16
this.datagrams = {17
readable: new ReadableStream({ start: controller => { datagram = controller; } }),18
writable: new WritableStream({ write: bytes => { if (++count % 3 !== 0) datagram.enqueue(bytes.slice()); } }),19
};20
}21
async createBidirectionalStream() {22
let controller;23
let held;24
return {25
readable: new ReadableStream({ start: value => { controller = value; } }),26
writable: new WritableStream({ write: bytes => {27
if (!held) { held = bytes.slice(); return; }28
const both = new Uint8Array(held.length + bytes.length);29
both.set(held); both.set(bytes, held.length); held = null;30
controller.enqueue(both.slice(0, 3)); controller.enqueue(both.slice(3));31
} }),32
};33
}34
async createUnidirectionalStream() {35
let bytes;36
return new WritableStream({37
write: value => { bytes = value.slice(); },38
close: () => this.uni.enqueue(new ReadableStream({ start(controller) {39
controller.enqueue(bytes.slice(0, 7)); controller.enqueue(bytes.slice(7)); controller.close();40
} })),41
});42
}43
observe(records, invalidLength = false) {44
const frames = records.map(record => {45
const bytes = new TextEncoder().encode(JSON.stringify(record));46
const frame = new Uint8Array(2 + bytes.length);47
frame[0] = bytes.length >> 8; frame[1] = bytes.length & 255; frame.set(bytes, 2);48
return frame;49
});50
const bytes = new Uint8Array(4 + frames.reduce((size, frame) => size + frame.length, 0));51
bytes.set([83, 71, 69, 49]);52
let offset = 4;53
for (const frame of frames) { bytes.set(frame, offset); offset += frame.length; }54
if (invalidLength) { bytes[4] = 4; bytes[5] = 1; }55
this.uni.enqueue(new ReadableStream({ start(controller) {56
controller.enqueue(bytes.slice(0, 2)); controller.enqueue(bytes.slice(2, 5));57
controller.enqueue(bytes.slice(5, 17)); controller.enqueue(bytes.slice(17)); controller.close();58
} }));59
}60
close() { if (!this.ended) { this.ended = true; this.resolve({ closeCode: 0, reason: 'simulated close' }); } }61
};62
})();`;64
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));65
export async function checkPhonePage(cdp, pageUrl, configuration) {66
const target = await cdp('Target.createTarget', { url: 'about:blank' });67
const { sessionId } = await cdp('Target.attachToTarget', { targetId: target.targetId, flatten: true });68
const evaluate = async expression => {69
const result = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId);70
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));71
return result.result?.value;72
};73
const snapshot = `(() => {74
const text = id => document.getElementById(id)?.textContent;75
return { state: text('state'), attempts: text('attempts'), sessions: text('sessions'),76
stream: text('stream'), datagram: text('datagram'), uni: text('unidirectional'),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,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;87
let value;88
while (Date.now() < deadline) {89
value = await evaluate(snapshot);90
if (predicate(value)) return value;91
await pause(100);92
}93
throw new Error(`Phone page ${label}: ${JSON.stringify(value)}`);94
};95
try {96
await cdp('Page.enable', {}, sessionId);97
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: simulatedTransport }, sessionId);98
await cdp('Page.navigate', { url: `${pageUrl}#${configuration}` }, sessionId);99
const pings = await waitFor(value => value.state === 'open' && parseInt(value.stream) >= 4 &&100
parseInt(value.datagram) >= 2, 'fragmented/coalesced stream and datagram echo');101
const datagrams = pings.datagram.split(' / ').map(Number);102
if (datagrams[0] >= datagrams[1]) throw new Error('Simulated datagram loss was hidden');103
if (!(Number(pings.graphStreamPoints) >= 4) || !(Number(pings.graphDatagramPoints) >= 2))104
throw new Error('Live graph did not retain the measured echo samples');105
await evaluate(`window.__phoneTransports[0].observe([106
{ type: 'peer', seq: 0, serverTime: '2026-10-18T10:00:00Z', peer: '192.0.2.10:51000' },107
{ type: 'path-change', seq: 1, serverTime: '2026-10-18T10:00:01Z', before: '192.0.2.10:51000', after: '192.0.2.20:52000' },108
{ type: 'path-validated', seq: 2, serverTime: '2026-10-18T10:00:02Z', peer: '192.0.2.20:52000' },109
{ type: 'cid-change', seq: 3, serverTime: '2026-10-18T10:00:03Z', localCid: '010203', peerCid: '040506' }110
])`);111
const paths = await waitFor(value => value.pathStatus.includes('1 path changes / 1 CID changes') &&112
value.pathLog.includes('path-validated'), 'fragmented/coalesced server observation records');113
await evaluate("document.getElementById('uni').click()");114
await waitFor(value => value.uni === '1 / 1', 'unidirectional echo');115
await evaluate("window.dispatchEvent(new Event('offline')); window.__phoneTransports[0].reject(new Error('simulated network failure'))");116
await waitFor(value => value.state === 'failed', 'failed session display');117
await pause(500);118
const failed = await evaluate(snapshot);119
if (failed.transports !== 1 || failed.attempts !== '1 / 0') throw new Error('Page reconnected automatically');120
await evaluate("document.getElementById('connect').click()");121
const reopened = await waitFor(value => value.state === 'open' && value.sessions === '2 / 1' &&122
value.attempts === '2 / 1', 'manual reconnect accounting');123
if (reopened.pathLog || !reopened.pathStatus.includes('Waiting'))124
throw new Error('Reopened session retained stale server path observations');125
await evaluate("document.getElementById('stop').click()");126
await waitFor(value => value.state === 'stopped', 'manual stop');127
await evaluate("document.getElementById('hash').value = 'invalid'; document.getElementById('connect').click()");128
const invalid = await waitFor(value => value.page?.message?.includes('64 hex'), 'invalid hash rejection');129
if (invalid.transports !== 2 || invalid.attempts !== '2 / 1') throw new Error('Invalid hash opened a transport');130
await evaluate(`document.getElementById('hash').value = ${JSON.stringify(configuration.get('hash'))}; document.getElementById('connect').click()`);131
await waitFor(value => value.state === 'open' && value.transports === 3, 'metadata error fixture');132
await evaluate(`window.__phoneTransports[2].observe([133
{ type: 'path-change', seq: 0, serverTime: '2026-10-18T10:00:00Z' }134
], true)`);135
await waitFor(value => value.state === 'failed', 'oversized server observation rejection');136
await evaluate("document.getElementById('connect').click()");137
await waitFor(value => value.state === 'open' && value.transports === 4, 'out-of-order metadata fixture');138
await evaluate(`window.__phoneTransports[3].observe([139
{ type: 'peer', seq: 1, serverTime: '2026-10-18T10:00:00Z', peer: '192.0.2.10:51000' },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
// Exercise the actual navigator hint, including programmatic form submit.195
await evaluate(`Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => false });196
window.dispatchEvent(new Event('offline'))`);197
const offline = await evaluate(`({ disabled: document.getElementById('connect').disabled,198
banner: document.getElementById('network-banner').textContent, count: window.__phoneTransports.length })`);199
if (!offline.disabled || !offline.banner.includes('OFFLINE')) throw new Error('Offline Connect gate missing');200
await evaluate(`document.getElementById('configuration').dispatchEvent(new Event('submit', { cancelable: true }))`);201
if (await evaluate('window.__phoneTransports.length') !== offline.count)202
throw new Error('Programmatic submission bypassed the offline gate');203
await evaluate(`Object.defineProperty(navigator, 'onLine', { configurable: true, get: () => true });204
window.dispatchEvent(new Event('online'))`);205
if (await evaluate("document.getElementById('connect').disabled")) throw new Error('Online recovery did not enable Connect');206
return { mode: 'simulated-page-controls-not-protocol', passed: true, pings,207
noAutomaticReconnect: failed.transports === 1, manualReconnect: reopened.sessions,208
uniEcho: true, invalidHashRejected: true, liveRttGraph: true, offlineGate: true, onlineRecovery: true,209
pathEvents: paths.pathStatus, oversizedObservationRejected: true, outOfOrderObservationRejected: true,210
queryLinks: { valid: validLinks.length, rejected: invalidLinks.length,211
manualUntilRequested: true, explicitAutoconnect: true, safeTargetDisplay: true } };212
} finally { await cdp('Target.closeTarget', { targetId: target.targetId }); }213
}