Files
FFF_vtt_frozen/prototype-server-vision
..

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: visibility, moves, cells, seed sanity)
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 run/leak-transcript.jsonl
devbox run concurrency 60 s (DUR= secs) A, B, GM(6 monsters + doors) at 20-50 ms per token
devbox run bench vision microbench

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 vision polygon equals the recomputed one (1e-6); A's explored set == recomputed set.
  • (c) remove arrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes.
  • (d) 256 tiles requested at 40+ points (10240 requests, 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:B on others' tokens, hello tokens == ["A"], no error msgs. Negative control done once by hand: injecting an out-of-vision token / a 200 for an unexplored tile into the transcript is flagged.

Result: PASS (220 gseq groups, 465 A msgs, 4 other tokens seen, 6 removes, tiles 1792 x 200 / 8448 x 403, 2163 explored cells, 0 failures).

Concurrency result (60 s, PASS)

Load was ~225 intents/s (A 28, B 28, 6 monsters 169) + door toggles every 1-3 s. 13876 mutations, 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), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot.

Measurements (laptop, release build, localhost)

metric avg p95 worst
vision recompute per player move (server, incl. cellsTouched + diff) 0.75 ms - 2.6 ms
vision recompute per monster move 0.000 ms (no vision) - 0.005 ms
door toggle (2 roles) 0.10 ms - 0.15 ms
bench: 1 visibility polygon 0.036 ms - 0.13 ms
bench: 6 polygons 0.20 ms - 0.29 ms
bench: 1 poly + cellsTouched 0.67 ms - 1.8 ms
bench: 6 polys + cellsTouched 4.7 ms - 7.3 ms
latency intent -> ack (sender, via nginx) 0.92 ms 1.98 ms 13.9 ms
latency intent -> arrival at other clients 1.26 ms 2.37 ms 11.2 ms

Bytes per delivery (only recipients that got something):

mutation recipient avg B
monster move GM 243
monster move player who sees it 147
player move the mover (ack + token + new vision + explored diff) 3470-3710 (worst 5.0 KB)
player move GM 144
door toggle GM 44

"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.2 ms polys, 4.7 ms with cell marking). 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 known map gives correct enter/leave (token/remove) and a fresh connection gets full state; clients reset on hello.
  • Tile gating via nginx internal + X-Accel-Redirect after 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.send appends the encoded frame to one server-wide deque under sendQueueLock and 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, ~14k mutations, ~40k messages: no crash, no reorder, no loss, consistent final views.
  • Caveats: WebSocket has 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 ms/move). 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 ~15x costlier than the polygon itself 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 vision polygon resent on each player move (~3.3 KB of the ~3.5 KB); 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 Text per token is heavy vs BitmapText at 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.