tools: test nginx, generated tile fixtures and the tile group (#24)

This commit is contained in:
2026-11-15 12:30:51 +01:00
parent 669e47e1ba
commit 30512127b0
8 changed files with 859 additions and 5 deletions
+2
View File
@@ -1,4 +1,6 @@
.devbox/
# devbox package plugins (nginx, slice 9) regenerate these helper files on every shell; not source
devbox.d/
nix/
nimbledeps/
nimble.paths
+2 -1
View File
@@ -14,7 +14,8 @@
"out",
"bin"
]
}
},
"nginx": "latest"
},
"shell": {
"init_hook": [],
+216
View File
@@ -137,6 +137,171 @@
}
}
},
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
@@ -255,6 +420,57 @@
}
}
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
+12 -1
View File
@@ -22,6 +22,9 @@
# az: in-use not enforced | b1: player.remove forgets the characters | b2: an encountered rename
# overwrites a name the player never knew | b3: cprops carries the character owner bucket |
# b4: a player is sent every character
# slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate
# c1: a tile is allowed without any explored cell | c2: every overlapping cell is required
# c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical
# Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order.
# Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected
# test are run per mutation (control runs all). Debug build. Wrapped in systemd-inhibit (sleep:idle) when that works.
@@ -169,10 +172,18 @@ run b1 "player.remove forgets the characters" server/characters.nim 's/WHERE own
run b2 "an encountered rename overwrites a secret" server/characters.nim 's/AND actual_name <> .."""/AND 1 = 1"""/' "a character rename follows the snapshots"
run b3 "cprops carries the character owner bucket" server/views.nim 's/cpropsPublic: objectOf(if ch\.isSome and not ownsCharacter: ch\.get\.props\[pbPublic\]/cpropsPublic: objectOf(if ch.isSome and not ownsCharacter: ch.get.props[pbOwner]/' "cprops carries the character"
run b4 "a player is sent every character" server/views.nim 's/ if c\.owner != playerId: continue/ if false: continue/' "a player gets only its own characters"
# slice 9 (#24): the tile URL grammar and the access rule (server/tiles.nim)
TILE_GATE="an unexplored tile is refused|a tile is allowed when any overlapping cell"
TILE_ZERO="leading zero tile coordinates"
TILE_RANGE="outside the grid is out of range"
run c1 "the tile gate ignores the explored set" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if true: return true/' "$TILE_GATE"
run c2 "the tile gate needs every overlapping cell" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if sc.cellIndex(cx, cy) notin explored: return false/' "$TILE_GATE"
run c3 "an out-of-grid tile coordinate is accepted" server/tiles.nim 's/^ x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)$/ x >= 0 and y >= 0/' "$TILE_RANGE"
run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if raw\[0\] == '0' and raw.len > 1: return false/ discard/" "$TILE_ZERO"
wait
rc=0; : > "$LOG"
for id in control a b c d1 d2 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4; do
for id in control a b c d1 d2 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do
[ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG"
if [ -f "$T/$id/verdict" ]; then tee -a "$LOG" < "$T/$id/verdict"; [ "$(cat "$T/$id/rc")" = 0 ] || rc=1
else echo "$id: NO RESULT (job killed?)" | tee -a "$LOG"; rc=1; fi
+142
View File
@@ -0,0 +1,142 @@
// 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.
//
// 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
// /_tiles/ -> `internal` alias of <stateDir>/tiles/, so only an internal redirect reaches it
// /ws -> the backend upgrade
// The `/healthz` proxy is the readiness probe for the proxy itself.
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import net from 'node:net'
import path from 'node:path'
import { sleep } from './lib.mjs'
function config({ prefix, port, backendPort, stateDir }) {
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
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;
image/png png;
}
map $http_upgrade $conn_up { default upgrade; '' close; }
server {
listen 127.0.0.1:${port};
server_name localhost;
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 <state>/tiles/<scene>/v<art_version>/, 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}/;
}
}
}
`
}
async function portIsFree(port) {
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)))
})
}
// Starts nginx in front of `backendPort`. Resolves once the proxy answers /healthz. Stop it with
// stopTestNginx(); the config and logs live under <stateDir>/nginx/ for post-mortem greps.
export async function startTestNginx({ backendPort, stateDir, port }) {
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))
const confPath = path.join(prefix, 'nginx.conf')
fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir }))
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,
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 r = await fetch(`${handle.origin}/healthz`)
if (r.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 {} }
}
+95
View File
@@ -0,0 +1,95 @@
// Fixture map tiles, generated at test time (DESIGN 13 M3 "fixture tiles at 32 px generated at test
// time by a helper (not committed)", slice 9 / #24). Zero npm deps: the PNG writer uses node:zlib.
//
// The fixture is deliberately boring art: each 32 px tile is one solid colour derived from its
// coordinates, so a test can tell two tiles apart by their bytes and no image work is needed. Tiles
// land under <stateDir>/tiles/<scene>/v<art_version>/, the tree the test nginx aliases for
// /_tiles/ (3.3, 11.1).
import fs from 'node:fs'
import path from 'node:path'
import zlib from 'node:zlib'
const CRC_TABLE = (() => {
const table = new Int32Array(256)
for (let n = 0; n < 256; n++) {
let c = n
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
table[n] = c
}
return table
})()
function crc32(buf) {
let c = 0xffffffff
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8)
return (c ^ 0xffffffff) >>> 0
}
function chunk(type, data) {
const head = Buffer.alloc(4)
head.writeUInt32BE(data.length)
const body = Buffer.concat([Buffer.from(type, 'latin1'), data])
const crc = Buffer.alloc(4)
crc.writeUInt32BE(crc32(body))
return Buffer.concat([head, body, crc])
}
// A solid-colour 8-bit RGB PNG of `size` x `size` (filter 0 on every scanline).
export function pngBytes(size, rgb) {
const ihdr = Buffer.alloc(13)
ihdr.writeUInt32BE(size, 0)
ihdr.writeUInt32BE(size, 4)
ihdr[8] = 8 // bit depth
ihdr[9] = 2 // colour type: truecolour (RGB)
ihdr[10] = 0 // compression
ihdr[11] = 0 // filter
ihdr[12] = 0 // interlace
const row = Buffer.alloc(1 + size * 3)
for (let x = 0; x < size; x++) {
row[1 + x * 3] = rgb[0]
row[2 + x * 3] = rgb[1]
row[3 + x * 3] = rgb[2]
}
const raw = Buffer.concat(Array.from({ length: size }, () => row))
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', zlib.deflateSync(raw, { level: 6 })),
chunk('IEND', Buffer.alloc(0)),
])
}
export function isPng(buf) {
return Buffer.isBuffer(buf) && buf.length > 8 &&
buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
}
export function tileDir(stateDir, scene, artVersion) {
return path.join(stateDir, 'tiles', String(scene), `v${artVersion}`)
}
// Deterministic colour of a tile: distinct neighbours, stable across runs.
function colourOf(x, y) {
return [(x * 37 + y * 11) & 0xff, (x * 17 + y * 53) & 0xff, (x * 97 + y * 5) & 0xff]
}
// Writes the given [x, y] tiles (default size 32 px) and returns the paths.
export function writeTiles(stateDir, { scene = 1, artVersion = 1, size = 32, tiles }) {
const dir = tileDir(stateDir, scene, artVersion)
fs.mkdirSync(dir, { recursive: true })
const files = []
for (const [x, y] of tiles) {
const file = path.join(dir, `${x}_${y}.png`)
fs.writeFileSync(file, pngBytes(size, colourOf(x, y)))
files.push(file)
}
return files
}
// Writes every tile of the rectangle x0..x1 / y0..y1 (inclusive). The leak check enumerates the
// same rectangle, so every tile it expects to be allowed has real bytes behind the internal alias.
export function writeTileGrid(stateDir, { scene = 1, artVersion = 1, size = 32, x0, x1, y0, y1 }) {
const tiles = []
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) tiles.push([x, y])
return writeTiles(stateDir, { scene, artVersion, size, tiles })
}
+385
View File
@@ -0,0 +1,385 @@
// M3 slice 9 (#24): the map-tile gate through the real binary and the test nginx (DESIGN 3.3, 6.6,
// 10.1, 10.2, 11.1, 13 group "tiles"). This file is the group's leak check (d) and its smoke
// tile-steal checks:
// - every gate decision over a whole tile region is compared with an INDEPENDENT explored oracle
// (clear-segment sampling over the GM's walls and the player token's vision radius, no server
// cell code involved): allowed => the oracle can see a point in the cell, and a cell the oracle
// is sure about must be allowed;
// - a tile behind a wall and a tile of another player are refused; a player with no sight state
// gets nothing, while the GM gets any in-range tile;
// - direct /_tiles/ is 404 (nginx `internal`), malformed/out-of-range/stale-version paths are 404,
// an unauthenticated or unknown session is 403, and traversal shapes never reach a file.
// Fixture tiles come from tools/tilefixture.mjs, generated in the test's state dir; none is committed.
import test from 'node:test'
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 { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { isPng, pngBytes, tileDir, writeTileGrid, writeTiles } from './tilefixture.mjs'
// ---------------------------------------------------------------------------------------------
// A stack: real server + test nginx in front (the production shape of 11.1). The server's configured
// public origin is the nginx origin, so WS connections through the proxy pass the Origin check.
async function withTileStack(fn) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
const s = await startServer({ stateDir, publicOrigin: baseUrl(nginxPort) })
let ngx
try {
ngx = await startTestNginx({ backendPort: s.port, stateDir, port: nginxPort })
return await fn({ s, gmKey, ngx, stateDir })
} finally {
await stopTestNginx(ngx)
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
async function gmConnect(origin, gmKey) {
const conn = await openAs(origin, gmKey)
await conn.ws.waitText('hello')
const walls = await conn.ws.waitText('walls')
return { ...conn, scene: walls.scene, walls }
}
async function addWall(gm, fields) {
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
// The GM's wall effect frame is the truth source for the oracle (the connect snapshot predates it).
const frame = await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
return { ack, frame }
}
// A named player who controls one token with vision at (300, 300), radius 400, and a wall at x=400
// splitting the view. The player's explored grid is then produced by the server's own resync.
async function sceneWithVision(s, gmKey, ngx) {
const gm = await gmConnect(ngx.origin, gmKey)
const player = await createPlayer(gm.ws)
await namePlayer(ngx.origin, player.key, 'Alice')
const wall = await addWall(gm, { a: [400, 100], b: [400, 700], kind: 'wall' })
const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [300, 300], flags: { vision: true },
vision_radius: 400, controller: player.id,
descriptive_name: 'Alice', actual_name: 'Alice' })
assert.equal(created.ok, true, JSON.stringify(created))
const token = await gm.ws.waitFor(m => m.t === 'token' && m.id === created.id)
const seen = await openAs(ngx.origin, player.key)
await seen.ws.waitText('hello')
const explored = await seen.ws.waitFor(m => m.t === 'explored' && m.full === true)
return { gm, player, token, seenCtx: seen, explored, scene: gm.scene, artVersion: exploredArt(gm),
wallsFrame: { walls: [wall.frame] } }
}
// art_version is in the GM's hello (views.sceneBlock, DESIGN 6.1).
function exploredArt(gm) {
const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene)
return hello.scene.art_version
}
// ---------------------------------------------------------------------------------------------
// The independent explored oracle (DESIGN 10.2). Nothing here uses the server's explored cells: the
// inputs are the GM's wall truth, the token position and its vision radius. A cell is
// sure = holds a lattice point inside the inscribed 64-gon (radius*cos(pi/64) - 0.5 px) whose
// line of sight stays > 0.5 px away from every blocking wall -> the gate must allow it;
// maybe = holds a point within radius + 0.5 px that no blocking wall properly crosses -> a gate
// that allows the tile is not inventing disclosure.
const Tol = 0.5
function segDist(p, a, b) {
const ex = b.x - a.x
const ey = b.y - a.y
const l2 = ex * ex + ey * ey
const t = l2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2))
return Math.hypot(p.x - a.x - t * ex, p.y - a.y - t * ey)
}
function orient(a, b, c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
function properCross(p, q, a, b) {
const d1 = orient(p, q, a), d2 = orient(p, q, b), d3 = orient(a, b, p), d4 = orient(a, b, q)
return d1 * d2 < 0 && d3 * d4 < 0
}
function segGap(p, q, a, b) {
if (properCross(p, q, a, b)) return 0
return Math.min(segDist(p, a, b), segDist(q, a, b), segDist(a, p, q), segDist(b, p, q))
}
function blockingWalls(wallsFrame) {
return wallsFrame.walls
.filter(w => w.kind === 'wall' || w.open === false)
.map(w => ({ a: { x: w.a[0], y: w.a[1] }, b: { x: w.b[0], y: w.b[1] } }))
}
// sure/maybe for one tile-sized cell (tile_size == cell in v1, Q4).
function oracleCell({ o, radius, walls, cell, x, y }) {
const rin = radius * Math.cos(Math.PI / 64) - Tol
const x0 = x * cell, y0 = y * cell
let sure = false, maybe = false
const n = 16
for (let j = 0; j <= n && !(sure && maybe); j++) {
for (let i = 0; i <= n; i++) {
const p = { x: x0 + (cell * i) / n, y: y0 + (cell * j) / n }
const d = Math.hypot(p.x - o.x, p.y - o.y)
if (!maybe && d <= radius + Tol) {
let clear = true
for (const w of walls) if (properCross(o, p, w.a, w.b)) { clear = false; break }
if (clear) maybe = true
}
if (!sure && d <= rin) {
let clear = true
for (const w of walls) if (segGap(o, p, w.a, w.b) <= Tol) { clear = false; break }
if (clear) sure = true
}
if (sure && maybe) break
}
}
return { sure, maybe }
}
// The explored cells the player was sent (full RLE frame), for a self-consistency cross-check.
function exploredSet(frame) {
const set = new Set()
for (const row of frame.rle) {
const cy = row[0]
for (let i = 1; i < row.length; i += 2) {
for (let k = 0; k < row[i + 1]; k++) set.add(`${row[i] + k},${cy}`)
}
}
return set
}
const tileUrl = (scene, art, x, y) => `/tiles/${scene}/v${art}/${x}_${y}.png`
async function getTile(origin, path, cookie) {
return await fetch(`${origin}${path}`, { headers: cookie ? { Cookie: cookie } : {} })
}
// ---------------------------------------------------------------------------------------------
test('tile gate: leak check (d) matches the independent explored oracle', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
const ctx = await sceneWithVision(s, gmKey, ngx)
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const cell = scene.cell
const tile = scene.tile_size
assert.equal(tile, cell, 'v1 pins tile_size = cell = 32 (Q4)')
// Fixtures for the whole checked rectangle: every tile the gate may allow has real bytes behind
// the internal alias, so a 200 always has a body to compare.
const x0 = 0, x1 = 31, y0 = 0, y1 = 31
const files = writeTileGrid(stateDir, { scene: scene.id, artVersion: ctx.artVersion, size: tile,
x0, x1, y0, y1 })
assert.equal(files.length, (x1 - x0 + 1) * (y1 - y0 + 1))
const walls = blockingWalls(ctx.wallsFrame)
const o = { x: ctx.token.pos[0], y: ctx.token.pos[1] }
const radius = ctx.token.vision_radius
assert.equal(radius, 400)
const explored = exploredSet(ctx.explored)
const cookie = ctx.seenCtx.cookie
let requests = 0, allowed = 0, sureCount = 0, maybeCount = 0, maybeRefused = 0, failures = 0
const allowedSet = new Set()
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const vis = oracleCell({ o, radius, walls, cell, x, y })
if (vis.sure) sureCount++
if (vis.maybe) maybeCount++
const r = await getTile(ngx.origin, tileUrl(scene.id, ctx.artVersion, x, y), cookie)
requests++
const fail = msg => { failures++; assert.fail(`tile ${x},${y} (sure=${vis.sure} maybe=${vis.maybe}): ${msg}`) }
if (r.status === 200) {
allowed++
allowedSet.add(`${x},${y}`)
// allowed => the oracle can see something in the cell (no invented disclosure)
if (!vis.maybe) fail('allowed although the oracle cannot see any point in the cell')
const body = Buffer.from(await r.arrayBuffer())
if (!isPng(body)) fail('a 200 did not carry PNG bytes')
const want = fs.readFileSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), `${x}_${y}.png`))
if (!body.equals(want)) fail('served bytes are not the requested tile')
if (r.headers.get('x-accel-redirect') !== null) fail('X-Accel-Redirect leaked to the client')
if ((r.headers.get('cache-control') ?? '') !== 'private') fail('Cache-Control is not private')
} else if (r.status === 403) {
if (vis.sure) fail('refused although the oracle is sure the cell is visible')
if (vis.maybe) maybeRefused++
} else {
fail(`unexpected status ${r.status}`)
}
}
if (failures > 0) break
}
// Self-consistency: the gate's allowed set is exactly the explored cells of the region (the gate
// and the view use the same set; the independent check above is what proves the set is right).
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
assert.equal(allowedSet.has(`${x},${y}`), explored.has(`${x},${y}`),
`tile ${x},${y}: gate disagrees with the player's explored frame`)
}
}
// Coverage and the documented tolerance at the polygon edge (10.2: superset/subset with a
// stated tolerance; the rasterizer skips a cell touched only along its min-x/min-y line).
assert.ok(sureCount > 20, `the oracle sampled too little (sure=${sureCount})`)
assert.ok(allowed > 20, `the gate allowed too few tiles (allowed=${allowed})`)
assert.ok(maybeRefused <= Math.max(2, Math.floor(maybeCount * 0.02)),
`too many maybe-visible cells refused: ${maybeRefused}/${maybeCount}`)
// Negative control for the oracle itself: a far cell is neither sure nor maybe, the token's own
// cell is both. A checker that says "maybe" everywhere would prove nothing.
assert.deepEqual(oracleCell({ o, radius, walls, cell, x: 110, y: 110 }),
{ sure: false, maybe: false })
const own = oracleCell({ o, radius, walls, cell, x: 9, y: 9 })
assert.equal(own.sure, true)
assert.equal(own.maybe, true)
// A wall is real: cells just behind it (x=13..15, y=9, right of x=400) are out of sight.
for (const bx of [14, 15]) {
assert.equal(oracleCell({ o, radius, walls, cell, x: bx, y: 9 }).maybe, false,
`cell ${bx},9 is behind the wall and must not be visible`)
}
console.log(`tile leak (d): ${requests} requests, ${allowed} allowed, ${sureCount} sure, ` +
`${maybeRefused} maybe-refused, ${failures} failures`)
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
test('tile gate: refusals, direct /_tiles, malformed and out-of-range paths', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
const ctx = await sceneWithVision(s, gmKey, ngx)
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
writeTiles(stateDir, { scene: scene.id, artVersion: ctx.artVersion,
tiles: [[9, 9], [110, 110], [127, 127]] })
const ok = tileUrl(scene.id, ctx.artVersion, 9, 9)
const unseen = tileUrl(scene.id, ctx.artVersion, 110, 110)
// The GM's own session is the differential control for every refusal below.
const gmCookie = ctx.gm.cookie
assert.equal((await getTile(ngx.origin, ok, gmCookie)).status, 200)
assert.equal((await getTile(ngx.origin, unseen, gmCookie)).status, 200)
assert.equal((await getTile(ngx.origin, tileUrl(scene.id, ctx.artVersion, 127, 127), gmCookie)).status,
200, 'the GM may have the last tile of the grid')
// Session rules: no cookie / unknown cookie / another player -> 403 on a tile Alice can see.
assert.equal((await getTile(ngx.origin, ok)).status, 403, 'no session is refused')
assert.equal((await getTile(ngx.origin, ok, 'fff_session=' + '0'.repeat(64))).status, 403,
'an unknown session is refused')
const bob = await createPlayer(ctx.gm.ws)
const bobSigned = await namePlayer(ngx.origin, bob.key, 'Bob')
const bobCookie = bobSigned.cookie
assert.equal((await getTile(ngx.origin, ok, bobCookie)).status, 403,
'another player cannot fetch Alice\'s tile')
// negative control: Bob may fetch his own explored tile once he has sight
const bobSeen = await openAs(ngx.origin, bob.key)
await bobSeen.ws.waitText('hello')
await bobSeen.ws.waitFor(m => m.t === 'explored' && m.full === true)
assert.equal((await getTile(ngx.origin, ok, bobSeen.cookie)).status, 403,
'a player with no vision token still has nothing explored')
bobSeen.ws.close()
// Direct /_tiles/ is internal: 404 even though the file exists, for every identity.
assert.ok(fs.existsSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), '9_9.png')))
for (const cookie of [undefined, ctx.seenCtx.cookie, gmCookie]) {
assert.equal((await getTile(ngx.origin, `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`, cookie)).status,
404, 'the internal alias is not reachable directly')
}
assert.equal((await getTile(ngx.origin, '/_tiles/')).status, 404)
// The gate's own answer, directly from Nim (before nginx consumes it).
const gate = await getTile(s.origin, ok, ctx.seenCtx.cookie)
assert.equal(gate.status, 200)
assert.equal(gate.headers.get('x-accel-redirect'), `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`)
assert.equal(gate.headers.get('cache-control'), 'private')
assert.equal((await gate.text()), '', 'Nim sends the decision, not the bytes')
const refused = await getTile(s.origin, unseen, ctx.seenCtx.cookie)
assert.equal(refused.status, 403)
assert.equal(refused.headers.get('x-accel-redirect'), null)
// Malformed components: 404 whatever the session (the URL is parsed first), including for the GM.
const malformed = [
`/tiles/${scene.id}/v${ctx.artVersion}/00_0.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/0_01.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/+1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.PNG`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.png.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1`,
`/tiles/${scene.id}/v${ctx.artVersion}/1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1_2.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1__1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/_1_1.png`,
`/tiles/${scene.id}/v01/1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}x/1_1.png`,
`/tiles/${scene.id}/${ctx.artVersion}/1_1.png`,
`/tiles/0${scene.id}/v${ctx.artVersion}/1_1.png`,
`/tiles/${scene.id}/v9999999999/1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/123456_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.png/extra`,
]
for (const p of malformed) {
assert.equal((await getTile(ngx.origin, p, ctx.seenCtx.cookie)).status, 404, p)
assert.equal((await getTile(ngx.origin, p, gmCookie)).status, 404, `${p} (GM)`)
}
// Out of range, wrong scene and a stale art version: 404.
for (const p of [
tileUrl(scene.id, ctx.artVersion, 128, 0),
tileUrl(scene.id, ctx.artVersion, 0, 128),
tileUrl(scene.id, ctx.artVersion, 99999, 9),
tileUrl(scene.id, ctx.artVersion + 1, 9, 9),
tileUrl(scene.id + 1, ctx.artVersion, 9, 9),
]) {
assert.equal((await getTile(ngx.origin, p, ctx.seenCtx.cookie)).status, 404, p)
assert.equal((await getTile(ngx.origin, p, gmCookie)).status, 404, `${p} (GM)`)
}
// Traversal and encoding shapes never produce a file: the gate parses integers and builds the
// internal path itself (T12). Encoded slashes survive URL normalisation and reach the server.
for (const p of [
`/tiles/${scene.id}/v${ctx.artVersion}/..%2f..%2f..%2fstate.db`,
`/tiles/${scene.id}/v${ctx.artVersion}/%2e%2e%2f%2e%2e%2fstate.db`,
`/tiles/${scene.id}/v${ctx.artVersion}/9_9.png%00`,
`/tiles/${scene.id}/v${ctx.artVersion}/..%5c..%5cstate.db`,
]) {
const r = await getTile(ngx.origin, p, ctx.seenCtx.cookie)
assert.ok([400, 404].includes(r.status), `${p} -> ${r.status}`)
}
// A method that is not GET is never a tile (mummy's router answers 405 for the known path).
assert.ok([404, 405].includes((await fetch(`${ngx.origin}${ok}`, { method: 'POST',
headers: { Cookie: ctx.seenCtx.cookie } })).status))
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
test('fixture tiles are generated by the helper and none is committed', async () => {
// The repo owns no PNG: tiles are generated per test into a state dir (DESIGN 13 M3).
const tracked = spawnSync('git', ['ls-files', '*.png'], { cwd: projectRoot, encoding: 'utf8' })
assert.equal(tracked.status, 0, tracked.stderr)
assert.equal(tracked.stdout.trim(), '', `committed PNG fixtures found:\n${tracked.stdout}`)
const stateDir = makeStateDir()
try {
const one = writeTiles(stateDir, { scene: 1, artVersion: 1, tiles: [[3, 4]] })
assert.equal(one.length, 1)
assert.equal(path.dirname(one[0]), tileDir(stateDir, 1, 1))
assert.ok(path.relative(projectRoot, one[0]).startsWith('..'), 'the fixture is outside the repo tree')
const bytes = fs.readFileSync(one[0])
assert.ok(isPng(bytes))
assert.equal(bytes.readUInt32BE(16), 32, '32 px tiles (DESIGN 3.3, #24)')
assert.equal(bytes.readUInt32BE(20), 32)
// two tiles differ, so a byte comparison in a test means something
const other = writeTiles(stateDir, { scene: 1, artVersion: 1, tiles: [[3, 5]] })
assert.ok(!bytes.equals(fs.readFileSync(other[0])))
// the writer itself emits a signature and the pinned dimensions
assert.ok(isPng(pngBytes(32, [1, 2, 3])))
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
+5 -3
View File
@@ -61,23 +61,25 @@ async function waitForHealth(handle) {
}
// Starts the server and waits for /healthz. Resolves to a handle; stopServer() tears it down.
// `defines` selects a build variant (e.g. a -d:leakfault build), `env` extra environment for it.
// `defines` selects a build variant (e.g. a -d:leakfault build), `env` extra environment for it,
// `publicOrigin` overrides the configured origin (a test nginx in front of the server).
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 port = opts.port ?? await freePort()
const publicOrigin = opts.publicOrigin ?? baseUrl(port)
refuseLivePort(port)
fs.mkdirSync(stateDir, { recursive: true })
const logPath = path.join(stateDir, 'server.log')
const logFd = fs.openSync(logPath, 'a')
const child = spawn(bin, [`--port=${port}`, `--state-dir=${stateDir}`,
`--public-origin=${baseUrl(port)}`, ...args],
`--public-origin=${publicOrigin}`, ...args],
{ cwd: projectRoot, stdio: ['ignore', logFd, logFd],
env: { ...process.env, ...(opts.env ?? {}) } })
const handle = {
port, origin: baseUrl(port), stateDir, dbPath: path.join(stateDir, 'state.db'),
port, origin: baseUrl(port), publicOrigin, stateDir, dbPath: path.join(stateDir, 'state.db'),
logPath, child, log: () => fs.readFileSync(logPath, 'utf8'),
}
try {