From 0f3aa2300fe2c58426759b472cd4068aafb8227f Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Thu, 19 Nov 2026 22:49:39 +0100 Subject: [PATCH] feat(walls): door refusals and secret/locked equivalence gate (#56) - door.set: opening a secret or locked door is invalid; closing either is allowed; a fixed window/non-door still has no open state. - new tools/doors.test.mjs: two fresh servers, one identical script, three equivalence pairs (secret/wall, secret+locked/wall, locked/closed door), canonicalised frame + full per-player tile sweeps, an open-door positive control and a pinned zero-thickness close-push. - secretgap fault hook (sight-only) makes the pair fail as exactly SECRETGAP; the clean pair passes and the shipped binary carries no fault hook. - docs/TESTING.md T2/T17 and the door-equivalence/10.3 sections: built. Ref #56 --- docs/TESTING.md | 45 ++--- server/vision.nim | 2 +- server/world.nim | 10 +- server/worldmap.nim | 11 +- tests/tworld.nim | 26 +++ tools/doors.test.mjs | 392 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 459 insertions(+), 27 deletions(-) create mode 100644 tools/doors.test.mjs diff --git a/docs/TESTING.md b/docs/TESTING.md index e69eabc..3cb62c5 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -60,7 +60,7 @@ How to run: `devbox run test` = Nim in-process tests first, then the Node black- | # | Proving test | |---|---| | T1 | leak test + fault classes | -| T2 | fault `walls` [MEASURED caught]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3) — planned: Walls r1 #59/#60; door-equivalence test (T17, §10.3) — planned: Walls r1 #56 | +| T2 | fault `walls` [MEASURED caught]; door-equivalence test (T17, §10.3) [MEASURED caught: fault `secretgap`]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3) — planned: Walls r1 #59/#60 | | T3 | faults `other-*` [MEASURED caught] | | T4 | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) | | T5 | documented, not testable as a leak; M4 timing gates (§13) | @@ -75,7 +75,7 @@ How to run: `devbox run test` = Nim in-process tests first, then the Node black- | T14 | leak test | | T15 | deploy check | | T16 | fault classes `ACTUAL_NAME`, `CHAR_LIST` (§10.3) | -| T17 | 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` — planned: Walls r1 #56 | +| T17 | differential door-equivalence test `tools/doors.test.mjs` (§10.3, #46), positive control on an open door [MEASURED], fault `secretgap` [MEASURED caught: `SECRETGAP`], door-key scan in `tools/leakcheck.nim` -> `WALLDATA` (Walls r1 #56) | --- @@ -347,8 +347,10 @@ from the prototype, what was missing, what the M3 build added, and the tools it exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`, `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`, `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`, - `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`. Planned: Walls r1 — `ONEWAY` (#58), - `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (#59/#60), `secretgap` (#56). `tools/leakcheck.nim` + `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`. Walls r1 built: `secretgap` (#56), asserted + as exactly `SECRETGAP` by `tools/doors.test.mjs` (the differential group, not the transcript + checker). Planned: Walls r1 — `ONEWAY` (#58), `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` + (#59/#60). `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a non-controller and any `source` on a player status entry. Two consequences: the `hidden` and `gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the client @@ -379,10 +381,9 @@ from the prototype, what was missing, what the M3 build added, and the tools it - **Probing test (T8)**: M2, in-process against the move-rules module (DESIGN §5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2). -- **Door equivalence (#46, T17)** — planned: Walls r1 #56; `tools/doors.test.mjs` is not built yet. It - will be the accept group for the "a player cannot - tell a secret or locked door from a wall" obligation DESIGN §5.8 states. Node harness, built-ins only - (10.4), shaped like `tools/probing.test.mjs`: two servers, fresh state, two scenes identical except +- **Door equivalence (#46, T17)** — built: Walls r1 #56, `tools/doors.test.mjs`. It is the accept + group for the "a player cannot tell a secret or locked door from a wall" obligation DESIGN §5.8 + states. Node harness, built-ins only (10.4): two servers, fresh state, two scenes identical except one segment, one identical scripted sequence. Pairs: (i) solid `wall` vs a closed `door` with `secret`; (ii) solid wall vs a closed door with `secret` and `locked`; (iii) closed `door` vs a closed `door` with `locked` (since #48 there are no `secret_door`/`locked_door` presets: the switches @@ -391,18 +392,22 @@ from the prototype, what was missing, what the M3 build added, and the tools it nacks, over-cap nacks); the GM adds the segment over a player token (`stuck`); the GM edits and toggles unrelated walls and doors elsewhere and moves tokens; a resync/reconnect; a GM `door.set open` on the secret/locked segment, refused `invalid` and GM-side only. **Assertion:** each player's - complete received frame sequence — `hello`, `vision`, `explored` (full and delta), `token` (statuses - included), `encountered`, and every `ack`/nack with its `code` and `pos` — is identical between the - two runs after JSON canonicalisation (keys sorted, no numeric reformatting). **Normalisation allowed: - none**; `n` is per connection and wall ids never reach a player, so nothing run-local leaks into the - comparison. If the build ever forces a run-local difference it must be named in the test header with - the reason. **Tiles:** the same per-player tile sweep in both runs, through the test nginx - (`tools/nginx.mjs`, §11.1), must give the same status per tile. **Positive control:** the same script - against a third scene whose segment is an open door (or absent) must produce *different* transcripts, - otherwise the harness cannot fail (this file's first principles). **Negative control:** a - `-d:leakfault` build with `LEAK_FAULT=secretgap` makes a secret door not block sight (or movement) - in the player-facing computation; the doors group must fail with that build, pass on a clean one, and - the shipped binary must carry no fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:** + complete received frame sequence — `hello`, `roster`, `vision`, `explored` (full and delta), `token` + (statuses included), `encountered`, and every `ack`/nack with its `code` and `pos` — is identical + between the two runs after JSON canonicalisation (keys sorted, no numeric reformatting). + **Normalisation allowed:** the one run-local value a fresh two-server world forces is an opaque + token id (the server CSPRNG, DESIGN 8); the harness maps each run's ids to `TOK` in creation order + and sorts an encountered list by that id before comparison. Nothing else is normalised: `n`, player + ids, positions, statuses, polygons, explored cells and tile statuses compare byte for byte. + **Tiles:** the same per-player tile sweep in both runs, through the test nginx + (`tools/nginx.mjs`, §11.1), must give the same status and body per tile. **Closing push:** the + script closes an ordinary door over a token and pins the resulting position (320,350), the + zero-thickness push gate unchanged. **Positive control:** the same script against a scene whose + segment is an open door must produce *different* transcripts, otherwise the harness cannot fail + (this file's first principles). **Negative control:** a `-d:leakfault` build with + `LEAK_FAULT=secretgap` makes a secret door not block sight in the player-facing computation; the + pair then fails as exactly `SECRETGAP`, the clean build passes, and the shipped binary carries no + fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:** `door.set` on a secret or locked door is `invalid` for the GM; a player `door.set` is `not-allowed` for every door (DESIGN §6.5), so the player side has one code and no oracle. **Not covered:** timing and size side channels (T11), accepted and unchanged. diff --git a/server/vision.nim b/server/vision.nim index 6a3aa41..fa26900 100644 --- a/server/vision.nim +++ b/server/vision.nim @@ -49,7 +49,7 @@ proc cellOf*(sc: SceneRec, idx: int): (int, int) = proc computePolys*(sc: SceneRec, tokens: seq[TokenRec], playerId: int): seq[Poly] = ## One polygon per token of this player that has vision, in token order (a stable wire order). if playerId <= 0: return - let walls = geometryWalls(sc) + let walls = geometryWalls(sc, forSight = true) for t in tokens: if t.owner != playerId or not t.hasVision: continue result.add Poly(tokenId: t.id, diff --git a/server/world.nim b/server/world.nim index 854ab3f..a8412ea 100644 --- a/server/world.nim +++ b/server/world.nim @@ -504,11 +504,15 @@ proc removeWall*(db: DbConn, sc: var SceneRec, id: int): WallApply = waOk proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply = - ## `door.set`: only a door can be opened or closed (`invalid` on a plain wall). + ## `door.set`: only a door has an open state (`invalid` on a plain wall or a fixed window). A + ## secret door is always closed and a locked door only refuses opening, so `open:true` on either + ## is `invalid`; closing either is allowed (it is already closed, DESIGN 5.8, 6.1, #56). let idx = wallIndex(sc, id) if idx.isNone: return waNotFound - if sc.walls[idx.get].door == false: return waNotDoor - var stored = sc.walls[idx.get] + let current = sc.walls[idx.get] + if current.door == false: return waNotDoor + if open and (current.secret or current.locked): return waInvalid + var stored = current stored.open = open authoringTransaction(db): db.exec(sql"UPDATE wall SET open = ? WHERE scene_id = ? AND id = ?", diff --git a/server/worldmap.nim b/server/worldmap.nim index a63d016..0c32175 100644 --- a/server/worldmap.nim +++ b/server/worldmap.nim @@ -15,13 +15,18 @@ ## copies a token record before it applies an outcome, and a Nim seq assignment shares its buffer, so ## in-place edits would reach the authoritative list before the transaction commits (4.2 step 6). import std/options -import geometry, moverules, tokens, world +import geometry, moverules, tokens, world, faults -proc geometryWalls*(sc: SceneRec): seq[Wall] = +proc geometryWalls*(sc: SceneRec, forSight = false): seq[Wall] = ## The scene's walls as the vision code sees them: an open door does not block (5.1). + ## `forSight` is only the sight computation; `LEAK_FAULT=secretgap` (a -d:leakfault build only) + ## opens a secret door there, the negative control for the door-equivalence group (#56). result = newSeqOfCap[Wall](sc.walls.len) for w in sc.walls: - result.add Wall(a: w.a, b: w.b, door: w.door, open: w.open) + var wall = Wall(a: w.a, b: w.b, door: w.door, open: w.open) + if forSight and w.secret and faultActive("secretgap"): + wall.open = true + result.add wall proc ruleWall*(w: WallRec): Wall = ## The same wall as the move rules see it (they need `door`/`open` to know what blocks). diff --git a/tests/tworld.nim b/tests/tworld.nim index 9bff85c..c74526a 100644 --- a/tests/tworld.nim +++ b/tests/tworld.nim @@ -185,6 +185,32 @@ suite "persistence (write-through, restart-identical)": check loadScene(conn).get.walls.len == 1 check loadScene(conn).get.nextWallId == 3 + test "door.set refuses to open a secret or locked door, closing either is allowed (#56)": + let (conn, d) = freshScene() + defer: + close(conn) + removeDir(d) + var sc = loadScene(conn).get + var secret = wall(10, 10, 100, 10, door = true) + secret.secret = true + let secretId = addWall(conn, sc, secret).get + var locked = wall(10, 20, 100, 20, door = true) + locked.locked = true + let lockedId = addWall(conn, sc, locked).get + check setDoor(conn, sc, secretId, true) == waInvalid + check setDoor(conn, sc, lockedId, true) == waInvalid + check wallById(sc, secretId).get.open == false + check wallById(sc, lockedId).get.open == false + check loadScene(conn).get.walls[0].open == false + # Closing either is a no-op, never a refusal: the setting only refuses opening. + check setDoor(conn, sc, secretId, false) == waOk + check setDoor(conn, sc, lockedId, false) == waOk + # Clearing the setting makes the same door openable, and the lock/secret never leaks. + var clear = wallById(sc, lockedId).get + clear.locked = false + check updateWall(conn, sc, clear) == waOk + check setDoor(conn, sc, lockedId, true) == waOk + test "nullable height and label use SQL literals and round-trip as none, not 0 or ''": let (conn, d) = freshScene() defer: diff --git a/tools/doors.test.mjs b/tools/doors.test.mjs new file mode 100644 index 0000000..b3592a5 --- /dev/null +++ b/tools/doors.test.mjs @@ -0,0 +1,392 @@ +// Walls r1 (#56, T17, TESTING 10.3 "Door equivalence"): a player cannot tell a secret door from a +// solid wall, nor a locked door from a closed one. Two fresh real servers run ONE scripted sequence +// each; the only difference between their worlds is the switches of the segment under test. Every +// player's complete received frame sequence (hello, roster, vision, explored full+delta, token with +// statuses, encountered, every ack/nack) and the per-tile HTTP status/body sweep must be identical +// after canonicalisation. The positive control is the same script with the segment an OPEN door: it +// must produce a different transcript, otherwise this harness cannot fail. +// +// Canonicalisation is structural, never semantic: the one thing that is necessarily run-local is an +// opaque token id (the server's CSPRNG, DESIGN 8), so ids are mapped to TOK in creation order and +// an encountered list is sorted by that id before comparison (a Table iteration order would +// otherwise vary with the random ids). Nothing else is normalised: `n`, player ids, positions, +// statuses, polygons, explored cells and tile statuses compare byte for byte. +// +// The `secretgap` fault build (LEAK_FAULT=secretgap) makes a secret door stop blocking sight in the +// player-facing computation; the same script must then FAIL as exactly SECRETGAP. A clean build +// passes, and tools/fault.test.mjs already proves the shipped binary carries no fault hook. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { baseUrl, createPlayer, freePort, namePlayer, refuseLivePort, sleep } from './lib.mjs' +import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' +import { startTestNginx, stopTestNginx } from './nginx.mjs' +import { writeTileGrid } from './tilefixture.mjs' + +const SEG = { a: [600, 500], b: [600, 700] } // the differing segment, identical geometry +const GRID = { x0: 0, x1: 31, y0: 0, y1: 31 } + +const canonical = value => { + if (Array.isArray(value)) return value.map(canonical) + if (value && typeof value === 'object') { + return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])) + } + return value +} + +// Map this run's opaque token ids to a stable ordinal, then canonicalise. Applied to player frames +// only: walls never reach a player, and GM frames are not compared. +function canonicalFrames(messages, tokenIds) { + const map = new Map(tokenIds.map((id, i) => [id, `TOK${i + 1}`])) + const rename = node => { + if (Array.isArray(node)) return node.map(rename) + if (node && typeof node === 'object') { + return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, rename(v)])) + } + if (typeof node === 'string' && map.has(node)) return map.get(node) + return node + } + const stable = m => { + const out = rename(m) + if (out && out.t === 'encountered') { + const byId = (x, y) => String(x.id).localeCompare(String(y.id)) + if (Array.isArray(out.set)) out.set = [...out.set].sort(byId) + if (Array.isArray(out.del)) out.del = [...out.del].sort() + } + return canonical(out) + } + return messages.map(stable) +} + +// --------------------------------------------------------------------------------------------- +// A stack: the real binary and the test nginx in front (the production shape, DESIGN 11.1). + +async function stack(opts = {}) { + const stateDir = opts.stateDir ?? makeStateDir() + const gmKey = gmKeyOf(stateDir) + const nginxPort = await freePort() + refuseLivePort(nginxPort) + const server = await startServer({ + stateDir, publicOrigin: baseUrl(nginxPort), + defines: opts.defines, env: opts.env, + }) + const nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort }) + return { stateDir, gmKey, server, nginx, origin: nginx.origin } +} + +async function stopStack(s) { + if (!s) return + await stopTestNginx(s.nginx) + await stopServer(s.server) + fs.rmSync(s.stateDir, { recursive: true, force: true }) +} + +// --------------------------------------------------------------------------------------------- +// The one script. `variant` is the segment's switch set; every other action is identical. + +async function runScript(ctx, variant, opts = {}) { + const gm = await openAs(ctx.origin, ctx.gmKey) + await gm.ws.waitText('hello') + const scene = (await gm.ws.waitText('walls')).scene + + const add = async fields => { + const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id) + return ack.id + } + const request = async (fields, code) => { + const ack = await gm.ws.request({ t: fields.t, scene, ...fields }) + if (code === undefined) assert.equal(ack.ok, true, JSON.stringify(ack)) + else { + assert.equal(ack.ok, false, JSON.stringify(ack)) + assert.equal(ack.code, code, JSON.stringify(ack)) + } + return ack + } + + // Common world: a far north wall, a door used for the close-push, and far walls the GM edits. + await add({ a: [0, 0], b: [4096, 0], flags: { note: 'north' } }) + const pushDoor = await add({ a: [300, 300], b: [300, 400], door: true }) + const farWall = await add({ a: [2000, 1000], b: [2500, 1000] }) + const farDoor = await add({ a: [2600, 1000], b: [2600, 1200], door: true }) + + // Two named players, so both sides of the differing segment have a viewer. + const alice = await createPlayer(gm.ws) + await namePlayer(ctx.origin, alice.key, 'Alice') + const bob = await createPlayer(gm.ws) + await namePlayer(ctx.origin, bob.key, 'Bob') + + const token = async fields => { + const ack = await gm.ws.request({ t: 'token.create', scene, ...fields }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + await gm.ws.waitFor(m => m.t === 'token' && m.id === ack.id) + return ack.id + } + // T1 sees the segment's left side; T2 sees the right side; T3 sits where the segment will be added + // (the GM's add must mark it stuck); T4 is for the close-push. + const t1 = await token({ kind: 'pc', pos: [520, 600], flags: { vision: true }, + vision_radius: 300, controller: alice.id, + descriptive_name: 'Alice', actual_name: 'Alice' }) + const t2 = await token({ kind: 'pc', pos: [680, 600], flags: { vision: true }, + vision_radius: 300, controller: bob.id, + descriptive_name: 'Bob', actual_name: 'Bob' }) + const t3 = await token({ kind: 'npc', pos: [615, 600], controller: alice.id, + descriptive_name: 'crate', actual_name: 'crate' }) + const t4 = await token({ kind: 'npc', pos: [330, 350], controller: bob.id, + descriptive_name: 'barrel', actual_name: 'barrel' }) + const tokenIds = [t1, t2, t3, t4] + + const connect = async key => { + const c = await openAs(ctx.origin, key) + await c.ws.waitText('hello') + await c.ws.waitFor(m => m.t === 'explored' && m.full === true) + return c + } + let a = await connect(alice.key) + let b = await connect(bob.key) + + // The GM adds the segment under test over T3 (stuck). This is the only world difference. + const segId = await add({ ...SEG, ...variant }) + await sleep(60) + + // An unrelated token move and unrelated wall/door edits: they must not perturb the player view. + await request({ t: 'token.move', id: t2, pos: [650, 600] }) + await request({ t: 'wall.update', id: farWall, b: [2600, 1000] }) + await request({ t: 'door.set', id: farDoor, open: true }) + await request({ t: 'door.set', id: farDoor, open: false }) + const extra = await add({ a: [3000, 3000], b: [3100, 3000] }) + await request({ t: 'wall.remove', id: extra }) + + // Closing a door over a token pushes it aside exactly as today (the zero-thickness gate). + await request({ t: 'door.set', id: pushDoor, open: true }) + await request({ t: 'token.move', id: t4, pos: [300, 350] }) + await request({ t: 'door.set', id: pushDoor, open: false }) + await sleep(40) + const pushed = gm.ws.messages.filter(m => m.t === 'token' && m.id === t4).pop() + assert.ok(Math.abs(pushed.pos[0] - 320) < 1e-3 && pushed.pos[1] === 350, + `closing a door over a token pushes it aside as today: ${JSON.stringify(pushed.pos)}`) + + // The GM's door intent on the differing segment: refused `invalid` for a wall, a secret or a + // locked door; an ordinary closed door opens. GM-side only, so no player frame changes with it. + if (opts.segmentOpen === 'invalid') { + await request({ t: 'door.set', id: segId, open: true }, 'invalid') + } else if (opts.segmentOpen === 'ok') { + await request({ t: 'door.set', id: segId, open: true }) + } + + // Player moves: along, into and across the segment; one accepted, collision and over-cap nacks. + const move = async (client, id, pos, ok) => { + const ack = await client.ws.request({ t: 'token.move', id, pos }) + assert.equal(ack.ok, ok, JSON.stringify(ack)) + return ack + } + await move(a, t1, [570, 600], true) + const crossAlice = await move(a, t1, [640, 600], !!opts.crosses) + if (!opts.crosses) { + assert.deepEqual(crossAlice.pos, [570, 600], 'the uniform nack carries the old position only') + assert.equal(crossAlice.code, undefined, 'the uniform nack names no cause') + } + await move(a, t1, [520, 600], true) + const overCap = await move(a, t1, [2000, 600], false) + assert.equal(overCap.code, undefined) + await move(a, t1, [-10, 600], false) + const crossBob = await move(b, t2, [560, 600], !!opts.crosses) + if (!opts.crosses) { + assert.deepEqual(crossBob.pos, [650, 600]) + assert.equal(crossBob.code, undefined) + } + await move(b, t2, [650, 600], true) + await move(b, t2, [3000, 600], false) + await sleep(80) + + const framesA1 = [...a.ws.messages] + const framesB1 = [...b.ws.messages] + + // A resync/reconnect: the whole state is rebuilt on a fresh connection. + a.ws.close(); b.ws.close() + await Promise.all([a.ws.closed, b.ws.closed]) + a = await connect(alice.key) + b = await connect(bob.key) + await sleep(100) + + const sceneBlock = gm.ws.messages.find(m => m.t === 'hello' && m.scene)?.scene + const art = sceneBlock?.art_version ?? 1 + const frames = { + alice: canonicalFrames([...framesA1, ...a.ws.messages], tokenIds), + bob: canonicalFrames([...framesB1, ...b.ws.messages], tokenIds), + } + const cookies = { alice: a.cookie, bob: b.cookie } + a.ws.close(); b.ws.close(); gm.ws.close() + await Promise.all([a.ws.closed, b.ws.closed]) + assert.equal(art, 1, 'the v1 art version is pinned (DESIGN 3.3)') + return { frames, cookies, scene, art } +} + +// Every tile of the checked rectangle, as status + bytes. The fixture bytes are per-(x,y), so a +// status difference and a substituted body both show up. Independent of the WS transcript. +async function tileSweep(ctx, scene, art, cookie) { + const out = [] + for (let y = GRID.y0; y <= GRID.y1; y++) { + for (let x = GRID.x0; x <= GRID.x1; x++) { + const r = await fetch(`${ctx.origin}/tiles/${scene}/v${art}/${x}_${y}.png`, + { headers: { Cookie: cookie } }) + const body = Buffer.from(await r.arrayBuffer()) + out.push(`${x},${y}:${r.status}:${body.toString('base64')}`) + } + } + return out +} + +// No difference -> []. Any player-frame or tile difference is the one class this obligation has. +function equivalenceClasses(a, b) { + const classes = new Set() + if (JSON.stringify(a.frames.alice) !== JSON.stringify(b.frames.alice)) classes.add('SECRETGAP') + if (JSON.stringify(a.frames.bob) !== JSON.stringify(b.frames.bob)) classes.add('SECRETGAP') + if (JSON.stringify(a.tiles.alice) !== JSON.stringify(b.tiles.alice)) classes.add('SECRETGAP') + if (JSON.stringify(a.tiles.bob) !== JSON.stringify(b.tiles.bob)) classes.add('SECRETGAP') + return [...classes] +} + +// Runs one two-server pair end to end: identical script, one differing segment. +async function runPair(aVariant, bVariant, opts = {}) { + const dirs = [makeStateDir(), makeStateDir()] + const stacks = [] + try { + for (const dir of dirs) { + // Fixture tiles for the whole rectangle: every tile the gate may allow has real bytes. + writeTileGrid(dir, { scene: 1, artVersion: 1, size: 32, ...GRID }) + } + stacks.push(await stack({ ...(opts.a ?? {}), stateDir: dirs[0] })) + stacks.push(await stack({ ...(opts.b ?? {}), stateDir: dirs[1] })) + const runs = [] + for (const [i, variant] of [aVariant, bVariant].entries()) { + const run = await runScript(stacks[i], variant, { + ...opts, + segmentOpen: opts.segmentOpen?.[i] ?? null, + crosses: opts.crosses?.[i] ?? false, + }) + run.tiles = { + alice: await tileSweep(stacks[i], run.scene, run.art, run.cookies.alice), + bob: await tileSweep(stacks[i], run.scene, run.art, run.cookies.bob), + } + runs.push(run) + } + return { a: runs[0], b: runs[1] } + } finally { + for (const s of stacks.reverse()) await stopStack(s) + } +} + +// --------------------------------------------------------------------------------------------- +// The equivalence pairs (TESTING 10.3 T17): secret vs wall, secret+locked vs wall, locked vs closed. + +const PAIRS = [ + { name: 'a secret door is a solid wall', + a: {}, b: { door: true, secret: true }, segmentOpen: ['invalid', 'invalid'] }, + { name: 'a secret+locked door is a solid wall', + a: {}, b: { door: true, secret: true, locked: true }, segmentOpen: ['invalid', 'invalid'] }, + { name: 'a locked door is a closed door', + a: { door: true }, b: { door: true, locked: true }, segmentOpen: [null, null] }, +] + +for (const pair of PAIRS) { + test(`door equivalence: ${pair.name}`, async () => { + const { a, b } = await runPair(pair.a, pair.b, { segmentOpen: pair.segmentOpen }) + assert.ok(a.frames.alice.length > 20, 'the script produced real player coverage') + assert.ok(a.tiles.alice.some(s => s.includes(':200:')), 'the sweep allowed some tiles') + assert.ok(a.tiles.alice.some(s => s.includes(':403:')), 'the sweep refused some tiles') + assert.deepEqual(equivalenceClasses(a, b), [], + `${pair.name}: one differing segment must give identical player frames and tile statuses`) + }) +} + +test('door equivalence positive control: an open door produces a different transcript', async () => { + const { a, b } = await runPair({}, { door: true, open: true }, + { segmentOpen: ['invalid', 'ok'], crosses: [false, true] }) + assert.notDeepEqual(equivalenceClasses(a, b), [], + 'the harness must be able to fail: an open (passable, transparent) segment differs') +}) + +test('fault secretgap: the equivalence group fails as exactly SECRETGAP', async () => { + // One side is the fault build; the secret door stops blocking sight for players there, so the + // same script must be caught. Nothing else may be reported. + const { a, b } = await runPair({}, { door: true, secret: true }, { + segmentOpen: ['invalid', 'invalid'], + b: { defines: ['leakfault'], env: { LEAK_FAULT: 'secretgap' } }, + }) + assert.deepEqual(equivalenceClasses(a, b), ['SECRETGAP']) +}) + +// --------------------------------------------------------------------------------------------- +// The door-only open path (DESIGN 5.8, 6.1, 6.5): GM refusals name no cause; every door refuses a +// player with `not-allowed` whatever its settings. + +test('door.set: secret and locked refuse opening, closing is allowed, players are refused every door', async () => { + const dir = makeStateDir() + let s + try { + s = await stack() + const gm = await openAs(s.origin, s.gmKey) + await gm.ws.waitText('hello') + const scene = (await gm.ws.waitText('walls')).scene + const add = async fields => { + const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + return ack.id + } + const setDoor = async (id, open, code) => { + const ack = await gm.ws.request({ t: 'door.set', scene, id, open }) + if (code === undefined) assert.equal(ack.ok, true, JSON.stringify(ack)) + else { + assert.equal(ack.ok, false, JSON.stringify(ack)) + assert.equal(ack.code, code, JSON.stringify(ack)) + // No refusal names a cause (DESIGN 5.8, 6.5): one static code and the frame number only. + assert.deepEqual(Object.keys(ack).sort(), ['code', 'n', 'ok', 'reqId', 't']) + assert.ok(!/secret|locked|door|wall|solid/i.test(JSON.stringify(ack)), JSON.stringify(ack)) + } + return ack + } + + const fixedWindow = await add({ a: [10, 10], b: [100, 10], blocks_sight: false, + blocks_movement: true }) + const plainDoor = await add({ a: [10, 20], b: [100, 20], door: true }) + const secret = await add({ a: [10, 30], b: [100, 30], door: true, secret: true }) + const locked = await add({ a: [10, 40], b: [100, 40], door: true, locked: true }) + const both = await add({ a: [10, 50], b: [100, 50], door: true, secret: true, locked: true }) + + // A fixed window/non-door has no open state at all, in either direction. + await setDoor(fixedWindow, true, 'invalid') + await setDoor(fixedWindow, false, 'invalid') + // A secret door is always closed: opening is refused, closing is a no-op and allowed. + await setDoor(secret, true, 'invalid') + await setDoor(secret, false) + // A locked door refuses only opening; closing is allowed (it is already closed). + await setDoor(locked, true, 'invalid') + await setDoor(locked, false) + await setDoor(both, true, 'invalid') + await setDoor(both, false) + // An ordinary closed door still opens. + await setDoor(plainDoor, true) + + // Clearing the cause lets the same door open; the lock/secret never reaches a player. + await gm.ws.request({ t: 'wall.update', scene, id: locked, locked: false }) + await setDoor(locked, true) + + const player = await createPlayer(gm.ws) + await namePlayer(s.origin, player.key, 'Dora') + const p = await openAs(s.origin, player.key) + await p.ws.waitText('hello') + for (const id of [plainDoor, secret, locked, both]) { + for (const open of [true, false]) { + const ack = await p.ws.request({ t: 'door.set', scene, id, open }) + assert.equal(ack.ok, false, JSON.stringify(ack)) + assert.equal(ack.code, 'not-allowed', JSON.stringify(ack)) + assert.ok(!/secret|locked|door|wall|solid/i.test(JSON.stringify(ack)), JSON.stringify(ack)) + } + } + p.ws.close(); gm.ws.close() + } finally { + await stopStack(s) + } +})