feat(m4): LAN playtest run script (devbox run serve) (#80)
One command builds the client dist and server binary, then starts the loopback server behind the DESIGN 11.1 TLS/HTTP2 nginx on the detected LAN address. State, GM key and certificate persist under run/lan so a table and a phone's trust survive Ctrl-C/restart; the certificate is regenerated when the address changes. Prints the URL, GM key and Android/laptop trust steps. tools/nginx.mjs and tools/tlsdev.mjs gained the bind/SAN knobs the LAN needs (test defaults unchanged). tools/serve.test.mjs proves h2 + verified TLS on /healthz and /, POST /join, a /ws upgrade on the LAN address, loopback-only server binding, and identical key/cert after a restart.
This commit is contained in:
@@ -6,8 +6,9 @@ The server decides what each player sees — line of sight, explored area, token
|
||||
modified client cannot reveal anything its player is not entitled to. No accounts, no external
|
||||
database, one scene, no RPG rules or dice.
|
||||
|
||||
Status: the client (M4) is built; the manual phone playtest is still pending. The NixOS
|
||||
deployment module is M6 and not written yet — today you run the binary behind your own TLS nginx.
|
||||
Status: the client (M4) is built; `devbox run serve` puts a table on the LAN for the manual phone
|
||||
playtest. The NixOS deployment module is M6 and not written yet — for a permanent install you still
|
||||
run the binary behind your own TLS nginx (the manual path below is the fallback).
|
||||
|
||||
---
|
||||
|
||||
@@ -20,7 +21,40 @@ deployment module is M6 and not written yet — today you run the binary behind
|
||||
- An HTTPS site in front of it. The session cookie is `Secure`, so plain HTTP will not keep you
|
||||
signed in. The server itself always binds `127.0.0.1`; nginx is the only public face.
|
||||
|
||||
### Build it once
|
||||
### Start a LAN playtest (one command)
|
||||
|
||||
From the repo root, inside devbox:
|
||||
|
||||
```sh
|
||||
devbox run serve
|
||||
```
|
||||
|
||||
It builds the server binary and the client, starts a TLS + HTTP/2 nginx on the laptop's LAN address
|
||||
in front of the server (the server itself stays on `127.0.0.1`), and prints:
|
||||
|
||||
- the `https://<lan-ip>:8443` URL to open on the phone and the laptop,
|
||||
- the GM key (created on first run; an existing key is printed, never replaced),
|
||||
- the certificate-trust steps for Android Chrome and for a laptop (Linux/macOS/Firefox).
|
||||
|
||||
Ctrl-C stops nginx and the server and releases the port; the next start works. State (`state.db`,
|
||||
`tiles/`), the GM key and the certificate live under `run/lan` and are **not** wiped, so a session
|
||||
survives a restart and a phone that trusted the certificate does not have to trust it again.
|
||||
|
||||
| setting | env | default |
|
||||
|---|---|---|
|
||||
| LAN address nginx binds | `FFF_VTT_LAN_HOST` | detected LAN IPv4 (`ip -4 route get 1.1.1.1`) |
|
||||
| nginx TLS port | `FFF_VTT_LAN_PORT` | `8443` |
|
||||
| state directory | `FFF_VTT_STATE_DIR` | `run/lan` |
|
||||
|
||||
The certificate's SAN is the LAN address. If the laptop's address changes, `serve` regenerates the
|
||||
certificate (and prints the trust steps again). This is the playtest path, not the M6 deployment:
|
||||
no systemd unit, hardening or backups.
|
||||
|
||||
### Manual fallback: build it once
|
||||
|
||||
Everything below is what `devbox run serve` automates; use it when you need to arrange the
|
||||
processes yourself (or to see the paths involved).
|
||||
|
||||
|
||||
From the repo root, inside devbox:
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
"client-test": [
|
||||
"client/run-tests.sh"
|
||||
],
|
||||
"serve": [
|
||||
"tools/serve.sh"
|
||||
],
|
||||
"mutation": [
|
||||
"tools/mutation.sh"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// The `devbox run serve` stack (M4 #80): the real server on loopback behind the TLS/HTTP2 nginx
|
||||
// vhost of DESIGN 11.1, listening on the laptop's LAN address, with PERSISTENT state and TLS
|
||||
// material under one directory so a table survives Ctrl-C and a phone trusts the certificate once.
|
||||
//
|
||||
// This is the dev playtest path, not the M6 NixOS deployment: no systemd, no hardening, no
|
||||
// backups. It composes the pieces the test harnesses already use (tools/withserver.mjs for the
|
||||
// server, tools/nginx.mjs for the vhost, tools/tlsdev.mjs for the certificate) but with the knobs
|
||||
// those helpers need for the LAN: a non-loopback bind for nginx, a long-lived certificate whose
|
||||
// SAN is the LAN address, and a state dir it never deletes.
|
||||
//
|
||||
// The server itself still binds 127.0.0.1 (DESIGN 3.4 T15 / config.BindAddress): nginx is the only
|
||||
// LAN listener, so the playtest keeps the same trust boundary as production.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import net from 'node:net'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { projectRoot } from './lib.mjs'
|
||||
import { gmKeyOf, startServer, stopServer } from './withserver.mjs'
|
||||
import { startTestNginx, stopTestNginx } from './nginx.mjs'
|
||||
import { ensureCert } from './tlsdev.mjs'
|
||||
|
||||
export const DEFAULT_STATE_DIR = 'run/lan'
|
||||
export const DEFAULT_LAN_PORT = 8443
|
||||
export const DEFAULT_DIST = path.join(projectRoot, 'client', 'dist')
|
||||
export const DEFAULT_SERVER_BIN = path.join(projectRoot, 'run', 'fff-vtt')
|
||||
|
||||
const isIPv4 = s => /^\d{1,3}(\.\d{1,3}){3}$/.test(s)
|
||||
|
||||
// The LAN address a phone should dial. `ip route get` names the interface the default route uses,
|
||||
// which is the one a same-Wi-Fi phone can reach; networkInterfaces is the portable fallback.
|
||||
export function detectLanIp() {
|
||||
if (process.platform === 'linux') {
|
||||
const r = spawnSync('ip', ['-4', 'route', 'get', '1.1.1.1'], { encoding: 'utf8' })
|
||||
if (r.status === 0) {
|
||||
const m = /\bsrc\s+(\d{1,3}(?:\.\d{1,3}){3})\b/.exec(r.stdout)
|
||||
if (m && !m[1].startsWith('127.')) return m[1]
|
||||
}
|
||||
}
|
||||
const candidates = []
|
||||
for (const list of Object.values(os.networkInterfaces())) {
|
||||
for (const a of list ?? []) {
|
||||
if (a.family !== 'IPv4' || a.internal) continue
|
||||
candidates.push(a.address)
|
||||
}
|
||||
}
|
||||
const privateFirst = candidates.find(a => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(a))
|
||||
return privateFirst ?? candidates[0] ?? null
|
||||
}
|
||||
|
||||
// A port free on a specific interface (freePort() in lib.mjs probes loopback only, which does not
|
||||
// prove the LAN address can bind it).
|
||||
export async function freePortOn(host) {
|
||||
const srv = net.createServer()
|
||||
await new Promise((res, rej) => { srv.once('error', rej); srv.listen(0, host, res) })
|
||||
const { port } = srv.address()
|
||||
await new Promise(res => srv.close(res))
|
||||
return port
|
||||
}
|
||||
|
||||
function certSans(address) {
|
||||
return isIPv4(address) ? `IP:${address}` : `DNS:${address}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the playtest stack. Resolves once nginx answers /healthz on the LAN address.
|
||||
*
|
||||
* opts: { stateDir = 'run/lan', host = detectLanIp(), port = 8443, distDir = client/dist,
|
||||
* bin = run/fff-vtt, serverPort = <free loopback> }
|
||||
*
|
||||
* `host` is the nginx bind address. `0.0.0.0` binds every interface; the certificate and the
|
||||
* printed URL then use the detected LAN address. The server always listens on 127.0.0.1.
|
||||
*/
|
||||
export async function startLanServe(opts = {}) {
|
||||
const bindHost = opts.host ?? detectLanIp()
|
||||
if (!bindHost) {
|
||||
throw new Error('no non-loopback IPv4 address found; pass --host=<address> ' +
|
||||
'(or FFF_VTT_LAN_HOST) with the laptop\'s LAN IP')
|
||||
}
|
||||
const originAddress = bindHost === '0.0.0.0' ? (detectLanIp() ?? (() => {
|
||||
throw new Error('--host=0.0.0.0 needs a detected LAN address for the URL/certificate; ' +
|
||||
'pass the LAN IP explicitly instead')
|
||||
})()) : bindHost
|
||||
const stateDir = path.resolve(opts.stateDir ?? DEFAULT_STATE_DIR)
|
||||
const port = opts.port ?? DEFAULT_LAN_PORT
|
||||
const distDir = path.resolve(opts.distDir ?? DEFAULT_DIST)
|
||||
const bin = opts.bin
|
||||
if (bin !== undefined && !fs.existsSync(bin)) {
|
||||
throw new Error(`server binary missing at ${bin}: run \`devbox run serve\` (it builds the ` +
|
||||
`server and client first) or \`nim c ... -o:run/fff-vtt server/main.nim\``)
|
||||
}
|
||||
fs.mkdirSync(stateDir, { recursive: true })
|
||||
|
||||
// Persistent certificate: the phone trusts it once; a changed LAN address regenerates it (and the
|
||||
// caller is told to trust the new one again).
|
||||
const cert = ensureCert(path.join(stateDir, 'tls'), {
|
||||
subject: '/CN=fff-vtt lan',
|
||||
sans: certSans(originAddress),
|
||||
days: 825,
|
||||
})
|
||||
|
||||
const gmKey = gmKeyOf(stateDir, bin)
|
||||
const serverPort = opts.serverPort ?? await freePortOn('127.0.0.1')
|
||||
const publicOrigin = `https://${originAddress}:${port}`
|
||||
|
||||
const server = await startServer({ stateDir, port: serverPort, publicOrigin, bin })
|
||||
let nginx
|
||||
try {
|
||||
nginx = await startTestNginx({
|
||||
backendPort: server.port,
|
||||
stateDir,
|
||||
port,
|
||||
distDir,
|
||||
bindHost,
|
||||
serverName: originAddress,
|
||||
originHost: originAddress,
|
||||
certPath: cert.certPath,
|
||||
keyPath: cert.keyPath,
|
||||
tag: 'dev serve (LAN playtest)',
|
||||
})
|
||||
} catch (e) {
|
||||
await stopServer(server)
|
||||
throw e
|
||||
}
|
||||
|
||||
let stopped = false
|
||||
return {
|
||||
stateDir,
|
||||
host: originAddress,
|
||||
bindHost,
|
||||
port,
|
||||
origin: nginx.origin,
|
||||
publicOrigin,
|
||||
gmKey,
|
||||
certPath: cert.certPath,
|
||||
keyPath: cert.keyPath,
|
||||
certRegenerated: cert.regenerated,
|
||||
distDir,
|
||||
serverPort: server.port,
|
||||
server,
|
||||
nginx,
|
||||
async stop() {
|
||||
if (stopped) return
|
||||
stopped = true
|
||||
await stopTestNginx(nginx)
|
||||
await stopServer(server)
|
||||
},
|
||||
}
|
||||
}
|
||||
+27
-13
@@ -25,7 +25,7 @@ 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'
|
||||
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,
|
||||
@@ -37,12 +37,13 @@ function trustCert(certPath) {
|
||||
if (!current.includes(pem)) tls.setDefaultCACertificates([...current, pem])
|
||||
}
|
||||
|
||||
function config({ prefix, port, backendPort, stateDir, distDir, certPath, keyPath }) {
|
||||
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; test only
|
||||
return `# generated by tools/nginx.mjs; ${tag}
|
||||
daemon off;
|
||||
worker_processes 1;
|
||||
pid ${temp('nginx.pid')};
|
||||
@@ -71,12 +72,12 @@ http {
|
||||
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 127.0.0.1:${port} ssl;
|
||||
listen ${bindHost}:${port} ssl;
|
||||
http2 on;
|
||||
ssl_certificate ${certPath};
|
||||
ssl_certificate_key ${keyPath};
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
server_name localhost;
|
||||
server_name ${serverName};
|
||||
|
||||
location = /healthz { proxy_pass http://127.0.0.1:${backendPort}; }
|
||||
|
||||
@@ -135,11 +136,11 @@ http {
|
||||
`
|
||||
}
|
||||
|
||||
async function portIsFree(port) {
|
||||
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, '127.0.0.1', () => srv.close(() => resolve(true)))
|
||||
srv.listen(port, host, () => srv.close(() => resolve(true)))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -161,25 +162,38 @@ function probeHealth(origin) {
|
||||
// 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`)
|
||||
//
|
||||
// `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 })
|
||||
}
|
||||
const { certPath, keyPath } = ensureDevCert(path.join(prefix, 'tls'))
|
||||
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 }))
|
||||
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://127.0.0.1:${port}`, prefix, confPath, child, certPath, keyPath,
|
||||
distDir: docRoot,
|
||||
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` +
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env node
|
||||
// `devbox run serve` (M4 #80). tools/serve.sh builds the client dist and the server binary, then
|
||||
// exec's this script: it starts nginx on the LAN address in front of the loopback server, prints
|
||||
// the URL, the GM key and the certificate-trust steps, and blocks until Ctrl-C.
|
||||
//
|
||||
// Configuration (flags win over env, env wins over defaults):
|
||||
// --host=<ip|0.0.0.0> FFF_VTT_LAN_HOST default: detected LAN IPv4
|
||||
// --port=<n> FFF_VTT_LAN_PORT default: 8443 (nginx TLS listener)
|
||||
// --state-dir=<path> FFF_VTT_STATE_DIR default: run/lan (persistent, never deleted)
|
||||
// --dist=<path> FFF_VTT_LAN_DIST default: client/dist
|
||||
// --server-bin=<path> FFF_VTT_SERVER_BIN default: run/fff-vtt
|
||||
// --server-port=<n> FFF_VTT_SERVER_PORT default: a free loopback port
|
||||
import fs from 'node:fs'
|
||||
import { DEFAULT_DIST, DEFAULT_LAN_PORT, DEFAULT_SERVER_BIN, DEFAULT_STATE_DIR,
|
||||
detectLanIp, startLanServe } from './lanserve.mjs'
|
||||
|
||||
const USAGE = `usage: devbox run serve [-- --host=<ip>] [-- --port=<n>] [-- --state-dir=<path>]
|
||||
|
||||
Starts the FFF_vtt server behind a TLS/HTTP2 nginx on the LAN. State, GM key and certificate
|
||||
persist under the state dir (default ${DEFAULT_STATE_DIR}), so a session (and a trusted phone)
|
||||
survives Ctrl-C and a restart. Env equivalents: FFF_VTT_LAN_HOST, FFF_VTT_LAN_PORT,
|
||||
FFF_VTT_STATE_DIR.
|
||||
`
|
||||
|
||||
function parseArgs(argv) {
|
||||
const opts = {}
|
||||
for (const arg of argv) {
|
||||
if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0) }
|
||||
const m = /^--([a-z-]+)=(.*)$/.exec(arg)
|
||||
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
|
||||
const [, key, value] = m
|
||||
if (key === 'host') opts.host = value
|
||||
else if (key === 'port') opts.port = Number(value)
|
||||
else if (key === 'state-dir') opts.stateDir = value
|
||||
else if (key === 'dist') opts.distDir = value
|
||||
else if (key === 'server-bin') opts.bin = value
|
||||
else if (key === 'server-port') opts.serverPort = Number(value)
|
||||
else throw new Error(`unknown option --${key} (see --help)`)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
function envOptions() {
|
||||
const env = process.env
|
||||
const opts = {}
|
||||
if (env.FFF_VTT_LAN_HOST) opts.host = env.FFF_VTT_LAN_HOST
|
||||
if (env.FFF_VTT_LAN_PORT) opts.port = Number(env.FFF_VTT_LAN_PORT)
|
||||
if (env.FFF_VTT_STATE_DIR) opts.stateDir = env.FFF_VTT_STATE_DIR
|
||||
if (env.FFF_VTT_LAN_DIST) opts.distDir = env.FFF_VTT_LAN_DIST
|
||||
if (env.FFF_VTT_SERVER_BIN) opts.bin = env.FFF_VTT_SERVER_BIN
|
||||
if (env.FFF_VTT_SERVER_PORT) opts.serverPort = Number(env.FFF_VTT_SERVER_PORT)
|
||||
return opts
|
||||
}
|
||||
|
||||
function printStartup(handle) {
|
||||
const { origin, gmKey, stateDir, certPath, distDir, serverPort, certRegenerated } = handle
|
||||
const ip = handle.host
|
||||
const lines = [
|
||||
'',
|
||||
'FFF_vtt playtest server (Ctrl-C stops nginx and the server)',
|
||||
` URL: ${origin}`,
|
||||
` GM key: ${gmKey}`,
|
||||
` state: ${stateDir} (kept across restarts)`,
|
||||
` cert: ${certPath}`,
|
||||
` server: 127.0.0.1:${serverPort} (loopback only; nginx is the LAN face)`,
|
||||
'',
|
||||
`Open ${origin} on the phone (same Wi-Fi) and on the laptop.`,
|
||||
'',
|
||||
'Phone (Android Chrome), one-time per certificate:',
|
||||
` 1. Open ${origin} -> "Advanced" -> "Proceed to ${ip} (unsafe)".`,
|
||||
' 2. To drop the warning: push the certificate and install it as a user CA:',
|
||||
` adb push ${certPath} /sdcard/Download/fff-vtt-lan.crt`,
|
||||
' Settings > Security > Encryption & credentials > Install a certificate >',
|
||||
' CA certificate > CA Certificate > fff-vtt-lan.crt > Install anyway.',
|
||||
' Only the "Proceed" tap is required; installing the CA just silences the warning.',
|
||||
'',
|
||||
'Laptop, one-time per certificate:',
|
||||
` Linux: sudo cp ${certPath} /usr/local/share/ca-certificates/fff-vtt-lan.crt`,
|
||||
' sudo update-ca-certificates',
|
||||
` macOS: sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${certPath}`,
|
||||
' Firefox: Settings > Privacy & Security > Certificates > View Certificates >',
|
||||
' Authorities > Import > select cert.pem > "Trust this CA to identify websites".',
|
||||
' (Chrome/Edge on the laptop read the system store; Firefox keeps its own.)',
|
||||
'',
|
||||
]
|
||||
if (certRegenerated) {
|
||||
lines.push(`NOTE: the LAN address is new (${ip}); the certificate was regenerated. Trust it again.`, '')
|
||||
}
|
||||
if (!fs.existsSync(distDir)) {
|
||||
lines.push(`WARNING: no client build at ${distDir}; "/" will 404 until it is built.`, '')
|
||||
}
|
||||
lines.push('The certificate only names this LAN address; if the laptop\'s address changes,',
|
||||
'`devbox run serve` regenerates it and prints these steps again.', '')
|
||||
process.stdout.write(lines.join('\n') + '\n')
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const opts = { ...envOptions(), ...parseArgs(process.argv.slice(2)) }
|
||||
if (!opts.host) {
|
||||
const detected = detectLanIp()
|
||||
if (detected) opts.host = detected
|
||||
}
|
||||
const handle = await startLanServe({
|
||||
stateDir: opts.stateDir ?? DEFAULT_STATE_DIR,
|
||||
host: opts.host,
|
||||
port: opts.port ?? DEFAULT_LAN_PORT,
|
||||
distDir: opts.distDir ?? DEFAULT_DIST,
|
||||
bin: opts.bin ?? DEFAULT_SERVER_BIN,
|
||||
serverPort: opts.serverPort,
|
||||
})
|
||||
printStartup(handle)
|
||||
|
||||
let stopping = false
|
||||
const shutdown = async signal => {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
process.stdout.write(`\n${signal}: stopping nginx and the server...\n`)
|
||||
try {
|
||||
await handle.stop()
|
||||
process.stdout.write('stopped; state, GM key and certificate are on disk for the next run.\n')
|
||||
process.exit(0)
|
||||
} catch (e) {
|
||||
process.stderr.write(`shutdown failed: ${e.stack ?? e}\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
process.on('SIGINT', () => { shutdown('SIGINT') })
|
||||
process.on('SIGTERM', () => { shutdown('SIGTERM') })
|
||||
process.on('uncaughtException', e => { process.stderr.write(`${e.stack ?? e}\n`); shutdown('error') })
|
||||
process.on('unhandledRejection', e => {
|
||||
process.stderr.write(`${(e && e.stack) ?? e}\n`); shutdown('error')
|
||||
})
|
||||
}
|
||||
|
||||
main().catch(e => {
|
||||
process.stderr.write(`serve: ${e.stack ?? e}\n`)
|
||||
process.exit(1)
|
||||
})
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# devbox run serve (M4 #80): one command for a LAN playtest.
|
||||
#
|
||||
# Builds the server binary (run/fff-vtt) and the client dist (client/dist), then starts the
|
||||
# TLS/HTTP2 nginx on the LAN address in front of the loopback server and blocks. Ctrl-C stops both
|
||||
# processes. State, GM key and certificate live under the state dir (default run/lan) and are
|
||||
# reused by the next run.
|
||||
#
|
||||
# devbox run serve # detected LAN IP, port 8443, state run/lan
|
||||
# FFF_VTT_LAN_PORT=9443 devbox run serve
|
||||
# FFF_VTT_STATE_DIR=run/lan2 devbox run serve
|
||||
# FFF_VTT_LAN_HOST=192.168.1.50 devbox run serve # override the detected address
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
|
||||
STATE_DIR="${FFF_VTT_STATE_DIR:-run/lan}"
|
||||
mkdir -p "$STATE_DIR" run
|
||||
|
||||
# Dependencies (idempotent) and the server binary. The worktree-local nimcache is deliberate: Nim's
|
||||
# default cache is shared by every checkout, and two parallel worktrees corrupt each other.
|
||||
nimble install -d -y
|
||||
NIMBLE_PKGS="${NIMBLE_DIR:-.devbox/nimble}/pkgs2"
|
||||
nim c --hints:off --mm:orc --nimblePath:"$NIMBLE_PKGS" \
|
||||
--nimcache:run/nimcache/fff-vtt -o:run/fff-vtt server/main.nim
|
||||
|
||||
# The client build nginx serves at `/`.
|
||||
( cd client
|
||||
if [ ! -d node_modules ]; then npm ci --no-audit --no-fund; fi
|
||||
npm run build
|
||||
)
|
||||
|
||||
exec node tools/serve.mjs "$@"
|
||||
@@ -0,0 +1,158 @@
|
||||
// M4 #80: the LAN playtest composition. Starts the real server behind the real TLS/HTTP2 nginx on
|
||||
// the machine's LAN address (not loopback), proves h2 + a trusted TLS chain on `/healthz` and `/`,
|
||||
// a POST /join with the GM key, and a WebSocket upgrade on /ws; then Ctrl-C equivalent (stop),
|
||||
// restart on the same address, and proves the state dir, GM key and certificate came back
|
||||
// unchanged. Also asserts the server itself never listens off 127.0.0.1 (nginx is the LAN face).
|
||||
//
|
||||
// `/` is a stub dist here, exactly like tools/vhost.test.mjs: `devbox run test` must not need the
|
||||
// client's npm build (the real Vite output is exercised by `devbox run client-test` / `e2e`).
|
||||
// `devbox run serve` builds the real dist before calling the same stack.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import http2 from 'node:http2'
|
||||
import net from 'node:net'
|
||||
import path from 'node:path'
|
||||
import { listeningSockets } from './lib.mjs'
|
||||
import { makeStateDir, openAs } from './withserver.mjs'
|
||||
import { detectLanIp, freePortOn, startLanServe } from './lanserve.mjs'
|
||||
|
||||
const STUB_MARK = 'lan-serve smoke stub'
|
||||
|
||||
function writeStubDist(dir) {
|
||||
fs.mkdirSync(path.join(dir, 'assets'), { recursive: true })
|
||||
const indexHtml = `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><title>${STUB_MARK}</title></head>
|
||||
<body><p>${STUB_MARK}</p></body></html>
|
||||
`
|
||||
fs.writeFileSync(path.join(dir, 'index.html'), indexHtml)
|
||||
return { dir }
|
||||
}
|
||||
|
||||
// One HTTP/2 request over the LAN origin; resolves with the ALPN, TLS authorization, status/headers
|
||||
// and the UTF-8 body.
|
||||
function h2Request(origin, urlPath, { method = 'GET', body, headers = {} } = {}) {
|
||||
const client = http2.connect(origin)
|
||||
return new Promise((resolve, reject) => {
|
||||
client.once('error', reject)
|
||||
const sendHeaders = {
|
||||
':method': method,
|
||||
':path': urlPath,
|
||||
...headers,
|
||||
}
|
||||
if (body !== undefined) sendHeaders['content-length'] = Buffer.byteLength(body)
|
||||
const req = client.request(sendHeaders)
|
||||
let resHeaders = null
|
||||
const chunks = []
|
||||
req.setEncoding('utf8')
|
||||
req.on('response', h => { resHeaders = h })
|
||||
req.on('data', c => chunks.push(c))
|
||||
req.on('error', reject)
|
||||
req.on('end', () => {
|
||||
const result = {
|
||||
alpn: client.alpnProtocol,
|
||||
authorized: client.socket?.authorized === true,
|
||||
status: Number(resHeaders?.[':status']),
|
||||
headers: resHeaders,
|
||||
body: chunks.join(''),
|
||||
}
|
||||
client.close()
|
||||
resolve(result)
|
||||
})
|
||||
if (body !== undefined) req.end(body)
|
||||
else req.end()
|
||||
})
|
||||
}
|
||||
|
||||
async function canBind(host, port) {
|
||||
const srv = net.createServer()
|
||||
try {
|
||||
await new Promise((res, rej) => { srv.once('error', rej); srv.listen(port, host, res) })
|
||||
return true
|
||||
} catch { return false } finally {
|
||||
await new Promise(res => { try { srv.close(res) } catch { res() } })
|
||||
}
|
||||
}
|
||||
|
||||
test('serve: LAN TLS+h2 composition, /join, /ws, and persistent state across a restart', async () => {
|
||||
const lanIp = detectLanIp()
|
||||
assert.ok(lanIp, 'no non-loopback IPv4 address detected: this smoke test needs a LAN address ' +
|
||||
'(set FFF_VTT_LAN_HOST on a host where `ip route get 1.1.1.1` has no source)')
|
||||
const stateDir = makeStateDir('fffvtt-serve-')
|
||||
const dist = writeStubDist(path.join(stateDir, 'dist'))
|
||||
const port = await freePortOn(lanIp)
|
||||
let handle = null
|
||||
let restarted = null
|
||||
try {
|
||||
handle = await startLanServe({ stateDir, host: lanIp, port, distDir: dist.dir })
|
||||
assert.equal(handle.origin, `https://${lanIp}:${port}`)
|
||||
assert.equal(handle.publicOrigin, handle.origin)
|
||||
assert.match(handle.gmKey, /^[A-Z0-9]{4}(-[A-Z0-9]{4}){4}$/)
|
||||
const gmKey1 = handle.gmKey
|
||||
const cert1 = fs.readFileSync(handle.certPath, 'utf8')
|
||||
assert.match(cert1, /BEGIN CERTIFICATE/)
|
||||
|
||||
// The stack is reachable on the LAN address, over h2, with the TLS chain verified.
|
||||
const health = await h2Request(handle.origin, '/healthz')
|
||||
assert.equal(health.alpn, 'h2', 'ALPN must negotiate h2')
|
||||
assert.equal(health.authorized, true, 'TLS chain must verify against the served certificate')
|
||||
assert.equal(health.status, 200)
|
||||
assert.equal(health.body, '{"status":"ok"}')
|
||||
|
||||
const index = await h2Request(handle.origin, '/')
|
||||
assert.equal(index.alpn, 'h2')
|
||||
assert.equal(index.authorized, true)
|
||||
assert.equal(index.status, 200)
|
||||
assert.match(index.body, new RegExp(STUB_MARK))
|
||||
|
||||
// POST /join with the GM key, over the same LAN h2 origin.
|
||||
const joinBody = new URLSearchParams({ key: handle.gmKey }).toString()
|
||||
const joined = await h2Request(handle.origin, '/join', {
|
||||
method: 'POST',
|
||||
body: joinBody,
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
assert.equal(joined.status, 303, `join status body=${joined.body}`)
|
||||
const setCookie = joined.headers['set-cookie']
|
||||
const firstCookie = Array.isArray(setCookie) ? setCookie[0] : setCookie
|
||||
assert.match(String(firstCookie ?? ''), /^fff_session=[^;]+;/)
|
||||
|
||||
// The signed-in WebSocket upgrade on /ws through nginx (the credential is the join cookie).
|
||||
const gm = await openAs(handle.origin, handle.gmKey)
|
||||
await gm.ws.waitText('hello')
|
||||
await gm.ws.waitText('walls')
|
||||
gm.ws.close()
|
||||
await gm.ws.closed
|
||||
|
||||
// The server never listens on the LAN address: only 127.0.0.1, and only nginx holds the LAN port.
|
||||
const serverSockets = listeningSockets(handle.serverPort)
|
||||
assert.ok(serverSockets.length > 0, 'server should listen on its loopback port')
|
||||
for (const s of serverSockets) {
|
||||
assert.equal(s.addr, '127.0.0.1', `server leaked a ${s.addr} listener (DESIGN 3.4 T15)`)
|
||||
}
|
||||
const lanSockets = listeningSockets(port)
|
||||
assert.ok(lanSockets.some(s => s.addr === lanIp), `nginx should hold ${lanIp}:${port}`)
|
||||
|
||||
// Ctrl-C: both processes stop and the LAN port is released.
|
||||
await handle.stop()
|
||||
handle = null
|
||||
assert.equal(await canBind(lanIp, port), true, 'the LAN port must be released after stop')
|
||||
|
||||
// Restart on the same state dir + address: same GM key, same certificate, still works.
|
||||
restarted = await startLanServe({ stateDir, host: lanIp, port, distDir: dist.dir })
|
||||
assert.equal(restarted.gmKey, gmKey1)
|
||||
assert.equal(restarted.certPath, path.join(stateDir, 'tls', 'cert.pem'))
|
||||
assert.equal(fs.readFileSync(restarted.certPath, 'utf8'), cert1,
|
||||
'the certificate must persist so the phone trusts it once')
|
||||
const health2 = await h2Request(restarted.origin, '/healthz')
|
||||
assert.equal(health2.status, 200)
|
||||
const gm2 = await openAs(restarted.origin, restarted.gmKey)
|
||||
await gm2.ws.waitText('hello')
|
||||
gm2.ws.close()
|
||||
await gm2.ws.closed
|
||||
} finally {
|
||||
if (handle) await handle.stop()
|
||||
if (restarted) await restarted.stop()
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
+44
-16
@@ -1,45 +1,73 @@
|
||||
// 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.
|
||||
// The TLS material for the test nginx (#66, DESIGN 11.1 / TESTING 11.1) and the `serve` playtest
|
||||
// stack (M4 #80). 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, the
|
||||
// harnesses and a phone on the LAN 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 client/e2e/run.sh), and nginx loads the same pair. The SANs are what a client checks on loopback.
|
||||
// and client/e2e/run.sh), and nginx loads the same pair. For `devbox run serve` the same helper
|
||||
// writes a PERSISTENT pair under the state dir with the LAN IP in the SANs, so the phone trusts it
|
||||
// once and keeps trusting it across restarts.
|
||||
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'
|
||||
const SAN = 'DNS:localhost,IP:127.0.0.1'
|
||||
const DAYS = 3
|
||||
|
||||
function generate(dir) {
|
||||
function generate(dir, { subject, sans, days }) {
|
||||
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',
|
||||
'-nodes', '-sha256', '-days', String(days),
|
||||
'-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,
|
||||
'-subj', subject,
|
||||
// CA:TRUE so the pair is usable as a trust anchor (NODE_EXTRA_CA_CERTS, Android's user CA
|
||||
// store) as well as a leaf; serverAuth + digitalSignature so a browser/h2 client accepts it
|
||||
// as a TLS server certificate.
|
||||
'-addext', `subjectAltName=${sans}`,
|
||||
'-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 ` +
|
||||
throw new Error(`openssl could not generate the 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) {
|
||||
// reused, so a run's harness files start from the same anchor. The generation parameters are
|
||||
// recorded next to the pair: if a later call asks for different SANs (the laptop's LAN address
|
||||
// changed), the stale pair is regenerated instead of silently not matching the new address.
|
||||
export function ensureCert(dir, opts = {}) {
|
||||
const subject = opts.subject ?? SUBJECT
|
||||
const sans = opts.sans ?? SAN
|
||||
const days = opts.days ?? DAYS
|
||||
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)
|
||||
const stampPath = path.join(dir, '.cert-opts')
|
||||
const want = JSON.stringify({ subject, sans, days })
|
||||
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
||||
let have = null
|
||||
try { have = fs.readFileSync(stampPath, 'utf8') } catch {}
|
||||
if (have === want) return { certPath, keyPath, regenerated: false }
|
||||
// No stamp: an existing pair from an older helper. Reuse it; its defaults are the loopback
|
||||
// ones this function produced before.
|
||||
if (have === null && subject === SUBJECT && sans === SAN && days === DAYS) {
|
||||
return { certPath, keyPath, regenerated: false }
|
||||
}
|
||||
}
|
||||
const made = generate(dir, { subject, sans, days })
|
||||
fs.writeFileSync(stampPath, want)
|
||||
return { ...made, regenerated: true }
|
||||
}
|
||||
|
||||
// The test certificates: loopback SANs, short lifetime, one directory per run.
|
||||
export function ensureDevCert(dir) {
|
||||
return ensureCert(dir)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ export async function startServer(opts = {}) {
|
||||
const ownStateDir = opts.stateDir === undefined
|
||||
const stateDir = opts.stateDir ?? makeStateDir()
|
||||
const args = opts.args ?? []
|
||||
const bin = buildServer({ defines: opts.defines })
|
||||
const bin = opts.bin ?? buildServer({ defines: opts.defines })
|
||||
const port = opts.port ?? await freePort()
|
||||
const publicOrigin = opts.publicOrigin ?? baseUrl(port)
|
||||
refuseLivePort(port)
|
||||
@@ -130,8 +130,8 @@ const KEY_LINE = /GM key(?: \(new\))?: ([A-Z0-9-]+)/
|
||||
|
||||
// Runs `fff-vtt gm-key` against a state dir (the CLI is part of the product, so it is the source
|
||||
// of the GM key in every harness).
|
||||
export function runGmKey(stateDir, extra = []) {
|
||||
const r = spawnSync(buildServer(), ['gm-key', `--state-dir=${stateDir}`, ...extra], { encoding: 'utf8' })
|
||||
export function runGmKey(stateDir, extra = [], bin = buildServer()) {
|
||||
const r = spawnSync(bin, ['gm-key', `--state-dir=${stateDir}`, ...extra], { encoding: 'utf8' })
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr }
|
||||
}
|
||||
|
||||
@@ -143,8 +143,8 @@ export function parseGmKey(stdout) {
|
||||
}
|
||||
|
||||
// The GM key of a state dir, created on first call and stable afterwards.
|
||||
export function gmKeyOf(stateDir) {
|
||||
const r = runGmKey(stateDir)
|
||||
export function gmKeyOf(stateDir, bin = buildServer()) {
|
||||
const r = runGmKey(stateDir, [], bin)
|
||||
if (r.status !== 0) throw new Error(`gm-key failed: ${r.stderr}`)
|
||||
return parseGmKey(r.stdout)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user