docs: point DESIGN §3-§4 at TESTING for their proofs

Security and server sections keep the rules; measured runs, oracle citations,
test pins and the threat table's Test column move to TESTING §3.1, §3.3, §3.4,
§4.1-§4.4.
This commit is contained in:
2026-11-17 23:21:16 +01:00
parent 39615afdf6
commit 6837bbcf11
+54 -61
View File
@@ -8,7 +8,9 @@ Section numbers are unchanged, so every existing `DESIGN §x.y` reference still
now holds only open items. The durable reasoning behind the non-obvious rules lives in
[`docs/adr/`](adr/); the change log, the dated owner-decision log (Q1-Q24) and all superseded
statements are in [`docs/DESIGN-history.md`](DESIGN-history.md), which is **not normative**.
Audience: the owner and coding agents.
The proofs live in [`docs/TESTING.md`](TESTING.md): every rule here that has a test, oracle, fault
class or gate names it there, organised by this file's section numbers. Audience: the owner and coding
agents.
Legend:
- **[FIXED]** owner decision, not up for debate here.
@@ -187,8 +189,8 @@ entitled to.
| Global activity counters (`gseq`) | yes | **no**: per-connection counter only | -- |
Notes:
- `gm_only` is enforced in the view builder, before any frame is built; fault class `GMONLY_TOKEN`
(10.3).
- `gm_only` is enforced in the view builder, before any frame is built. Proven by: TESTING §3.1
(fault class `GMONLY_TOKEN`).
- Players get a per-connection monotonic counter `n`, never a global one; a gap in `n` reveals
nothing about hidden mutations (6.4).
- `hello` to a player carries world size, tile size, explored cell size, scene default token and
@@ -285,20 +287,17 @@ Notes:
`404`), checks the session's explored grid (the explored-area logic of 5.1), and answers `200`
with `X-Accel-Redirect: /_tiles/<scene>/v<art_version>/<x>_<y>.png`, or `403` if unexplored
[FIXED, owner decision 2026-11-14, #7]. nginx serves the bytes from an `internal` location; direct
hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README "Phase
2a"].
hits on `/_tiles/` give 404 (MEASURED in the prototype; TESTING §3.3).
- GM is always allowed.
- Rule: a tile is allowed iff at least one explored cell of that player overlaps it [MEASURED
semantics: leak test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`,
`results/leak-B.log`].
- Rule: a tile is allowed iff at least one explored cell of that player overlaps it. Proven by:
TESTING §3.3 (leak test (d), independent oracle in TESTING §10.3).
- **Residual tile-edge leak (accepted for v1, documented) [FIXED, Q4]:** a tile is the unit of
disclosure. v1 sets `tile_size` = explored cell = 32 px (section 8), tile grid origin = world
origin, so a tile is allowed iff its one cell is explored. The residual is the whole 32 px cell
that a vision polygon grazed, including art the LOS did not actually see. Once revealed it is
never revoked. No server-side masking is built [FIXED, Q4]. Static art only: door state is never
in tiles. Consequences for map authors: do not paint secrets (secret doors, hidden traps, notes)
in map art within ~32 px of areas players can reach; keep secrets as GM-only entities. Evidence:
`prototype-tile-leak/README.md` (desktop numbers; phone run 2026-11-08). Fallback if the M4 gates
in map art within ~32 px of areas players can reach; keep secrets as GM-only entities. Evidence and the M4 gates: TESTING §3.3, §13. Fallback if the M4 gates
fail: `tile_size` 64 px (per-scene config, no code change; leak <= 3 cells per allowed tile, 4x
fewer files).
- A second consequence: map art itself may depict walls/doors. Art is "what players see once there",
@@ -324,30 +323,32 @@ Notes:
`X-Accel-Redirect` is built only from the parsed integers
(`/_tiles/<scene>/v<art_version>/<x>_<y>.png`), never from request text, so no path shape can
steer it. `Cache-Control: private` is set by the Nim gate and rides through nginx's internal
redirect unchanged; nginx adds nothing of its own there (the test vhost records this, 11.1). Nim
sends no body and no `Content-Type`.
redirect unchanged; nginx adds nothing of its own there (the test vhost records this, TESTING
§11.1). Nim sends no body and no `Content-Type`.
### 3.4 Threat list
| # | Threat | Mitigation | Test |
|---|---|---|---|
| T1 | Player reads hidden token/entity/prop from WS | view builder filters by LOS, `gm_only`, bucket; single egress | leak test + fault classes |
| T2 | Player reads wall/door data | walls only in GM view; the sole exception is a player's own marker (anchor point + opaque id, nothing else, 3.1/5.8, #48) | fault `walls` [MEASURED caught]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (10.3); door-equivalence test (T17, 10.3) |
| T3 | Player reads other player's vision/explored/ownership | per-player view only | faults `other-*` [MEASURED caught] |
| T4 | Player fetches unexplored tiles | Nim gate + internal nginx location | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) |
| T5 | Tile-edge over-disclosure: one 32 px cell grazed by vision, never revoked | tile_size = explored cell = 32 px, no server masking, authoring rule ~32 px (Q4 FIXED) | documented, not testable as a leak; M4 timing gates (13) |
| T6 | Player key / session theft via logs, referrer, history | key in POST body, never in URL; session != key (hash stored); log redaction; no-referrer on sign-in; HTTPS only | config test (grep logs for secret) [new] |
| T7 | Cross-site WS hijack | Origin check + SameSite=Strict | new test |
| T8 | **Wall-probing oracle via move validation** [INFERRED, not in prototype tests]: `moveBlocked` answers `ok:false` for any chosen segment, with unlimited length; binary searching lets a player map walls beyond LOS and tell open from closed doors | cap step length per intent (= token's effective vision radius, scene default if no vision; 5.5, Q18 FIXED), rate limit intents per connection (6.4), uniform nack that carries only the old position (5.5) | M2 in-process probing test (5.5, 13); WS version in M3 (10.3): count wall/door facts recoverable from nacks beyond LOS |
| T9 | Info via error replies (`not yours` echoing a position) | refusals are static codes, never state (6.5); a move of a non-controlled or unknown token gives `ack {ok:false, code:"not-allowed"}` without position, one code for both [MEASURED rule, README Findings] | leak test (e) |
| T10 | Message-size or rate DoS, slow client memory growth | max frame size (6.4), per-connection rate limit (6.4), connection cap (4.3); **bounded per-connection outbox** (byte/message caps, state coalescing), lagging clients stopped and resynced (4.3, Q13); mummy queue is unbounded [MEASURED finding, README mummy caveats] | new tests (10.3 slow client, protocol) |
| T11 | Timing/size side channels (message bytes reveal hidden activity) | accepted; only deliver messages when state visible to that recipient changes | not tested |
| T12 | Path tricks on static/tile routes | strict parsing; webby rejected `%2f`/`%00` [MEASURED, NOTES Phase 2a] | smoke |
| T13 | Player-controlled strings (token names, props) as XSS in DOM overlay | render with `textContent`, never `innerHTML`; CSP | new test |
| T14 | Boundary ambiguity: token exactly on vision edge | documented epsilon; tests use 0.5 px tolerance [MEASURED] | leak test |
| T15 | Backend reachable bypassing nginx (prototype nginx binds 0.0.0.0, `HANDOFF.md`) | Nim binds 127.0.0.1 only [MEASURED: prototype does], systemd `IPAddressAllow`, TLS at nginx | deploy check |
| T16 | Name leak: actual name or reveal state of an unrevealed character/token, another player's character or encountered entry, or a browsable character list reaches a player | names and lists built per recipient at egress (8); no list-all message; encountered list is per player | fault classes `ACTUAL_NAME`, `CHAR_LIST` (10.3) |
| T17 | **Player tells a secret or a locked door from a solid wall**, by any observable: frames, explored cells, tiles, refusal shapes, move outcomes, churn | the door settings never leave the GM view (3.1); a secret or locked door is a closed barrier to sight, movement and the door push with no other signal (5.8); same closed geometry in both scenes | differential door-equivalence test `tools/doors.test.mjs` (10.3, #46), positive control on an open door, fault `secretgap`, door-key scan in `tools/leakcheck.nim` -> `WALLDATA` |
| # | Threat | Mitigation |
|---|---|
| T1 | Player reads hidden token/entity/prop from WS | view builder filters by LOS, `gm_only`, bucket; single egress |
| T2 | Player reads wall/door data | walls only in GM view; the sole exception is a player's own marker (anchor point + opaque id, nothing else, 3.1/5.8, #48) |
| T3 | Player reads other player's vision/explored/ownership | per-player view only |
| T4 | Player fetches unexplored tiles | Nim gate + internal nginx location |
| T5 | Tile-edge over-disclosure: one 32 px cell grazed by vision, never revoked | tile_size = explored cell = 32 px, no server masking, authoring rule ~32 px (Q4 FIXED) |
| T6 | Player key / session theft via logs, referrer, history | key in POST body, never in URL; session != key (hash stored); log redaction; no-referrer on sign-in; HTTPS only |
| T7 | Cross-site WS hijack | Origin check + SameSite=Strict |
| T8 | **Wall-probing oracle via move validation** [INFERRED, not in prototype tests]: `moveBlocked` answers `ok:false` for any chosen segment, with unlimited length; binary searching lets a player map walls beyond LOS and tell open from closed doors | cap step length per intent (= token's effective vision radius, scene default if no vision; 5.5, Q18 FIXED), rate limit intents per connection (6.4), uniform nack that carries only the old position (5.5) |
| T9 | Info via error replies (`not yours` echoing a position) | refusals are static codes, never state (6.5); a move of a non-controlled or unknown token gives `ack {ok:false, code:"not-allowed"}` without position, one code for both [MEASURED rule, README Findings] |
| T10 | Message-size or rate DoS, slow client memory growth | max frame size (6.4), per-connection rate limit (6.4), connection cap (4.3); **bounded per-connection outbox** (byte/message caps, state coalescing), lagging clients stopped and resynced (4.3, Q13); mummy queue is unbounded [MEASURED finding, README mummy caveats] |
| T11 | Timing/size side channels (message bytes reveal hidden activity) | accepted; only deliver messages when state visible to that recipient changes |
| T12 | Path tricks on static/tile routes | strict parsing; webby rejected `%2f`/`%00` [MEASURED, NOTES Phase 2a] |
| T13 | Player-controlled strings (token names, props) as XSS in DOM overlay | render with `textContent`, never `innerHTML`; CSP |
| T14 | Boundary ambiguity: token exactly on vision edge | documented epsilon; tests use 0.5 px tolerance [MEASURED] |
| T15 | Backend reachable bypassing nginx (prototype nginx binds 0.0.0.0, `HANDOFF.md`) | Nim binds 127.0.0.1 only [MEASURED: prototype does], systemd `IPAddressAllow`, TLS at nginx |
| T16 | Name leak: actual name or reveal state of an unrevealed character/token, another player's character or encountered entry, or a browsable character list reaches a player | names and lists built per recipient at egress (8); no list-all message; encountered list is per player |
| T17 | **Player tells a secret or a locked door from a solid wall**, by any observable: frames, explored cells, tiles, refusal shapes, move outcomes, churn | the door settings never leave the GM view (3.1); a secret or locked door is a closed barrier to sight, movement and the door push with no other signal (5.8); same closed geometry in both scenes |
The `Test` column (the proving test for each row) is in TESTING §3.4.
---
@@ -372,13 +373,14 @@ never queried at runtime for reads).
per-connection counter, player id, role.
- Prototype used fixed roles `gm`/`A`/`B`; real build uses player ids. Multiple connections per
player are allowed and share the player's vision/explored (as prototype).
- Monsters/NPCs have no vision [MEASURED design: `vision_ms move-monster` 0.000 ms]; only
player-owned entities with `vision` produce polygons.
- Monsters/NPCs have no vision; only player-owned entities with `vision` produce polygons. Proven by:
TESTING §4.1 ([MEASURED] `vision_ms move-monster` 0.000 ms).
### 4.2 Mutation pipeline
`intent -> validate -> apply -> per-player visibility -> diff -> persist -> ack -> send`
Under the single global lock (as prototype, order proven correct by 3 x 60 s runs):
Under the single global lock (as prototype; the order is proven correct by the 3 x 60 s runs in
TESTING §4.3):
1. **Parse** with strict type checks (prototype pattern: kind checks per field). Unknown `t` -> `ack
unknown-type` (`error malformed` if the envelope is unreadable; 6.5).
2. **Authorize**: role/ownership.
@@ -418,12 +420,11 @@ server clamps nothing silently (clamping would leak the hit distance, T8).
and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED
reading, `prototype-server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
- **One global lock** around intent handling and outbox enqueue; network sends happen outside it
(flush, see 4.2). [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223
intents/s): no crash, no reorder, no loss, consistent final views
(`results/concurrency-final{1,2,3}.log`); intent->ack avg 1.40 ms, p99 4.58 ms, worst 20.31 ms.
- Decision [PROPOSED]: keep the global lock in v1. A table of <= ~10 clients is 2 orders of
magnitude below the single-core limit (server total per mutation avg 0.70 ms [MEASURED]). Revisit
only if a measured p99 > 50 ms appears in production logs.
(flush, see 4.2). [MEASURED] order, loss and final-view consistency over 3 x 60 s runs, and the
latency figures: TESTING §4.3.
- Decision [PROPOSED]: keep the global lock in v1; a table of <= ~10 clients is 2 orders of
magnitude below the single-core limit (measurement in TESTING §4.3). Revisit only if a measured
p99 > 50 ms appears in production logs.
- Worker threads: prototype uses 8; one table needs 2-4 [INFERRED].
- **Slow client [FIXED (owner decision), 2026-11-08, Q13 option A]**. mummy's send queue is one
unbounded deque and per-socket backlog is invisible to app code (no forced close, no depth API at
@@ -457,8 +458,8 @@ server clamps nothing silently (clamping would leak the hit distance, T8).
`clientId`; Nim 2.2 stdlib) [MEASURED reading, `docs/research/q13-mummy-slow-clients.md`,
Corrections]. Prototype keys connections by the raw bytes of the ref (`key(ws)`), flagged as
shortcut. Real build: assign an app `connId` at upgrade and key the outbox table by `connId`, not
by `WebSocket` [PROPOSED, per Q13 research]; add a test that fails if mummy's `WebSocket` fields
change (the pin makes this stable, the test makes it explicit) [PROPOSED].
by `WebSocket` [PROPOSED, per Q13 research]. A test that fails if mummy's `WebSocket` fields change
is proposed in TESTING §4.3.
- Handler discipline: no blocking I/O under the lock except the one SQLite COMMIT; no logging
formatting of large structures under the lock; metrics are O(1) updates (section 11).
- **Borrow, do not copy, under the lock** (#28): the egress reads the live tables through
@@ -470,12 +471,11 @@ server clamps nothing silently (clamping would leak the hit distance, T8).
`X-Accel-Redirect` from one record), `checkScene` (the id), the wall/door handlers (the post-lock
log and effect frame). A handler that reads `app.scene` twice can see two records; one that reads
it outside the lock races the assignment and ORC's free of the old `walls`.
- SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and
every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted
for v1. Moving persist out of the lock breaks ack-after-commit and order; not done.
- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (host stall or node harness
pause; not proven either way, `results/spike/investigation.md`). Production logging (section 11)
must make a recurrence diagnosable (SLOW lines with breakdown).
- SQLite tail: server worst ~20 ms is the COMMIT and every other mutation queues behind it as
`lock_wait` (measurement and hypothesis: TESTING §4.3). Accepted for v1. Moving persist out of the
lock breaks ack-after-commit and order; not done.
- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (TESTING §4.3). Production
logging (section 11) must make a recurrence diagnosable (SLOW lines with breakdown).
### 4.4 Persistence
Engine: SQLite via `db_connector/db_sqlite`, `journal_mode=WAL`, one connection used under the
@@ -483,10 +483,7 @@ global lock. Also `busy_timeout=5000` and `foreign_keys=ON` at open [FIXED (owne
2026-11-14, #16)].
**synchronous choice [FIXED, Q12]: `NORMAL`; `FULL` around GM authoring transactions.**
- [MEASURED] avg commit 0.60 -> 0.17 ms, server total avg 1.16 -> 0.74 ms; tail unchanged (~20 ms
worst) (`results/spike/investigation.md`).
- Process kill (SIGKILL) loses nothing [MEASURED: `results/final-restart.log`, SIGTERM and SIGKILL,
same DB, identical state].
- Commit cost and the SIGKILL result are measured in TESTING §4.4 ([MEASURED]).
- OS crash/power loss can drop the last few commits; never corrupts. For a VTT (positions, explored
cells) that is acceptable; GM-authored content (walls, scenes) is the expensive loss, so GM
authoring transactions run with `synchronous=FULL` [FIXED, Q12].
@@ -521,10 +518,7 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
`HANDOFF.md`); the real build stores **chunked bitmaps** [FIXED (owner-delegated, 2026-11-15,
#21)]: a chunk is 64x64 cells = 512 B, upserted per mutation and only when the mutation dirtied
it. Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144
cells = 32 KB (8x8 chunks). Measured cost of one mutation-scale write (BEGIN; 512 B upsert;
COMMIT): avg 0.015 ms, p99 0.035 ms (4.3's accepted commit tail is ~20 ms), and a real move's ack
stays at avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`,
`tools/persistence.test.mjs`).
cells = 32 KB (8x8 chunks). The measured write cost and the pinning tests: TESTING §4.4.
- Entity move = one UPSERT of x,y (prototype: `INSERT OR REPLACE INTO tok`).
- Migrations: `PRAGMA user_version` + forward-only migration list; startup refuses to run on a newer
DB [PROPOSED]. Detail [FIXED (owner-delegated, 2026-11-14, #16)]: `schema_migration(version
@@ -550,8 +544,8 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
CHECK (open IN (0,1)), flags TEXT JSON DEFAULT '{}', PRIMARY KEY (scene_id, id))`. `w, h,
tile_size, cell, art_version` stay off the wire (6.1 `scene.set`). The scene row carries
`next_wall_id`, so wall ids survive restarts, removals and re-imports of the same scene (#3);
seeding in the migration keeps the scene identical on every start and lets the migration test
assert it (10.3).
seeding in the migration keeps the scene identical on every start (asserted by the migration test,
TESTING §4.4).
- Step 4 (`tokens`) [FIXED (owner-delegated, 2026-11-15, #20)]: creates `entity`, the map figures
(`id TEXT PK`, `scene_id FK ON DELETE CASCADE`, `kind`, `descriptive_name`, `actual_name`, `x`,
`y`, `radius REAL NULL`, `owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL`,
@@ -569,9 +563,8 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
+ (cx mod 64)`, byte `bit div 8`, mask `1 shl (bit mod 8)`). Cells outside the scene stay 0, so a
map whose cell count is not a multiple of 64 needs no special case; the v1 scene is 128x128 cells
= 2x2 chunks, a 16384 px map 8x8. Both FKs cascade, so `player.remove` and a scene delete take the
explored rows with them. The layout is pinned by `tests/texplored.nim` (exact byte/bit positions)
and re-read independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes
or bit order.
explored rows with them. The layout is pinned by tests (TESTING §4.4), so a refactor cannot
silently swap axes or bit order.
- Step 6 (`token details`) [FIXED (owner-delegated, 2026-11-15, #22)]: adds `entity.props_public`,
`props_owner`, `props_gm` (`TEXT NOT NULL DEFAULT '{}'`: one JSON object per visibility bucket)
and creates `entity_status(entity_id TEXT REFERENCES entity(id) ON DELETE CASCADE, status TEXT