Server-authoritative vision prototype (throwaway)
Question: can the server alone decide what each player sees (tokens, fog, map tiles) so a modified client learns nothing hidden? Stack: Nim + mummy (WS/HTTP), SQLite, nginx (static + X-Accel-Redirect tiles), Vite + TS + Pixi v8 client.
Run (everything through devbox)
devbox run gen # data/scene.json + data/tiles/*.png (deterministic, hand-authored layout)
devbox run client # npm install, reducer test, tsc + vite build -> client/dist
PORT=8088 devbox run server # :9000 backend, prints invite links, writes run/invites.txt
PORT=8088 devbox run nginx # public port; separate terminal
PORT (default 8080) is only the public nginx port and the origin printed in invite links. On the dev box 8080 is taken by unrelated docker, hence 8088 in all examples.
Open the 3 invite links (gm, A, B) each in a separate browser or profile. The link sets cookie sid=<secret> (HttpOnly, SameSite=Strict) and redirects to /; the WS and tile requests authenticate by that cookie. One cookie jar = one identity, so two links in the same profile overwrite each other. Same cookie in two tabs = same player (shared vision, both connections synced).
Browser rendering was NOT verified (no browser in the build environment): only HTTP/WS behaviour is scripted-tested (served /, JS bundle 200, join -> cookie, WS through nginx, tiles).
Tests
| cmd | what |
|---|---|
devbox run test |
regen map + nimble test (geometry), smoke, leaktest, faulttest, restart, concurrency (DUR=15) |
devbox run client |
includes client reducer test (npm run check, incl. reconnect reset) |
devbox run smoke |
fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks |
devbox run leaktest |
runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (tools/leakcheck.nim) replays the transcript. Output per subject: results/leak-A.log, results/leak-B.log (committed), transcripts results/leak-{A,B}.jsonl (1.1-1.3 MB, gitignored) |
devbox run faulttest |
deliberate leaks: builds the server with -d:leakfault (hook absent from the normal build, asserted by grepping the clean binary for LEAK_FAULT), injects 8 faults one at a time (LEAK_FAULT=): hidden token sent (hidden), wall data to player (walls), unexplored tile 200 (tile), visible token withheld (withhold), B's vision / explored / ownership sent to A (other-vision, other-explored, other-owner), missing remove (noremove). Passes only if the checker fails each with exactly the expected failure-class set (classes: HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE, plus collateral OWN_VIEW / EXPLORED) and the clean build still passes. Details in results/faults.log (gitignored) |
devbox run restart |
isolated server, moves A/B/monsters, toggles doors, A explores a new area; stops with SIGTERM then (second round of changes) SIGKILL, restarts on the same DB; asserts invite secrets, token positions, doors, vision, explored grids per role and the full hello+state a reconnecting client receives are identical (gseq excluded: in-memory). Note: the server has no SIGTERM handler, so SIGTERM is as abrupt as SIGKILL; durability rests on the SQLite WAL commit before ack (synchronous=NORMAL: survives process kill, may lose the last commits on OS crash/power loss; see results/spike-investigation.md) |
devbox run concurrency |
60 s (DUR= secs) A, B, GM(6 monsters + doors) at 20-50 ms per token; logs results/concurrency-<DUR>s.log + ...-server.log (server STATS) |
devbox run mutation |
geometry mutation check on a temp copy (tools/mutation.sh): (a) no ±RayEps rays, (b) upper segment end exclusive, (c) lower end exclusive; control must pass, each mutation must fail a corner test. Logs results/mutation-{a,b,c}.log |
devbox run bench |
vision microbench, log results/bench.log |
Tests are isolated: tools/withserver.sh uses run/test/ (own DB, invites, nginx conf/logs) and ports 18088 (nginx) / 19000 (server), overridable via TEST_PORT/TEST_BACKEND_PORT; the live session on 8088/9000 and run/ are never touched. Server stats print on stop into run/test/server.log.
Leak test asserts
Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored is recomputed with geometry.nim, never from A's own messages. Per gseq:
- (a) A receives only hello/vision/explored/token/remove/moveAck; no wall-like keys (walls, door, open, a, b, segments...) anywhere.
- (b) every token A is sent is inside the independently computed polygon (0.5 px boundary tolerance); every token inside it IS in A's view (completeness); view positions == truth; A's
visionpolygon equals the recomputed one (1e-6); A's explored set == recomputed set. - (c)
removearrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes. - (d) 256 tiles requested per sweep (A: 39 sweeps = 9984 requests, B: 29 = 7424; incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403.
- (e) A never gets B-bound info: no B string outside token/remove, no
by:Bon others' tokens, hello tokens == ["A"], no error msgs. Negative control: automated,devbox run faulttest(above).
Result (results/leak-A.log): PASS (218 gseq groups, 467 A msgs, 4 other tokens seen, 4 removes, tiles 1709 x 200 / 8275 x 403, 2142 explored cells, 0 failures).
Result (results/leak-B.log): PASS (218 gseq groups, 217 B msgs, 3 other tokens seen, 3 removes, tiles 686 x 200 / 6738 x 403, 1114 explored cells, 0 failures).
Concurrency result (60 s, PASS; results/concurrency-60s.log)
Load was ~223 intents/s (A 28, B 28, 6 monsters 167; results/concurrency-60s.log) + door toggles every 1-3 s. 13781 mutations (10300 monster + 3421 player moves + 60 doors; results/concurrency-60s-server.log, = final gseq in the log), no crash, 0 errors, gseq never went backwards at any client (non-decreasing; messages of one mutation share a gseq), every intent acked (sent == acks for all 3 clients; nacks = blocked random-walk moves: GM 64, A 17, B 0), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot.
Measurements (laptop, release build, localhost)
Sources: C = results/concurrency-60s.log, S = results/concurrency-60s-server.log (server STATS), B = results/bench.log.
| metric | avg | p95 | worst | source |
|---|---|---|---|---|
| vision recompute per player move (server, incl. cellsTouched + diff) | 1.16 ms | - | 14.0 ms | S vision_ms move-player |
| vision recompute per monster move | 0.000 ms (no vision) | - | 0.025 ms | S vision_ms move-monster |
| door toggle (2 roles) | 0.19 ms | - | 0.49 ms | S vision_ms door |
| bench: 1 visibility polygon | 0.038 ms | - | 0.19 ms | B |
| bench: 6 polygons | 0.21 ms | - | 0.29 ms | B |
| bench: 1 poly + cellsTouched | 0.46 ms | - | 1.2 ms | B |
| bench: 6 polys + cellsTouched | 3.0 ms | - | 5.1 ms | B |
| latency intent -> ack (sender, via nginx) | 6.33 ms | 11.58 ms | 583 ms | C |
| latency intent -> arrival at other clients | 7.22 ms | 12.89 ms | 583 ms | C |
Bytes per delivery (only recipients that got something; S bytes/delivery):
| mutation | recipient | avg B |
|---|---|---|
| monster move | GM | 243 |
| monster move | player who sees it | 145 (A) - 148 (B) |
| player move | the mover (ack + token + new vision + explored diff) |
3181 (B) - 3679 (A) (worst 4.9 KB) |
| player move | GM | 145 |
| door toggle | GM | 45 |
"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.21 ms polys, 3.0 ms with cell marking; B). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players.
Findings
Worked
- Server-only filtering is simple under one global lock: validate -> mutate -> recompute -> persist -> per-connection diff -> send. Players never receive walls/doors/other tokens; leak test finds nothing.
- Per-connection
knownmap gives correct enter/leave (token/remove) and a fresh connection gets full state; clients reset onhello. - Token radius
tokenRadius(20 px, data/scene.json via tools/genmap.mjs) is server-authoritative and sent inhello(client falls back to 20 if absent). A move is accepted only if the centre path crosses no blocking wall AND the destination circle is >= r from every blocking wall (open doors ignored). Only the destination is checked, so a token already overlapping a wall (closed door, legacy DB) can leave. Vision origin stays the token centre. - Tile gating via nginx
internal+X-Accel-Redirectafter Nim checks explored cells;/_tiles/unreachable directly. - Moves: inclusive segment test blocks squeezing through shared vertices; non-owned/malformed moves get
error(not an ack, an ack would echo the position of an unseen token).
Edge cases that broke (see NOTES.md): cellsTouched missed polygons wholly inside one cell (fix: vertex-in-cell test); client did not reset on reconnect (fix: reset on hello); door id 0 falsy check; leak scenario steps crossing walls diagonally (scenario bug, server correctly refused).
mummy suitability
- Send is thread-safe by construction:
WebSocket.sendappends the encoded frame to one server-wide deque undersendQueueLockand triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, 13781 mutations, ~36k messages (C): no crash, no reorder, no loss, consistent final views. - Caveats:
WebSockethas no==/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1.2 ms/player move, S). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows). - Pinned to an exact commit (no tags upstream).
Worries for a real VTT
- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~12x costlier than the polygon itself (0.46 vs 0.038 ms, B) and dominates.
- Explored grid: 128x128 cells here; explored set sent whole on connect, kept in memory + one SQLite row per cell. Larger maps need run-length/bitmap + per-tile summaries.
- Full
visionpolygon resent on each player move (most of the ~3.2-3.7 KB per mover delivery); needs deltas or lower-res polygons. - Cookie = the secret (bearer, no rotation/expiry); invite links in logs/URLs are credentials. HTTPS needed beyond localhost.
- Tiles do not update when a door changes (static art; only fog changes); a revealed tile stays visible forever and leaks the whole tile (256 px), not just the explored cells; tile granularity vs exploredCell is a leak/size tradeoff.
- Polygon boundary epsilon: ray nudges (1e-4 rad) and inclusive tolerances; tokens right on the boundary are ambiguous (tests use a 0.5 px tolerance). A token standing exactly on a wall cannot move off it; server must keep tokens off walls.
- Fog masks are Graphics that grow unbounded (explored rects re-tessellated); needs baking to a RenderTexture. Pixi
Textper token is heavy vsBitmapTextat scale. - Browser rendering (fog masks, drag, reconnect visuals) is unverified: only the reducer and HTTP/WS paths were tested.
- Timing trusts a single machine/loopback; latencies exclude real network and client render.