diff --git a/.gitignore b/.gitignore index cc4278a..6492b13 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,6 @@ tools/mkcorpus run/ # node-test.log carries per-run durations; regenerate it, do not commit it results/node-test.log +results/e2e.log +e2e/node_modules/ .cache-nim*/ diff --git a/devbox.json b/devbox.json index 774c2e9..3c585cc 100644 --- a/devbox.json +++ b/devbox.json @@ -15,7 +15,9 @@ "bin" ] }, - "nginx": "latest" + "nginx": "latest", + "openssl": "latest", + "chromium": "latest" }, "shell": { "init_hook": [], @@ -23,6 +25,9 @@ "test": [ "tools/test.sh" ], + "e2e": [ + "e2e/run.sh" + ], "mutation": [ "tools/mutation.sh" ], diff --git a/devbox.lock b/devbox.lock index d349768..3c461fb 100644 --- a/devbox.lock +++ b/devbox.lock @@ -1,6 +1,42 @@ { "lockfile_version": "1", "packages": { + "chromium@latest": { + "last_modified": "2026-10-08T19:21:32Z", + "resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#chromium", + "source": "devbox-search", + "version": "155.0.8059.39", + "systems": { + "aarch64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39", + "default": true + }, + { + "name": "sandbox", + "path": "/nix/store/a1w34yg08mvma03xps5dsy8vw5hrdy9w-chromium-155.0.8059.39-sandbox" + } + ], + "store_path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39", + "default": true + }, + { + "name": "sandbox", + "path": "/nix/store/5hpd396v5byrfp1vnw7zmpfscqd3b1zv-chromium-155.0.8059.39-sandbox" + } + ], + "store_path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39" + } + } + }, "coreutils@latest": { "last_modified": "2026-10-08T19:21:32Z", "resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#coreutils", @@ -586,6 +622,130 @@ } } }, + "openssl@latest": { + "last_modified": "2025-12-05T06:24:47Z", + "resolved": "github:NixOS/nixpkgs/42e29df35be6ef54091d3a3b4e97056ce0a98ce8#openssl", + "source": "devbox-search", + "version": "3.6.0", + "systems": { + "aarch64-darwin": { + "outputs": [ + { + "name": "bin", + "path": "/nix/store/z9prisxci5h5lsk3rdknd4jzq7k9q13d-openssl-3.6.0-bin", + "default": true + }, + { + "name": "man", + "path": "/nix/store/ii9mnzr3i92mgk9dkgg65739mavd0j6f-openssl-3.6.0-man", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/h0qgqik0mk0wn7rmm2kk3grfi1wzly74-openssl-3.6.0-dev" + }, + { + "name": "doc", + "path": "/nix/store/yx3ip21fdaaxpjn5fbir02mqnaw9cm4f-openssl-3.6.0-doc" + }, + { + "name": "out", + "path": "/nix/store/3z54dgks2mz3dhwddj158sdibll8xmq5-openssl-3.6.0" + } + ], + "store_path": "/nix/store/z9prisxci5h5lsk3rdknd4jzq7k9q13d-openssl-3.6.0-bin" + }, + "aarch64-linux": { + "outputs": [ + { + "name": "bin", + "path": "/nix/store/wb6q44n9kcb5acmaa4rgqsajadx1fhhl-openssl-3.6.0-bin", + "default": true + }, + { + "name": "man", + "path": "/nix/store/c9n1alb7ypzjvzd47m16fiwfczz23qs3-openssl-3.6.0-man", + "default": true + }, + { + "name": "debug", + "path": "/nix/store/ci6d4k1sj4bnr892lsrqqmjiihqsk0bl-openssl-3.6.0-debug" + }, + { + "name": "dev", + "path": "/nix/store/pq8b7fb3282g68pmk14mbyi20qn6chid-openssl-3.6.0-dev" + }, + { + "name": "doc", + "path": "/nix/store/vaplp6w56dyz38986bgkf0pbg3r486b2-openssl-3.6.0-doc" + }, + { + "name": "out", + "path": "/nix/store/nj50gkyx813dxvfmsg1q8m330hmf3h86-openssl-3.6.0" + } + ], + "store_path": "/nix/store/wb6q44n9kcb5acmaa4rgqsajadx1fhhl-openssl-3.6.0-bin" + }, + "x86_64-darwin": { + "outputs": [ + { + "name": "bin", + "path": "/nix/store/m3xwn9n0jypwjgi256idfzs979g30j29-openssl-3.6.0-bin", + "default": true + }, + { + "name": "man", + "path": "/nix/store/hw43f3y1vl7ydrd4samnwnrwqqwkpisv-openssl-3.6.0-man", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/dirjrfjk8jgsbdpslgb51cav6qaxn2vm-openssl-3.6.0-dev" + }, + { + "name": "doc", + "path": "/nix/store/va1zhkz0nfmycvd0h239hi4w40qgaxcx-openssl-3.6.0-doc" + }, + { + "name": "out", + "path": "/nix/store/q9a4wssx24xsy28w8kifdqizc01fh7sc-openssl-3.6.0" + } + ], + "store_path": "/nix/store/m3xwn9n0jypwjgi256idfzs979g30j29-openssl-3.6.0-bin" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "bin", + "path": "/nix/store/k0gl1zc7f5hk87lylxwbipb0b870bcmk-openssl-3.6.0-bin", + "default": true + }, + { + "name": "man", + "path": "/nix/store/a9jdl6xq9fc98ykpvqmc9kf0b0j9y8wh-openssl-3.6.0-man", + "default": true + }, + { + "name": "debug", + "path": "/nix/store/sqv8kbdgfxlr2d6nysr8c2715qpsi6f5-openssl-3.6.0-debug" + }, + { + "name": "dev", + "path": "/nix/store/ydrckgnllgg8nmhdwni81h7xhcpnrlhd-openssl-3.6.0-dev" + }, + { + "name": "doc", + "path": "/nix/store/cgp9ig35iwicfb9spcrgyg2m5dmlcgrv-openssl-3.6.0-doc" + }, + { + "name": "out", + "path": "/nix/store/61i74yjkj9p1qphfl7018ja4sdwkipx0-openssl-3.6.0" + } + ], + "store_path": "/nix/store/k0gl1zc7f5hk87lylxwbipb0b870bcmk-openssl-3.6.0-bin" + } + } + }, "sqlite@latest": { "last_modified": "2026-10-08T19:21:32Z", "resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite", diff --git a/docs/TESTING.md b/docs/TESTING.md index 7503943..288face 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -555,7 +555,16 @@ from the prototype, what was missing, what the M3 build added, and the tools it already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect - restores view; drag moves token and rollback works. + restores view; drag moves token and rollback works. The harness is `e2e/` and the gate is + `devbox run e2e`, separate from `devbox run test` (§11.1). +- **TLS/HTTP2 vhost (#66)**: `tools/vhost.test.mjs` (built-ins, `node:http2`) is the independent + client for the vhost itself: the generated certificate is self-signed and names loopback, ALPN + selects `h2`, `/` serves the client `dist` with index `no-cache`, `/assets/` with a year-immutable + cache and no SPA fallback for a missing hash, a client route falls back to `index.html`, and direct + `/_tiles/` is still 404. `e2e/h2.test.mjs` proves the same from real Chromium: it loads the dist and + `performance.getEntriesByType('navigation')[0].nextHopProtocol` is `h2` over TLS. Before the client + exists the served `dist` is the throwaway fixture of `tools/distfixture.mjs`; T4 replaces it with + the real Vite build and extends the same gate. - **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player browser and run the leak checker's (a)(e) assertions over them. @@ -573,7 +582,9 @@ from the prototype, what was missing, what the M3 build added, and the tools it `Cookie` and `Origin` on the wire, and without `{headers}` no `Origin` is sent; pinned by `tools/wsheaders.test.mjs` so a Node upgrade that drops the option fails loudly. - Root `devbox.json` pins `nodejs` 26 and the `nginx` used only by the test harness (DESIGN §11.1); no - global tooling. + global tooling. M4 (#66) adds `chromium` (the browser e2e) and `openssl` (generating the test + certificate); the e2e's only npm dependency, `playwright-core`, is pinned by `e2e/package-lock.json` + and lives outside `tools/`, so this built-ins-only rule keeps holding. - `devbox run test` = Nim tests first, then Node harnesses. - The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the @@ -596,6 +607,13 @@ from the prototype, what was missing, what the M3 build added, and the tools it describes: `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and `location /_tiles/ { internal; alias /tiles/; }`. Tile bytes are 32 px fixture PNGs from `tools/tilefixture.mjs`, written under `/tiles/`; none is committed. + - TLS + HTTP/2 + client dist (#66, spec #63 decision 6): the listener is TLS-only with `http2 on`, + because browsers negotiate h2 only over TLS and the session cookie is `Secure`. `tools/tlsdev.mjs` + generates the self-signed certificate per run (SAN `localhost`/`127.0.0.1`, never committed) and + appends it to the process's default CA list, so fetch/WebSocket/`node:http2` verify it with + verification on. `distDir` (default `/dist`) is served at `/` with the production cache + split; the tile/doors/oneway harnesses keep their `publicOrigin` at the vhost, so they now run + through the same TLS origin the browser uses. ### 11.2 Backups diff --git a/e2e/h2.test.mjs b/e2e/h2.test.mjs new file mode 100644 index 0000000..4394cbe --- /dev/null +++ b/e2e/h2.test.mjs @@ -0,0 +1,80 @@ +// The browser e2e gate (TESTING 10.3 "Browser e2e"; #66 first slice). `playwright-core` drives the +// devbox `chromium` against the real server through the TLS/HTTP2 test nginx: the one proof that +// matters before a phone is asked to measure is that real browsers negotiate h2 over the vhost and +// execute the built client from `/`. +// +// The app's own e2e (join, fog pixels, drag, reconnect, traffic audit) lands with the client in T4+ +// on this same harness. Here the page is the fixture `dist` of tools/distfixture.mjs, so the gate +// exists and is green before the client package does. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { chromium } from 'playwright-core' +import { freePort, httpsBaseUrl } from '../tools/lib.mjs' +import { makeStateDir, startServer, stopServer } from '../tools/withserver.mjs' +import { startTestNginx, stopTestNginx } from '../tools/nginx.mjs' +import { writeClientDist } from '../tools/distfixture.mjs' + +// Nix's chromium is a wrapper around the real binary; playwright-core launches it by path (the +// perf prototype does the same). SwiftShader is enough for correctness, never for a perf number. +const CHROMIUM = process.env.CHROMIUM ?? 'chromium' +const LAUNCH_ARGS = ['--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', + '--ignore-gpu-blocklist'] + +async function stack(fn) { + const stateDir = makeStateDir() + const dist = writeClientDist(`${stateDir}/dist`) + const nginxPort = await freePort() + 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, origin: nginx.origin }) + } finally { + await stopTestNginx(nginx) + await stopServer(server) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +} + +test('e2e: headless chromium loads the client dist and the page reports h2', async () => { + await stack(async ({ origin, dist }) => { + const browser = await chromium.launch({ executablePath: CHROMIUM, args: LAUNCH_ARGS }) + try { + // The certificate is a generated self-signed one (tools/tlsdev.mjs); a browser must be told + // to accept it. Every other security property of the page is the real thing. + const context = await browser.newContext({ ignoreHTTPSErrors: true }) + const page = await context.newPage() + const loaded = [] + page.on('response', r => loaded.push({ url: r.url(), status: r.status() })) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + page.on('console', m => { if (m.type() === 'error') errors.push(m.text()) }) + + await page.goto(`${origin}/`, { waitUntil: 'load' }) + + assert.equal(await page.title(), 'fff-vtt client fixture') + assert.equal(await page.textContent('#fixture'), 'client dist fixture') + // The hashed asset was fetched and executed by the vhost's immutable-cache location. + assert.equal(await page.evaluate(() => document.documentElement.dataset.fixture), 'loaded') + assert.deepEqual(errors, []) + const assetResponse = loaded.find(r => r.url.endsWith(dist.assetPath)) + assert.ok(assetResponse, `the page loaded ${dist.assetPath}: ${JSON.stringify(loaded)}`) + assert.equal(assetResponse.status, 200) + + // The acceptance criterion: the browser's own view of the connection is h2 over TLS. + const proto = await page.evaluate(() => { + const nav = performance.getEntriesByType('navigation')[0] + const resources = performance.getEntriesByType('resource') + .map(e => ({ name: e.name, protocol: e.nextHopProtocol })) + return { scheme: location.protocol, navigation: nav.nextHopProtocol, resources } + }) + assert.equal(proto.scheme, 'https:') + assert.equal(proto.navigation, 'h2', 'the document came over HTTP/2') + assert.ok(proto.resources.some(r => r.protocol === 'h2' && r.name.endsWith('.js')), + `subresources are h2 too: ${JSON.stringify(proto.resources)}`) + } finally { + await browser.close() + } + }) +}) diff --git a/e2e/package-lock.json b/e2e/package-lock.json new file mode 100644 index 0000000..3f7aa26 --- /dev/null +++ b/e2e/package-lock.json @@ -0,0 +1,28 @@ +{ + "name": "fff-vtt-e2e", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fff-vtt-e2e", + "version": "1.0.0", + "devDependencies": { + "playwright-core": "1.65.1" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/e2e/package.json b/e2e/package.json new file mode 100644 index 0000000..a73388e --- /dev/null +++ b/e2e/package.json @@ -0,0 +1,10 @@ +{ + "name": "fff-vtt-e2e", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Headless-browser e2e for fff-vtt (playwright-core + the devbox chromium). Lives outside tools/ because TESTING 10.4 keeps the black-box harnesses npm-dependency-free.", + "devDependencies": { + "playwright-core": "1.65.1" + } +} diff --git a/e2e/run.sh b/e2e/run.sh new file mode 100755 index 0000000..bad1307 --- /dev/null +++ b/e2e/run.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# devbox run e2e: the headless-browser gate (TESTING 10.3). Separate from `devbox run test` so the +# fast server gate stays fast (TESTING 11.1 note in #66). Requires the root devbox's `chromium` and +# the e2e/ npm dependency (`playwright-core`); the client build test in T4+ extends this script. +set -euo pipefail +cd "$(dirname "$0")/.." || exit 1 +mkdir -p results +export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}" +if [ -z "$CHROMIUM" ]; then + echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2 + exit 1 +fi +# npm deps stay out of tools/ (TESTING 10.4) and out of git; install once per checkout. +( cd e2e && { [ -d node_modules ] || npm ci --no-audit --no-fund; } ) +node --test --test-concurrency=1 --test-reporter=spec e2e/*.test.mjs > results/e2e.log 2>&1 +rc=$? +cat results/e2e.log +exit $rc diff --git a/tools/distfixture.mjs b/tools/distfixture.mjs new file mode 100644 index 0000000..c6bbf61 --- /dev/null +++ b/tools/distfixture.mjs @@ -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 = ` + +fff-vtt client fixture + +

client dist fixture

+ +` + 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 } +} diff --git a/tools/doors.test.mjs b/tools/doors.test.mjs index 684fef4..8b73d94 100644 --- a/tools/doors.test.mjs +++ b/tools/doors.test.mjs @@ -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 }) diff --git a/tools/lib.mjs b/tools/lib.mjs index d3c4baa..5eb2e7c 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -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}`) diff --git a/tools/nginx.mjs b/tools/nginx.mjs index 9336661..41ec22c 100644 --- a/tools/nginx.mjs +++ b/tools/nginx.mjs @@ -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 /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 /nginx/ for post-mortem greps. -export async function startTestNginx({ backendPort, stateDir, port }) { +// 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). +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') diff --git a/tools/oneway.test.mjs b/tools/oneway.test.mjs index 2c05cd7..6747b04 100644 --- a/tools/oneway.test.mjs +++ b/tools/oneway.test.mjs @@ -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 diff --git a/tools/tiles.test.mjs b/tools/tiles.test.mjs index 2ee08ac..9b30dbf 100644 --- a/tools/tiles.test.mjs +++ b/tools/tiles.test.mjs @@ -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 }) diff --git a/tools/tlsdev.mjs b/tools/tlsdev.mjs new file mode 100644 index 0000000..c1ebfdc --- /dev/null +++ b/tools/tlsdev.mjs @@ -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 /{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) +} diff --git a/tools/vhost.test.mjs b/tools/vhost.test.mjs new file mode 100644 index 0000000..f22a175 --- /dev/null +++ b/tools/vhost.test.mjs @@ -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') + }) +}) diff --git a/tools/wallbehaviour.test.mjs b/tools/wallbehaviour.test.mjs index a225e25..94b1a34 100644 --- a/tools/wallbehaviour.test.mjs +++ b/tools/wallbehaviour.test.mjs @@ -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 } } diff --git a/tools/withserver.mjs b/tools/withserver.mjs index be290cb..137655f 100644 --- a/tools/withserver.mjs +++ b/tools/withserver.mjs @@ -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/_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