// 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: // / -> 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 /tiles/, so only an internal redirect reaches it // /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 { ensureCert } from './tlsdev.mjs' // 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, bindHost = '127.0.0.1', serverName = 'localhost', tag = 'test only' }) { 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). const tilesRoot = path.join(stateDir, 'tiles') return `# generated by tools/nginx.mjs; ${tag} daemon off; worker_processes 1; pid ${temp('nginx.pid')}; error_log ${temp('error.log')} warn; events { worker_connections 128; } http { access_log ${temp('access.log')}; client_body_temp_path ${temp('client_body')}; proxy_temp_path ${temp('proxy')}; fastcgi_temp_path ${temp('fastcgi')}; uwsgi_temp_path ${temp('uwsgi')}; scgi_temp_path ${temp('scgi')}; server_tokens off; 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 { # 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 ${bindHost}:${port} ssl; http2 on; ssl_certificate ${certPath}; ssl_certificate_key ${keyPath}; ssl_protocols TLSv1.2 TLSv1.3; server_name ${serverName}; location = /healthz { proxy_pass http://127.0.0.1:${backendPort}; } location = /join { proxy_pass http://127.0.0.1:${backendPort}; access_log off; add_header Referrer-Policy no-referrer; } # Nim decides and answers X-Accel-Redirect; nginx only forwards the decision. location /tiles/ { proxy_pass http://127.0.0.1:${backendPort}; } location = /ws { proxy_pass http://127.0.0.1:${backendPort}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $conn_up; proxy_read_timeout 1h; proxy_buffering off; } # Unreachable from outside: the internal directive rejects a direct request with 404. The alias # is /tiles//v/, the tree the X-Accel-Redirect names (3.3, 11.1). # Cache-Control: private rides from the Nim gate through the internal redirect (nginx passes it). location /_tiles/ { 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; } } } ` } async function portIsFree(port, host = '127.0.0.1') { return await new Promise(resolve => { const srv = net.createServer() srv.once('error', () => resolve(false)) srv.listen(port, host, () => srv.close(() => resolve(true))) }) } // 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, certificate and logs live under /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). // // `bindHost`/`serverName` default to loopback (every test stack); `devbox run serve` passes the // detected LAN address so nginx, not the server, is the LAN listener. `certDir`/`certPath` let the // caller supply a persistent certificate instead of the per-run loopback one; `tag` labels the // generated config header. export async function startTestNginx({ backendPort, stateDir, port, distDir, bindHost = '127.0.0.1', serverName = 'localhost', originHost, certDir, certPath, keyPath, certOpts, tag }) { if (!(await portIsFree(port, bindHost))) { throw new Error(`test nginx port ${port} on ${bindHost} 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 }) } if (!certPath || !keyPath) { const cert = ensureCert(certDir ?? path.join(prefix, 'tls'), certOpts) certPath = cert.certPath keyPath = cert.keyPath } trustCert(certPath) const docRoot = distDir ?? path.join(stateDir, 'dist') const confPath = path.join(prefix, 'nginx.conf') fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir, distDir: docRoot, certPath, keyPath, bindHost, serverName, tag })) 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: `https://${originHost ?? bindHost}:${port}`, prefix, confPath, child, certPath, keyPath, distDir: docRoot, bindHost, 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` + `--- stderr.log ---\n${read('stderr.log')}` }, } const deadline = Date.now() + 15000 for (;;) { if (child.exitCode !== null) { fs.closeSync(logFd) throw new Error(`nginx exited (code=${child.exitCode})\n${handle.log()}`) } try { const status = await probeHealth(handle.origin) if (status === 200) break } catch {} if (Date.now() > deadline) { child.kill('SIGKILL') fs.closeSync(logFd) throw new Error(`nginx did not proxy /healthz\n${handle.log()}`) } await sleep(50) } handle.logFd = logFd return handle } export async function stopTestNginx(handle) { if (!handle) return if (handle.child.exitCode === null && handle.child.signalCode === null) { handle.child.kill('SIGTERM') const deadline = Date.now() + 5000 while (handle.child.exitCode === null && handle.child.signalCode === null && Date.now() < deadline) { await sleep(25) } if (handle.child.exitCode === null && handle.child.signalCode === null) handle.child.kill('SIGKILL') } if (handle.logFd !== undefined) { try { fs.closeSync(handle.logFd) } catch {} } }