AtlatestRepositorysigil-http3
sigil-http3 / tree / scriptsphone-page-host.mjs
1
// Static HTTPS page hosting with exact configured address binding. The2
// WebTransport backend remains Sigil QUIC; this host has no application API.3
import { createServer } from 'node:https';4
import { createHash, createPrivateKey, X509Certificate } from 'node:crypto';5
import { lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';6
import { hostname } from 'node:os';7
import { isAbsolute, join, resolve } from 'node:path';8
import { fileURLToPath } from 'node:url';9
import { identity, stopRun } from './echo-lifecycle.mjs';11
function check(value, message) { if (!value) throw new Error(message); }12
function boundedFile(path, maximum) {13
const info = statSync(path);14
check(info.isFile() && info.size > 0 && info.size <= maximum, 'Page host file size/type mismatch');15
return readFileSync(path);16
}17
function stateFile(directory, state) {18
const temporary = join(directory, 'state.next');19
writeFileSync(temporary, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });20
renameSync(temporary, join(directory, 'state.json'));21
}23
export async function startPhonePage(config) {24
check(config.schema === 1 && config.expectedHost === hostname(), 'Page host schema/host mismatch');25
const expected = { vpn: (process.env.HTTP3_IPV4_ADDRESS ?? '127.0.0.1'), 'test-loopback': '127.0.0.1' }[config.scope];26
check(expected && config.bindAddress === expected, 'Page host must bind only its configured exact address');27
check(Number.isInteger(config.port) && config.port <= 65535 &&28
config.port >= (config.scope === 'test-loopback' ? 0 : 1024), 'Invalid page TCP port');29
check(Number.isInteger(config.lifetimeSeconds) && config.lifetimeSeconds >= 1 && config.lifetimeSeconds <= 7200,30
'Page lifetime must be between 1 and 7200 seconds');31
for (const name of ['page', 'certificateDirectory']) check(isAbsolute(config[name] ?? ''), 'Page paths must be absolute');32
const page = boundedFile(config.page, 131072);33
const cert = boundedFile(join(config.certificateDirectory, 'cert.pem'), 65536);34
const keyPath = join(config.certificateDirectory, 'key.pem');35
const info = lstatSync(keyPath);36
check(info.isFile() && info.uid === process.getuid() && (info.mode & 0o077) === 0, 'Page TLS key must be private and owned');37
const key = boundedFile(keyPath, 8192);38
let server;39
try {40
const certificate = new X509Certificate(cert);41
check(certificate.checkIP(config.bindAddress) === config.bindAddress, 'Page certificate must name the exact bind IP');42
check(certificate.checkPrivateKey(createPrivateKey(key)), 'Page certificate/private key mismatch');43
check(Date.parse(certificate.validFrom) <= Date.now() &&44
Date.parse(certificate.validTo) >= Date.now() + config.lifetimeSeconds * 1000 &&45
Date.parse(certificate.validTo) - Date.parse(certificate.validFrom) <= 14 * 86400000 &&46
certificate.publicKey.asymmetricKeyDetails?.namedCurve === 'prime256v1', 'Page certificate must be current short-lived P-256');47
let origin;48
let windowStart = Date.now(), requests = 0;49
server = createServer({ cert, key, minVersion: 'TLSv1.2', handshakeTimeout: 3000, maxHeaderSize: 8192 },50
(request, response) => {51
const headers = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',52
'Referrer-Policy': 'no-referrer', 'Connection': 'close' };53
const reply = (code, body = '') => { response.writeHead(code, headers); response.end(body); };54
if (Date.now() - windowStart >= 1000) { windowStart = Date.now(); requests = 0; }55
if (++requests > 16) return reply(429);56
if (!['GET', 'HEAD'].includes(request.method)) return reply(405);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) ||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);66
});67
server.maxConnections = 8;68
server.maxRequestsPerSocket = 16;69
server.maxHeadersCount = 16;70
server.headersTimeout = 5000;71
server.requestTimeout = 5000;72
server.keepAliveTimeout = 1000;73
server.setTimeout(5000, socket => socket.destroy());74
const sockets = new Set();75
server.on('connection', socket => {76
sockets.add(socket);77
socket.once('close', () => sockets.delete(socket));78
});79
await new Promise((ready, reject) => {80
server.once('error', reject);81
server.listen(config.port, config.bindAddress, ready);82
});83
const address = server.address();84
check(address.address === config.bindAddress, 'Page host bound an unexpected address');85
origin = `https://${config.bindAddress}:${address.port}`;86
let closing;87
let timer;88
let resolveClosed;89
const closed = new Promise(done => { resolveClosed = done; });90
const close = () => {91
if (closing) return closing;92
clearTimeout(timer);93
closing = new Promise((done, reject) => {94
server.close(error => {95
if (error) reject(error);96
else { resolveClosed(); done(); }97
});98
// Exact sockets accepted by this server only; includes TLS handshakes99
// that have not yet become HTTP connections.100
for (const socket of sockets) socket.destroy();101
});102
return closing;103
};104
timer = setTimeout(() => { void close(); }, config.lifetimeSeconds * 1000);105
return { origin, url: `${origin}/phone.html`, port: address.port, close, closed,106
certificateSha256: createHash('sha256').update(certificate.raw).digest('hex') };107
} catch (error) { server?.close(); throw error; }108
finally { key.fill(0); }109
}111
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {112
let host;113
let state;114
let config;115
let stopRequested = false;116
const terminate = () => { stopRequested = true; void host?.close(); };117
try {118
const [command, path] = process.argv.slice(2);119
check(path && process.argv.length === 4, 'Usage: phone-page-host.mjs run CONFIG.json | stop RUN_DIRECTORY');120
if (command === 'stop') console.log(JSON.stringify(stopRun(resolve(path))));121
else {122
check(command === 'run', 'Expected run or stop');123
config = JSON.parse(boundedFile(resolve(path), 65536));124
check(isAbsolute(config.runDirectory ?? ''), 'Page runDirectory must be absolute');125
mkdirSync(config.runDirectory, { mode: 0o700 });126
state = { schema: 1, kind: 'phone-page-host', phase: 'starting', supervisor: identity(process.pid),127
startedAt: new Date().toISOString() };128
stateFile(config.runDirectory, state);129
process.on('SIGTERM', terminate); process.on('SIGINT', terminate);130
host = await startPhonePage(config);131
if (stopRequested) await host.close();132
Object.assign(state, { phase: 'ready', url: host.url, port: host.port,133
expiresAt: new Date(Date.now() + config.lifetimeSeconds * 1000).toISOString(),134
certificateSha256: host.certificateSha256 });135
stateFile(config.runDirectory, state);136
console.log(`RESULT phone-page-ready url=${host.url} expires=${state.expiresAt}`);137
await host.closed;138
}139
} catch (error) { console.error(`RESULT phone-page-error ${error.message}`); process.exitCode = 1; }140
finally {141
await host?.close();142
process.off('SIGTERM', terminate); process.off('SIGINT', terminate);143
if (state) {144
Object.assign(state, { phase: 'finished', endedAt: new Date().toISOString(), pageClosed: true });145
stateFile(config.runDirectory, state);146
console.log('RESULT phone-page-closed');147
}148
}149
}