test: TLS + HTTP/2 test vhost with the client dist served at /

The test nginx is now the production shape of DESIGN 11.1 and the browser
gate's real path (#66, spec #63 decision 6): TLS-only listener with
http2 on, a self-signed certificate generated per run (tools/tlsdev.mjs,
added to the process's default CA list so verification stays on), the
client dist at / with SPA fallback, index no-cache and a year-immutable
/assets/ cache, and the tile gate's internal /_tiles/ still unreachable.

Existing tile/doors/oneway/wallbehaviour harnesses point their server's
public origin at the https vhost, so they prove the same listener the
browser uses. tools/vhost.test.mjs is the independent node:http2 client
(cert SANs, ALPN h2, cache headers, SPA fallback, direct /_tiles/ 404);
e2e/h2.test.mjs drives devbox chromium via playwright-core and asserts
the page reports h2 (`devbox run e2e`, npm deps outside tools/).

Root devbox gains chromium + openssl. Harness builds use a worktree-local
nimcache so parallel worktrees stop corrupting each other's objects.

Refs #66
This commit is contained in:
2026-11-20 23:11:05 +01:00
parent 0448002cc5
commit 1dff520f31
18 changed files with 627 additions and 27 deletions
+92 -15
View File
@@ -1,21 +1,43 @@
// A minimal test nginx for the tile gate (DESIGN 3.3, 10.1 "withserver + M3 test nginx", 11.1;
// M3 slice 9 / #24). nginx itself is a devbox package (devbox.json), never a global install: the
// harness starts it on a free loopback port with a config generated at test time under the server's
// state dir, so nothing about a run (ports, state paths) is committed.
// A minimal test nginx for the tile gate and the client build (DESIGN 11.1, TESTING 10.1 "withserver
// + M3 test nginx", 11.1; M3 slice 9 / #24, TLS + HTTP/2 + client dist #66). nginx itself is a
// devbox package (devbox.json), never a global install: the harness starts it on a free loopback
// port with a config generated at test time under the server's state dir, so nothing about a run
// (ports, state paths, certificate) is committed.
//
// The vhost shape mirrors the production one of 11.1 that this slice has to prove:
// /join -> the backend (`access_log off`, no-referrer header)
// /tiles/ -> the backend, which decides and answers X-Accel-Redirect
// / -> the client build (`dist`): SPA fallback to index.html, index no-cache, hashed
// assets under /assets/ with a long immutable cache
// /join -> the backend (`access_log off`, no-referrer header)
// /tiles/ -> the backend, which decides and answers X-Accel-Redirect
// /_tiles/ -> `internal` alias of <stateDir>/tiles/, so only an internal redirect reaches it
// /ws -> the backend upgrade
// /ws -> the backend upgrade
// The `/healthz` proxy is the readiness probe for the proxy itself.
//
// TLS + HTTP/2 (#66, spec #63 decision 6): browsers negotiate h2 only over TLS, and the session
// cookie is `Secure`, so the vhost listens only on TLS with `http2 on`. The certificate is a
// self-signed one generated per run by tools/tlsdev.mjs (never committed) and added to this
// process's default CA list, so the harnesses' fetch/WebSocket/h2 clients verify it with verification
// on.
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import https from 'node:https'
import net from 'node:net'
import path from 'node:path'
import tls from 'node:tls'
import { sleep } from './lib.mjs'
import { ensureDevCert } from './tlsdev.mjs'
function config({ prefix, port, backendPort, stateDir }) {
// Every TLS client in this process (global fetch, the global WebSocket, node:http2) must trust the
// certificate that was generated milliseconds ago. NODE_EXTRA_CA_CERTS can only be read at startup,
// so the generated cert is appended to the process's default CA list instead: same effect, no env
// plumbing, and verification stays ON (only this one self-signed loopback cert is trusted).
function trustCert(certPath) {
const pem = fs.readFileSync(certPath, 'utf8')
const current = tls.getCACertificates('default')
if (!current.includes(pem)) tls.setDefaultCACertificates([...current, pem])
}
function config({ prefix, port, backendPort, stateDir, distDir, certPath, keyPath }) {
const temp = p => path.join(prefix, p)
// `alias` needs the tiles root with its trailing slash; state dirs are harness temp dirs, so no
// quoting surprises (nginx does not take a quoted path here).
@@ -39,12 +61,21 @@ http {
default_type application/octet-stream;
types {
text/html html;
text/css css;
application/javascript js;
application/json json;
image/png png;
}
map $http_upgrade $conn_up { default upgrade; '' close; }
server {
listen 127.0.0.1:${port};
# TLS only, h2 by ALPN (#66): the production listener is 443/TLS and a browser will not speak
# h2 to a plaintext port. http2 on is the nginx >= 1.25.1 form of the old 'listen ... http2' directive.
listen 127.0.0.1:${port} ssl;
http2 on;
ssl_certificate ${certPath};
ssl_certificate_key ${keyPath};
ssl_protocols TLSv1.2 TLSv1.3;
server_name localhost;
location = /healthz { proxy_pass http://127.0.0.1:${backendPort}; }
@@ -74,6 +105,31 @@ http {
internal;
alias ${tilesRoot}/;
}
# The client build (DESIGN 11.1): Vite writes content-hashed files under assets/ and an
# index.html that names them, so index (and every SPA route that falls back to it) is
# revalidated while a hashed asset is cached for a year. A missing asset is a 404, never the
# SPA fallback: a stale index asking for a deleted hash must fail loudly, not boot the app.
location /assets/ {
root ${distDir};
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable" always;
}
# The SPA fallback target is an exact location on purpose: the internal redirect from the
# prefix location lands here, so a stack with no dist at all answers 404 instead of the "rewrite
# or internal redirection cycle" nginx raises when a try_files fallback re-enters its location.
location = /index.html {
root ${distDir};
try_files /index.html =404;
add_header Cache-Control "no-cache" always;
}
location / {
root ${distDir};
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache" always;
}
}
}
`
@@ -87,22 +143,43 @@ async function portIsFree(port) {
})
}
// The readiness probe is the proxy's own /healthz. It is a single TLS request with verification off
// on purpose: the certificate was generated a few milliseconds ago by this process, and this check
// only answers "did *this* nginx master come up", not "is the chain trusted".
function probeHealth(origin) {
return new Promise((resolve, reject) => {
const req = https.get(`${origin}/healthz`, { rejectUnauthorized: false, timeout: 2000 }, res => {
res.resume()
resolve(res.statusCode)
})
req.on('timeout', () => req.destroy(new Error('timeout')))
req.on('error', reject)
})
}
// Starts nginx in front of `backendPort`. Resolves once the proxy answers /healthz. Stop it with
// stopTestNginx(); the config and logs live under <stateDir>/nginx/ for post-mortem greps.
export async function startTestNginx({ backendPort, stateDir, port }) {
// stopTestNginx(); the config, certificate and logs live under <stateDir>/nginx/ for post-mortem
// greps. `distDir` is the static client root (`/`); a caller that only proves the API surface can
// leave it missing (every unknown path is then a plain 404).
export async function startTestNginx({ backendPort, stateDir, port, distDir }) {
if (!(await portIsFree(port))) throw new Error(`test nginx port ${port} is already in use`)
const prefix = path.join(stateDir, 'nginx')
fs.mkdirSync(prefix, { recursive: true })
for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) {
fs.mkdirSync(path.join(prefix, d), { recursive: true })
}
const { certPath, keyPath } = ensureDevCert(path.join(prefix, 'tls'))
trustCert(certPath)
const docRoot = distDir ?? path.join(stateDir, 'dist')
const confPath = path.join(prefix, 'nginx.conf')
fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir }))
fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir, distDir: docRoot,
certPath, keyPath }))
const logFd = fs.openSync(path.join(prefix, 'stderr.log'), 'a')
const child = spawn('nginx', ['-p', prefix, '-c', confPath, '-e', path.join(prefix, 'error.log')],
{ stdio: ['ignore', logFd, logFd] })
const handle = {
port, origin: `http://127.0.0.1:${port}`, prefix, confPath, child,
port, origin: `https://127.0.0.1:${port}`, prefix, confPath, child, certPath, keyPath,
distDir: docRoot,
log: () => {
const read = f => { try { return fs.readFileSync(path.join(prefix, f), 'utf8') } catch { return '' } }
return `--- access.log ---\n${read('access.log')}\n--- error.log ---\n${read('error.log')}\n` +
@@ -116,8 +193,8 @@ export async function startTestNginx({ backendPort, stateDir, port }) {
throw new Error(`nginx exited (code=${child.exitCode})\n${handle.log()}`)
}
try {
const r = await fetch(`${handle.origin}/healthz`)
if (r.status === 200) break
const status = await probeHealth(handle.origin)
if (status === 200) break
} catch {}
if (Date.now() > deadline) {
child.kill('SIGKILL')