Files
FFF_vtt_frozen/tools/serve.mjs
T
SirStone 9c7f9de910 feat(m4): playtest friction: perf overlay, fresh import, token seed (#82)
Opt-in ?perf=1 overlay (fps, frame p50/p95, JS p50/p95, tokens, zoom; no node or ticker work when off). fff-vtt import creates and migrates a fresh/empty state dir through the shared server startup path; devbox run serve gains --image. devbox run seed creates deterministic labelled NPC tokens over the real WS (idempotent rerun, --replace), and the GM token form defaults X/Y to the viewport centre.
2026-11-21 17:20:05 +01:00

187 lines
8.4 KiB
JavaScript

#!/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
// --image=<file> FFF_VTT_LAN_IMAGE import this map before the server starts (#82);
// the import runs offline and refuses (exit 3) if a server holds the lock
// --tile-size=<px> FFF_VTT_LAN_TILE optional for --image (64 is the playtest fallback)
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
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>]
[-- --image=<file> [-- --tile-size=<px>]]
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.
--image imports a PNG/WebP map before starting (a fresh state dir is created and migrated first)
and then serves the imported scene; a server already holding the state-dir lock is refused (exit 3).
`
const VALUE_OPTIONS = new Set(
['host', 'port', 'state-dir', 'dist', 'server-bin', 'server-port', 'image', 'tile-size'],
)
function parseArgs(argv) {
const opts = {}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
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 = m[1]
if (!VALUE_OPTIONS.has(key)) throw new Error(`unknown option --${key} (see --help)`)
let value = m[2]
if (value === undefined) {
if (i + 1 >= argv.length) throw new Error(`--${key}: missing value (see --help)`)
value = argv[++i]
}
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 if (key === 'image') opts.image = value
else if (key === 'tile-size') opts.tileSize = Number(value)
}
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)
if (env.FFF_VTT_LAN_IMAGE) opts.image = env.FFF_VTT_LAN_IMAGE
if (env.FFF_VTT_LAN_TILE) opts.tileSize = Number(env.FFF_VTT_LAN_TILE)
return opts
}
/**
* `--image`: run the offline import before the server exists. Import creates and migrates a fresh
* state dir through the server's startup path, and refuses (exit 3) while a server holds the lock,
* so `serve` never starts a stack on top of a half-imported scene.
*/
function importImage(opts, stateDir) {
const bin = path.resolve(opts.bin ?? DEFAULT_SERVER_BIN)
if (!fs.existsSync(bin)) {
throw new Error(`server binary missing at ${bin}: run \`devbox run serve\` (it builds the ` +
'server first), or pass --server-bin')
}
const args = ['import', `--state-dir=${stateDir}`, `--image=${path.resolve(opts.image)}`]
if (Number.isFinite(opts.tileSize)) args.push(`--tile-size=${opts.tileSize}`)
process.stdout.write(`serve: importing ${opts.image} before starting the server...\n`)
const r = spawnSync(bin, args, { stdio: 'inherit', cwd: process.cwd() })
if (r.error) throw r.error
if (r.status !== 0) {
const error = new Error(`map import failed (exit ${r.status}); the server was not started`)
error.exitCode = r.status ?? 1
throw error
}
}
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 stateDir = path.resolve(opts.stateDir ?? DEFAULT_STATE_DIR)
if (opts.image) importImage(opts, stateDir)
const handle = await startLanServe({
stateDir,
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(e.exitCode ?? 1)
})