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
+24
View File
@@ -0,0 +1,24 @@
// A throwaway client build for the vhost tests (#66). The real Vite build lands in T4; until then the
// test nginx's `/` needs *some* `dist` to serve, with the shape DESIGN 11.1 pins: an index.html that
// names a content-hashed asset under /assets/. Nothing here is committed: the fixture is written into
// the run's state dir, and no version of it pretends to be the client.
import fs from 'node:fs'
import path from 'node:path'
export const ASSET_HASH = 'a1b2c3d4e5f6'
export function writeClientDist(dir, { hash = ASSET_HASH } = {}) {
const assetPath = `/assets/app-${hash}.js`
fs.mkdirSync(path.join(dir, 'assets'), { recursive: true })
const index = `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>fff-vtt client fixture</title>
<script type="module" src="${assetPath}"></script></head>
<body><p id="fixture">client dist fixture</p></body>
</html>
`
const asset = `// content-hashed fixture asset (#66)\ndocument.documentElement.dataset.fixture = 'loaded'\n`
fs.writeFileSync(path.join(dir, 'index.html'), index)
fs.writeFileSync(path.join(dir, assetPath.slice(1)), asset)
return { dir, indexHtml: index, assetPath }
}
+2 -2
View File
@@ -18,7 +18,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { baseUrl, createPlayer, freePort, namePlayer, refuseLivePort, sleep } from './lib.mjs'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, refuseLivePort, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeTileGrid } from './tilefixture.mjs'
@@ -67,7 +67,7 @@ async function stack(opts = {}) {
const nginxPort = await freePort()
refuseLivePort(nginxPort)
const server = await startServer({
stateDir, publicOrigin: baseUrl(nginxPort),
stateDir, publicOrigin: httpsBaseUrl(nginxPort),
defines: opts.defines, env: opts.env,
})
const nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort })
+4
View File
@@ -20,6 +20,10 @@ export const anchorOf = w => [Math.round((w.a[0] + w.b[0]) / 2), Math.round((w.a
export const baseUrl = port => `http://127.0.0.1:${port}`
// The test nginx is TLS-only (#66): its origin is https, and its generated certificate is added to
// this process's default CA list by tools/nginx.mjs. The backend server keeps its plain-http origin.
export const httpsBaseUrl = port => `https://127.0.0.1:${port}`
// Ports of a live dev session: never let a test stack touch them (prototype withserver.sh rule).
export function refuseLivePort(port) {
if ([8088, 8080, 9000].includes(port)) throw new Error(`refusing live port ${port}`)
+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')
+2 -2
View File
@@ -11,7 +11,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { baseUrl, createPlayer, freePort, namePlayer, sleep } from './lib.mjs'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeTileGrid } from './tilefixture.mjs'
@@ -35,7 +35,7 @@ async function withOneWayStack(fn) {
const stack = { stateDir, gmKey }
const boot = async () => {
stack.nginxPort = await freePort()
stack.server = await startServer({ stateDir, publicOrigin: baseUrl(stack.nginxPort) })
stack.server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(stack.nginxPort) })
stack.nginx = await startTestNginx({ backendPort: stack.server.port, stateDir,
port: stack.nginxPort })
stack.origin = stack.nginx.origin
+2 -2
View File
@@ -15,7 +15,7 @@ import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { baseUrl, createPlayer, freePort, namePlayer, projectRoot } from './lib.mjs'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { isPng, pngBytes, tileDir, writeTileGrid, writeTiles } from './tilefixture.mjs'
@@ -27,7 +27,7 @@ async function withTileStack(fn) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
const s = await startServer({ stateDir, publicOrigin: baseUrl(nginxPort) })
const s = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let ngx
try {
ngx = await startTestNginx({ backendPort: s.port, stateDir, port: nginxPort })
+45
View File
@@ -0,0 +1,45 @@
// The test nginx's TLS material (#66, DESIGN 11.1 / TESTING 11.1). A self-signed certificate is
// GENERATED at run time, never committed: browsers only negotiate HTTP/2 over TLS, and the session
// cookie is `Secure`, so the browser e2e and the harnesses have to speak https.
//
// One directory per run (`run/tls`, gitignored) is shared by every harness file in the run: the
// certificate is a trust anchor for the Node side through NODE_EXTRA_CA_CERTS (set by tools/test.sh
// and e2e/run.sh), and nginx loads the same pair. The SANs are what a client checks on loopback.
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
const SUBJECT = '/CN=fff-vtt test nginx'
const SAN = 'subjectAltName=DNS:localhost,IP:127.0.0.1'
function generate(dir) {
fs.mkdirSync(dir, { recursive: true })
const certPath = path.join(dir, 'cert.pem')
const keyPath = path.join(dir, 'key.pem')
const r = spawnSync('openssl', [
'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1',
'-nodes', '-sha256', '-days', '3',
'-keyout', keyPath, '-out', certPath,
'-subj', SUBJECT,
// CA:TRUE so the pair is usable as a trust anchor (NODE_EXTRA_CA_CERTS) as well as a leaf;
// serverAuth + digitalSignature so a browser/h2 client accepts it as a TLS server certificate.
'-addext', SAN,
'-addext', 'basicConstraints=critical,CA:TRUE',
'-addext', 'keyUsage=critical,digitalSignature,keyCertSign',
'-addext', 'extendedKeyUsage=serverAuth',
], { encoding: 'utf8' })
if (r.status !== 0) {
throw new Error(`openssl could not generate the test certificate (is the openssl devbox ` +
`package installed?):\n${r.stdout}\n${r.stderr}`)
}
return { certPath, keyPath }
}
// Ensures <dir>/{cert,key}.pem exist and returns their paths. Idempotent: an existing pair is
// reused, so a run's harness files start from the same anchor.
export function ensureDevCert(dir) {
const certPath = path.join(dir, 'cert.pem')
const keyPath = path.join(dir, 'key.pem')
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) return { certPath, keyPath }
return generate(dir)
}
+124
View File
@@ -0,0 +1,124 @@
// #66 (spec #63 decision 6): the test vhost is the production shape of DESIGN 11.1 — TLS only, h2
// by ALPN, the client build at `/` (SPA fallback, index no-cache, hashed assets immutable), and the
// tile gate's `internal` location still unreachable from outside. The certificate is generated per
// run by tools/tlsdev.mjs. Here a Node HTTP/2 client (built-in `node:http2`, TESTING 10.4) is the
// independent client; the headless-browser proof lives in `e2e/` (npm dep, outside tools/).
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import http2 from 'node:http2'
import { X509Certificate } from 'node:crypto'
import { freePort, httpsBaseUrl, refuseLivePort } from './lib.mjs'
import { makeStateDir, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeClientDist } from './distfixture.mjs'
async function stack(fn) {
const stateDir = makeStateDir()
const dist = writeClientDist(`${stateDir}/dist`)
const nginxPort = await freePort()
refuseLivePort(nginxPort)
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let nginx
try {
nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort, distDir: dist.dir })
return await fn({ stateDir, server, nginx, dist })
} finally {
await stopTestNginx(nginx)
await stopServer(server)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
// One HTTP/2 request; resolves with the negotiated protocol, the response and the body.
async function h2Get(origin, urlPath) {
const client = http2.connect(origin)
try {
await new Promise((resolve, reject) => {
client.once('connect', resolve)
client.once('error', reject)
})
const alpn = client.alpnProtocol
const res = await new Promise((resolve, reject) => {
const req = client.request({ ':path': urlPath, ':method': 'GET' })
let headers = null
let body = ''
req.setEncoding('utf8')
req.on('response', h => { headers = h })
req.on('data', c => { body += c })
req.on('end', () => resolve({ status: headers[':status'], headers, body }))
req.on('error', reject)
req.end()
})
return { alpn, ...res }
} finally {
client.close()
}
}
test('vhost: the generated certificate is self-signed and names loopback', async () => {
await stack(async ({ nginx }) => {
const cert = new X509Certificate(fs.readFileSync(nginx.certPath))
assert.equal(cert.subject, cert.issuer, 'the certificate is self-signed')
assert.equal(cert.verify(cert.publicKey), true, 'its own signature verifies')
assert.equal(cert.checkIP('127.0.0.1'), '127.0.0.1', 'the SAN covers the loopback address')
assert.equal(cert.checkHost('localhost'), 'localhost', 'the SAN covers localhost')
assert.ok(new Date(cert.validTo) > new Date(), 'the certificate is still valid')
})
})
test('vhost: an HTTP/2 client negotiates h2 and serves the client index', async () => {
await stack(async ({ nginx, dist }) => {
const r = await h2Get(nginx.origin, '/')
assert.equal(r.alpn, 'h2', 'TLS ALPN must select h2, not http/1.1')
assert.equal(r.status, 200)
assert.match(r.headers['content-type'], /^text\/html/)
assert.equal(r.body, dist.indexHtml, 'index.html is served at /')
assert.equal(r.headers['cache-control'], 'no-cache', 'index.html is revalidated, never cached hard')
})
})
test('vhost: hashed assets are immutable, the SPA falls back, a missing asset is 404', async () => {
await stack(async ({ nginx, dist }) => {
const asset = await h2Get(nginx.origin, dist.assetPath)
assert.equal(asset.status, 200)
assert.equal(asset.alpn, 'h2')
assert.match(asset.headers['content-type'], /^application\/javascript/)
assert.equal(asset.headers['cache-control'], 'public, max-age=31536000, immutable')
assert.match(asset.body, /content-hashed fixture asset/)
// A client-side route with no file behind it is index.html (SPA fallback), revalidated.
const route = await h2Get(nginx.origin, '/scene/abc/tokens')
assert.equal(route.status, 200)
assert.equal(route.body, dist.indexHtml)
assert.equal(route.headers['cache-control'], 'no-cache')
// A stale index naming a deleted hash must fail, not boot the app.
const missing = await h2Get(nginx.origin, '/assets/app-000000000000.js')
assert.equal(missing.status, 404)
})
})
test('vhost: direct /_tiles/ is 404 over TLS', async () => {
await stack(async ({ nginx }) => {
for (const p of ['/_tiles/', '/_tiles/scene1/v1/0_0.png']) {
const r = await h2Get(nginx.origin, p)
assert.equal(r.status, 404, `${p} is internal and must not be reachable from outside`)
}
// The backend still answers through the proxy, so the 404 is the location's, not a dead vhost.
const health = await h2Get(nginx.origin, '/healthz')
assert.equal(health.status, 200)
assert.equal(health.body, '{"status":"ok"}')
})
})
test('vhost: an HTTP/1.1 client without ALPN is still served over TLS', async () => {
// Global fetch is Node's HTTP/1.1 client: it proves the TLS listener is not h2-only, so the
// harnesses (fetch + WebSocket) keep working against the same vhost the browser uses.
await stack(async ({ nginx, dist }) => {
const r = await fetch(`${nginx.origin}/`)
assert.equal(r.status, 200)
assert.equal(await r.text(), dist.indexHtml)
assert.equal(r.headers.get('cache-control'), 'no-cache')
})
})
+2 -2
View File
@@ -9,7 +9,7 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { DatabaseSync } from 'node:sqlite'
import { baseUrl, freePort, refuseLivePort } from './lib.mjs'
import { freePort, httpsBaseUrl, refuseLivePort } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeTileGrid } from './tilefixture.mjs'
@@ -49,7 +49,7 @@ async function stack(stateDir) {
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
refuseLivePort(nginxPort)
const server = await startServer({ stateDir, publicOrigin: baseUrl(nginxPort) })
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
const nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort })
return { stateDir, gmKey, server, nginx, origin: nginx.origin }
}
+6 -1
View File
@@ -27,8 +27,13 @@ export function buildServer(opts = {}) {
: path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`))
if (builtCache.has(key)) return builtCache.get(key)
fs.mkdirSync(path.dirname(out), { recursive: true })
// Worktree-local nimcache: Nim's default (~/.cache/nim/<project>_d) is shared by every checkout of
// the repo, so two worktrees building at once corrupt each other's object files. run/ is
// gitignored, and the variant name keeps a fault build separate from the clean build's cache.
const cache = path.join(projectRoot, 'run', 'nimcache', path.basename(out))
const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`,
...defines.map(d => `-d:${d}`), `-o:${out}`, path.join('server', 'main.nim')]
`--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${out}`,
path.join('server', 'main.nim')]
const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' })
if (r.status !== 0) throw new Error(`nim c server/main.nim ${defines.join(' ')} failed:\n${r.stdout}\n${r.stderr}`)
builtAt = out