From 959412ff09d52e7dff7c2b8a2eb54d57a00477c3 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sun, 15 Nov 2026 09:35:24 +0100 Subject: [PATCH] tools: leak driver, checker and the fault controls (#20) tools/leak.mjs builds a 27-group scene over the real wire (movement, a closed door, create/remove, gm_only, a controller hand-over, another player walking in and out, a wall added and removed, a door push) and records every frame each socket saw, one group per mutation. tools/leakcheck.nim replays it: the GM socket is ground truth, the subject's polygons and explored cells are recomputed from geometry.nim, and the explored set is also probed with a clear-segment sampler. Subjects A and B both pass with zero failures; the transcripts and logs land in results/. tools/fault.test.mjs runs the same scenario against a -d:leakfault build for each fault and asserts the EXACT class set (HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, OTHER_PLAYER, NO_REMOVE, EXPLORED), plus that the shipped binary carries no LEAK_FAULT string. withserver can build a variant with extra -d: flags and pass an env to it; lib.mjs can name a player out of band, the fixture the player-side tests need until slice 8 brings player.setname (the unnamed gate itself is pinned in tools/tokens.test.mjs). --- tools/fault.test.mjs | 67 +++++++ tools/leak.mjs | 258 +++++++++++++++++++++++++ tools/leak.test.mjs | 34 ++++ tools/leakcheck.nim | 450 +++++++++++++++++++++++++++++++++++++++++++ tools/lib.mjs | 32 +++ tools/withserver.mjs | 29 ++- 6 files changed, 861 insertions(+), 9 deletions(-) create mode 100644 tools/fault.test.mjs create mode 100644 tools/leak.mjs create mode 100644 tools/leak.test.mjs create mode 100644 tools/leakcheck.nim diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs new file mode 100644 index 0000000..47976aa --- /dev/null +++ b/tools/fault.test.mjs @@ -0,0 +1,67 @@ +// Negative controls for the leak checker (DESIGN 10.1 "fault test", 10.3; M3 slice 5 / #20). +// Every deliberate leak injected into a `-d:leakfault` build must make tools/leakcheck.nim fail, +// and it must fail under the EXACT class set named here: a checker that flags everything would +// prove nothing. The shipped build must contain no fault hook at all, and it must still pass. +// +// Classes of this slice: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, +// OTHER_PLAYER, EXPLORED. (The character and name classes of 10.3 land with slice 8, the tile class +// with slice 9.) +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { runLeak, runChecker } from './leak.mjs' +import { buildServer, gmKeyOf, makeStateDir, startServer, stopServer } from './withserver.mjs' +import { projectRoot } from './lib.mjs' + +const results = path.join(projectRoot, 'results') + +// fault -> the exact set of classes the checker must report (nothing more, nothing less) +const FAULTS = { + hidden: ['HIDDEN_TOKEN'], + gmOnly: ['GMONLY_TOKEN'], + walls: ['WALLDATA'], + withhold: ['WITHHELD'], + otherOwner: ['OTHER_PLAYER'], + otherVision: ['OTHER_PLAYER'], + otherExplored: ['OTHER_PLAYER'], + noremove: ['NO_REMOVE'], + explored: ['EXPLORED'], +} + +function classesOf(output) { + return output.split('\n') + .map(line => /^FAILCLASS ([A-Z_]+) \d+/.exec(line)) + .filter(Boolean) + .map(m => m[1]) + .sort() +} + +test('the shipped build carries no fault hook and passes the leak test', () => { + const bin = buildServer() + const bytes = fs.readFileSync(bin) + assert.equal(bytes.includes(Buffer.from('LEAK_FAULT')), false, + `${bin} contains the fault hook: a production binary must be incapable of leaking`) +}) + +for (const [fault, expected] of Object.entries(FAULTS)) { + test(`fault ${fault}: caught as exactly ${expected.join(' ')}`, async () => { + fs.mkdirSync(results, { recursive: true }) + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: fault } }) + const transcript = path.join(stateDir, 'fault.jsonl') + try { + await runLeak({ origin: s.origin, gmKey, stateDir, transcript }) + const check = runChecker(transcript, 'A') + fs.appendFileSync(path.join(results, 'faults.log'), + `== fault ${fault}\n${check.output}\n`) + assert.notEqual(check.status, 0, `the checker passed a leak (${fault}):\n${check.output}`) + assert.deepEqual(classesOf(check.output), expected.sort(), + `wrong classes for ${fault}:\n${check.output}`) + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) +} diff --git a/tools/leak.mjs b/tools/leak.mjs new file mode 100644 index 0000000..297792f --- /dev/null +++ b/tools/leak.mjs @@ -0,0 +1,258 @@ +// Leak test driver (DESIGN 10.1, 10.3; M3 slice 5 / #20). Builds a known scene over the real wire, +// then plays a scripted narrative with ONE mutation per group and writes every frame each socket +// received to a JSONL transcript. tools/leakcheck.nim replays it: the GM socket is ground truth, +// the subject's own messages are only ever checked, never trusted. +// +// Groups: a marker line, one action, then "quiescent" (no frame for QUIET ms on any socket). That +// is what lets the checker evaluate a group as one state: every mutation is its own group, so the +// truth after the group is the truth the group's frames describe. +// +// The scenario (4096 px world, 32 px cells, 400 px vision, token radius 20) is built to exercise +// every way a token can enter or leave a player's view: +// - visible at the first resync (M1, and the subject's own token) +// - hidden behind a closed door, revealed by opening it (M2) +// - removed from view by moving away, and re-entering +// - created and removed while in view +// - a `gm_only` token inside LOS that must never appear (M3) +// - a controller change: handed to the subject while out of sight, handed back +// - another player's token walking in and out (A sees B) +// - a wall added and removed while the subject watches (its polygon shrinks and grows) +// - a door closing on a token, which the server pushes aside (5.5) +// - a token that is never within range at all (M4) +import fs from 'node:fs' +import path from 'node:path' +import { spawnSync } from 'node:child_process' +import { createPlayer, namePlayer, openWs, sleep, projectRoot } from './lib.mjs' +import { signIn } from './withserver.mjs' + +const QUIET_MS = 60 +const nimblePkgs = () => path.join(process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble'), 'pkgs2') + +// The checker is compiled once per process (it imports server/geometry.nim through --path in nim.cfg). +let checkerBin = null +export function buildChecker() { + if (checkerBin) return checkerBin + const out = path.join(projectRoot, 'run', 'test', 'leakcheck') + fs.mkdirSync(path.dirname(out), { recursive: true }) + const r = spawnSync('nim', ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`, + `-o:${out}`, path.join('tools', 'leakcheck.nim')], + { cwd: projectRoot, encoding: 'utf8' }) + if (r.status !== 0) throw new Error(`nim c tools/leakcheck.nim failed:\n${r.stdout}\n${r.stderr}`) + checkerBin = out + return out +} + +export function runChecker(transcript, subject) { + const r = spawnSync(buildChecker(), [transcript, subject], { encoding: 'utf8' }) + return { status: r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}` } +} + +// One socket, its received frames, and where the transcript cursor is. +async function connect(origin, key, who, log) { + const { cookie } = await signIn(origin, key) + const ws = await openWs(origin, cookie) + return { who, ws, logged: 0, log } +} + +export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = false }) { + // The transcript is written in group order; the checker needs nothing else. + const lines = [] + const log = obj => lines.push(JSON.stringify(obj)) + const clients = [] + + const gm = await connect(origin, gmKey, 'GM', log) + clients.push(gm) + await gm.ws.waitText('hello') + const walls = await gm.ws.waitText('walls') + const scene = walls.scene + + let g = 0 + let quiesceMs = QUIET_MS + + const flush = () => { + // Only now, at a group boundary, do the frames a client received get attributed to the group. + for (const c of clients) { + for (; c.logged < c.ws.messages.length; c.logged++) { + log({ k: 'msg', who: c.who, g, m: c.ws.messages[c.logged] }) + } + } + } + + async function quiesce() { + const deadline = Date.now() + 5000 + let last = -1 + let since = Date.now() + for (;;) { + const n = clients.reduce((a, c) => a + c.ws.messages.length, 0) + if (n !== last) { last = n; since = Date.now() } + if (Date.now() - since >= quiesceMs) return + if (Date.now() > deadline) throw new Error('server never went quiet') + await sleep(10) + } + } + + async function group(label, fn) { + g++ + log({ k: 'group', g, label }) + await fn() + await quiesce() + flush() + } + + // --- the scene ------------------------------------------------------------------------------- + // x = 500 is a wall with a door in the middle (y 400..700): the subject starts west of it. + const wallsToAdd = [ + { a: [500, 0], b: [500, 400], kind: 'wall' }, + { a: [500, 400], b: [500, 700], kind: 'door', open: false }, + { a: [500, 700], b: [500, 1000], kind: 'wall' }, + { a: [1400, 400], b: [1400, 900], kind: 'wall' }, + ] + const wallIds = [] + + const addWall = async fields => { + const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields }) + if (ack.ok !== true) throw new Error(`wall.add refused: ${JSON.stringify(ack)}`) + wallIds.push(ack.id) + return ack.id + } + + const createToken = async (id, fields) => { + const ack = await gm.ws.request({ t: 'token.create', scene, ...fields }) + if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`) + ids[id] = ack.id + return ack.id + } + const ids = {} + + const move = async (client, id, pos) => { + const ack = await client.ws.request({ t: 'token.move', id, pos }) + return ack + } + + // Two named players: the naming is the fixture of lib.mjs (player.setname is slice 8). + const playerA = await createPlayer(gm.ws) + const playerB = await createPlayer(gm.ws) + await namePlayer(stateDir, playerA.id, 'Subject A') + await namePlayer(stateDir, playerB.id, 'Player B') + + await group('walls', async () => { + for (const w of wallsToAdd) await addWall(w) + }) + + await group('tokens', async () => { + await createToken('A', { kind: 'pc', pos: [300, 300], descriptive_name: 'A', actual_name: 'A', + controller: playerA.id, flags: { vision: true } }) + await createToken('B', { kind: 'pc', pos: [300, 3000], descriptive_name: 'B', actual_name: 'B', + controller: playerB.id, flags: { vision: true } }) + await createToken('M1', { kind: 'npc', pos: [400, 200], descriptive_name: 'a wolf', + actual_name: 'Fang' }) + await createToken('M2', { kind: 'npc', pos: [560, 550], descriptive_name: 'a guard', + actual_name: 'Captain Vex' }) + await createToken('M3', { kind: 'npc', pos: [350, 350], descriptive_name: 'a shadow', + actual_name: 'The Hidden', gm_only: true }) + await createToken('M4', { kind: 'item', pos: [3500, 3500], descriptive_name: 'a chest', + actual_name: 'The Vault' }) + }) + + const A = await connect(origin, playerA.key, 'A', log) + clients.push(A) + await A.ws.waitText('hello') + await group('connect subject', async () => { await sleep(0) }) + + const B = await connect(origin, playerB.key, 'B', log) + clients.push(B) + await B.ws.waitText('hello') + await group('connect other', async () => { await sleep(0) }) + + // A walks from (300,300) to just west of the door. + await group('A walks to the door', async () => { + expectAck(await move(A, ids.A, [350, 600]), true) + }) + await group('A at the door', async () => { + expectAck(await move(A, ids.A, [350, 620]), true) + }) + await group('M2 is hidden behind the closed door', async () => { await sleep(0) }) + + await group('GM opens the door', async () => { + const ack = await gm.ws.request({ t: 'door.set', scene, id: wallIds[1], open: true }) + if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`) + }) + await group('A steps through the door', async () => { + expectAck(await move(A, ids.A, [560, 600]), true) + }) + await group('A steps into the room', async () => { + expectAck(await move(A, ids.A, [600, 640]), true) + }) + await group('GM moves M1 into the room', async () => { + expectAck(await move(gm, ids.M1, [700, 700]), true) + }) + await group('GM creates a token in view', async () => { + await createToken('N1', { kind: 'item', pos: [520, 700], descriptive_name: 'a lamp', + actual_name: 'Lantern' }) + }) + await group('GM removes it', async () => { + const ack = await gm.ws.request({ t: 'token.remove', id: ids.N1 }) + if (ack.ok !== true) throw new Error(`token.remove refused: ${JSON.stringify(ack)}`) + }) + await group('GM hides M1', async () => { + const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, gm_only: true }) + if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) + }) + await group('GM unhides M1', async () => { + const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, gm_only: false }) + if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) + }) + await group('GM hands M1 to the subject', async () => { + const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, controller: playerA.id }) + if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) + }) + await group('GM moves the subject-owned token far away', async () => { + expectAck(await move(gm, ids.M1, [3000, 3000]), true) + }) + await group('GM hands M1 back to the GM', async () => { + const ack = await gm.ws.request({ t: 'token.update', id: ids.M1, controller: null }) + if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) + }) + await group('GM walks the other player in', async () => { + expectAck(await move(gm, ids.B, [420, 640]), true) + }) + await group('GM walks the other player out', async () => { + expectAck(await move(gm, ids.B, [420, 1500]), true) + }) + await group('GM adds a wall in the subject sight', async () => { + await addWall({ a: [400, 900], b: [900, 900], kind: 'wall' }) + }) + await group('GM removes it again', async () => { + const ack = await gm.ws.request({ t: 'wall.remove', scene, id: wallIds[wallIds.length - 1] }) + if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`) + }) + await group('GM puts M2 on the door line', async () => { + expectAck(await move(gm, ids.M2, [500, 600]), true) + }) + await group('GM closes the door: the server pushes M2 aside', async () => { + const ack = await gm.ws.request({ t: 'door.set', scene, id: wallIds[1], open: false }) + if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`) + }) + await group('A walks away from the door', async () => { + expectAck(await move(A, ids.A, [560, 950]), true) + }) + await group('A walks further south', async () => { + expectAck(await move(A, ids.A, [560, 1300]), true) + }) + await group('end', async () => { await sleep(0) }) + + // Let anything still queued arrive, then close politely. + await sleep(100) + flush() + if (!keepOpen) for (const c of clients) c.ws.close() + + fs.mkdirSync(path.dirname(transcript), { recursive: true }) + fs.writeFileSync(transcript, lines.join('\n') + '\n') + return { transcript, groups: g, walls: wallIds, tokens: ids } +} + +function expectAck(ack, ok) { + const got = ack.ok === true + if (got !== ok) throw new Error(`unexpected ack: ${JSON.stringify(ack)}`) + return ack +} diff --git a/tools/leak.test.mjs b/tools/leak.test.mjs new file mode 100644 index 0000000..2e3c6f0 --- /dev/null +++ b/tools/leak.test.mjs @@ -0,0 +1,34 @@ +// M3 slice 5 (#20), leak test A and B (DESIGN 10.1 "leak test", 10.3): the driver builds a scene +// over the real wire and records every frame each socket saw; tools/leakcheck.nim then verifies the +// subject's whole view against the GM socket (ground truth) and its own geometry. One run per +// subject on its own server; logs land in results/leak-.{jsonl,log}. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { runLeak, runChecker } from './leak.mjs' +import { gmKeyOf, makeStateDir, startServer, stopServer } from './withserver.mjs' +import { projectRoot } from './lib.mjs' + +const results = path.join(projectRoot, 'results') + +for (const subject of ['A', 'B']) { + test(`leak test ${subject}: the subject's whole view matches the GM's truth`, async () => { + fs.mkdirSync(results, { recursive: true }) + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + const transcript = path.join(results, `leak-${subject}.jsonl`) + try { + const run = await runLeak({ origin: s.origin, gmKey, stateDir, transcript }) + assert.ok(run.groups > 15, `the scenario must have real coverage, got ${run.groups} groups`) + const check = runChecker(transcript, subject) + fs.writeFileSync(path.join(results, `leak-${subject}.log`), check.output) + assert.equal(check.status, 0, `${check.output}\n--- server log ---\n${s.log()}`) + assert.match(check.output, / 0 failures/) + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) +} diff --git a/tools/leakcheck.nim b/tools/leakcheck.nim new file mode 100644 index 0000000..665572c --- /dev/null +++ b/tools/leakcheck.nim @@ -0,0 +1,450 @@ +## Leak checker: replays a leak-transcript.jsonl written by tools/leak.mjs and verifies one player's +## whole view (DESIGN 10.1, 10.2, 10.3; M3 slice 5 / #20). Ground truth is the GM socket: the GM sees +## every token and every wall, so the checker never trusts the subject's own messages for *what is*. +## +## Independent oracles: the subject's visibility polygons and explored cells are recomputed from the +## GM's truth with geometry.nim, and the explored set is additionally probed with a clear-segment +## test (no ray fan), because the prototype's explored check was self-consistent only (10.2). +## +## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each +## injected server fault: +## HIDDEN_TOKEN a token the subject may not see reached it +## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS +## WALLDATA a wall-ish key or frame reached the subject +## WITHHELD a token the subject may see was not sent (or was taken away while visible) +## NO_REMOVE a token that left the view was never withdrawn +## OWN_VIEW the subject's own token position or its vision polygon is wrong +## OTHER_PLAYER another player's polygon, `mine` flag, explored cells or presence leaked +## EXPLORED the explored set differs from the recomputation / the clear-segment oracle +## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity) +## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block +## +## usage: leakcheck exit 0 = clean +import std/[algorithm, json, math, options, os, sets, strutils, tables] +import geometry + +const + AllowedTypes = ["hello", "ack", "token", "token_gone", "vision", "explored"] + BannedKeys = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", + "flags", "descriptive_name", "actual_name", "reveal_all", "revealed", "source", + "radius_own", "extra"] + +type + TruthToken = object + pos: Vec + controller: int + gmOnly: bool + hasVision: bool + visionRadius: Option[float] + radius: float + + Truth = object + walls: seq[Wall] + tokens: Table[string, TruthToken] + + Group = object + label: string + gmMsgs: seq[JsonNode] + subjMsgs: seq[JsonNode] + +var fails = 0 +var classes: CountTable[string] + +proc fail(cls, s: string) = + inc fails + classes.inc cls + if fails <= 25: echo "FAIL [", cls, "] ", s + +proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat) + +proc samePos(j: JsonNode, p: Vec): bool = + ## JSON numbers lose their int/float spelling on the wire round trip: compare numerically. + j.kind == JArray and j.len == 2 and + abs(j[0].getFloat - p.x) < 1e-6 and abs(j[1].getFloat - p.y) < 1e-6 + +# --------------------------------------------------------------------------------------------------- +# Transcript + +proc readGroups(path, subject: string): seq[Group] = + ## One entry per group marker; every message belongs to the group that was open when it arrived. + var current = -1 + var groups: seq[Group] + for line in lines(path): + if line.strip.len == 0: continue + let j = parseJson(line) + case j["k"].getStr + of "group": + groups.add Group(label: j["label"].getStr) + current = groups.high + of "msg": + if current < 0: continue + let who = j["who"].getStr + if who == "GM": groups[current].gmMsgs.add j["m"] + elif who == subject: groups[current].subjMsgs.add j["m"] + else: discard + groups + +# --------------------------------------------------------------------------------------------------- +# Truth from the GM socket (walls and every token) + +proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) = + ## `wall` (upsert) and `wall_gone` need the id, which geometry.Wall does not carry. + case m["t"].getStr + of "walls": + truth.walls.setLen(0) + ids.setLen(0) + for w in m["walls"]: + truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), + door: w["kind"].getStr == "door", open: w["open"].getBool) + ids.add w["id"].getInt + of "wall": + let id = m["id"].getInt + let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["kind"].getStr == "door", + open: m["open"].getBool) + var found = false + for i in 0 ..< ids.len: + if ids[i] == id: + truth.walls[i] = w + found = true + if not found: + truth.walls.add w + ids.add id + of "wall_gone": + let id = m["id"].getInt + for i in 0 ..< ids.len: + if ids[i] == id: + truth.walls.delete i + ids.delete i + break + else: discard + +proc applyGmTokens(truth: var Truth, m: JsonNode) = + case m["t"].getStr + of "token": + var t = TruthToken(pos: vec(m["pos"]), controller: (if m["controller"].kind == JNull: 0 + else: m["controller"].getInt), + gmOnly: m["gm_only"].getBool, + hasVision: m["flags"].hasKey("vision") and + m["flags"]["vision"].kind == JBool and + m["flags"]["vision"].getBool, + radius: m["radius"].getFloat) + if m["vision_radius"].kind != JNull: t.visionRadius = some(m["vision_radius"].getFloat) + truth.tokens[m["id"].getStr] = t + of "token_gone": + truth.tokens.del m["id"].getStr + else: discard + +# --------------------------------------------------------------------------------------------------- +# Independent oracles + +proc clearLine(walls: seq[Wall], o, p: Vec): bool = + ## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan). + for w in walls: + if w.blocks and segsCross(o, p, w.a, w.b): return false + true + +proc rangeOf(sceneDefault: float, t: TruthToken): float = + if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get + else: sceneDefault + +proc polygonsOf(truth: Truth, controller: int, sceneDefault: float): seq[(string, seq[Vec])] = + for id, t in truth.tokens: + if t.controller != controller or not t.hasVision: continue + result.add (id, visibilityPolygon(t.pos, truth.walls, rangeOf(sceneDefault, t))) + # deterministic order: by token id (the server keeps creation order; the checker sorts) + result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0])) + +proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool = + for (_, pts) in polys: + if inside(pts, p): return true + +proc cellOf(sceneW: float, cell: int, ix, iy: int): (float, float) = + (float(ix * cell) + float(cell) / 2, float(iy * cell) + float(cell) / 2) + +proc definitelySeen(walls: seq[Wall], polys: seq[(string, seq[Vec])], sceneW: float, + cell, cx, cy: int): bool = + ## A cell is seen if any of its corners or its centre is in clear LOS inside a polygon. The + ## tolerance for the opposite direction (explored but no sample in LOS) lives in the caller. + let (mx, my) = cellOf(sceneW, cell, cx, cy) + let pts = [(mx, my), (float(cx * cell), float(cy * cell)), + (float((cx + 1) * cell), float(cy * cell)), + (float((cx + 1) * cell), float((cy + 1) * cell)), + (float(cx * cell), float((cy + 1) * cell))] + for p in pts: + if insideAny(polys, p) and clearLine(walls, (mx, my), p): return true + false + +proc keysDeep(node: JsonNode, into: var HashSet[string]) = + if node.kind == JObject: + for k, v in node: + into.incl k + keysDeep(v, into) + elif node.kind == JArray: + for v in node: keysDeep(v, into) + +# --------------------------------------------------------------------------------------------------- + +proc checkArgs(): (string, string) = + if paramCount() < 2: + echo "usage: leakcheck " + quit 2 + (paramStr(1), paramStr(2)) + +proc main() = + let (path, subject) = checkArgs() + let groups = readGroups(path, subject) + if groups.len == 0: + echo "leakcheck: no groups in ", path + quit 2 + + var truth: Truth + var wallIds: seq[int] + var me = 0 + var other = 0 + var sceneDefault = 400.0 + var sceneW = 4096.0 + var cell = 32 + var haveHello = false + var expectedN = 1 + + # what the subject has been told + var view: Table[string, JsonNode] # token id -> last `token` frame + var leaked: Table[string, string] # token id -> the class it was first reported under + var exploredSent: HashSet[int] + var otherExplored: HashSet[int] + var removes = 0 + var groupsSeen = 0 + var recomputedSoFar: HashSet[int] # every cell the subject has ever seen, recomputed + var seenAny: HashSet[string] # token ids the subject was legitimately shown + + for g in groups: + inc groupsSeen + for m in g.gmMsgs: + applyGmWalls(truth, wallIds, m) + applyGmTokens(truth, m) + + # player ids: the subject from its hello, the other from any token it does not control + for m in g.subjMsgs: + if m["t"].getStr == "hello": + haveHello = true + me = m["me"]["id"].getInt + if m.hasKey("scene"): + sceneW = m["scene"]["w"].getFloat + cell = m["scene"]["cell"].getInt + sceneDefault = m["scene"]["vision_radius_default"].getFloat + else: + fail "PROTOCOL", "hello without a scene block for a named player" + for id, t in truth.tokens: + if me != 0 and t.controller != me and t.controller != 0 and + (other == 0 or t.controller < other): + other = t.controller + + # Before the subject's hello there is no subject side to check: `me` is unknown, so "mine" and + # "visible to the subject" would both be meaningless. Always apply the GM truth first. + if me == 0: continue + + let polys = polygonsOf(truth, me, sceneDefault) + let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault) else: @[] + + # the other player's explored cells, independently (attribute leaks, 3.1 OTHER_PLAYER) + for (_, pts) in otherPolys: + for (cx, cy) in cellsTouched(pts, float(cell)): + if cx < 0 or cy < 0: continue + otherExplored.incl cy * int(ceil(sceneW / float(cell))) + cx + + # --- the subject's frames of this group ----------------------------------------------------- + for m in g.subjMsgs: + let t = m["t"].getStr + if not m.hasKey("n") or m["n"].getInt != expectedN: + fail "PROTOCOL", "n " & (if m.hasKey("n"): $m["n"].getInt else: "missing") & + " where " & $expectedN & " was expected (" & t & ")" + expectedN = (if m.hasKey("n"): m["n"].getInt else: expectedN) + 1 + if t notin AllowedTypes: + fail (if t in ["walls", "wall", "wall_gone"]: "WALLDATA" else: "PROTOCOL"), + "frame type the catalogue forbids: " & t + continue + var keys = initHashSet[string]() + keysDeep(m, keys) + for k in keys: + if k in BannedKeys: fail "WALLDATA", "player frame has wall-ish/GM-only key " & k + case t + of "ack": + # only a bad shape is interesting here; the driver already checked the outcomes it expected + if m["ok"].getBool and m.hasKey("code"): fail "PROTOCOL", "ok ack with a code" + of "token": + let id = m["id"].getStr + if id notin truth.tokens: + fail "HIDDEN_TOKEN", "token " & id & " is not in the GM's truth" + continue + let actual = truth.tokens[id] + if not samePos(m["pos"], actual.pos): + fail "OWN_VIEW", "token " & id & " position " & $m["pos"] & " != truth " & + $[actual.pos.x, actual.pos.y] + let wantMine = actual.controller == me + if m["mine"].getBool != wantMine: + fail (if wantMine: "OWN_VIEW" else: "OTHER_PLAYER"), "mine flag on " & id + view[id] = m + let visible = wantMine or (not actual.gmOnly and insideAny(polys, actual.pos)) + if not visible: + let cls = if actual.gmOnly and insideAny(polys, actual.pos): "GMONLY_TOKEN" + else: "HIDDEN_TOKEN" + leaked[id] = cls + fail cls, "token " & id & " sent but not visible (group " & g.label & ")" + else: + seenAny.incl id + of "token_gone": + let id = m["id"].getStr + if id notin view: + fail "PROTOCOL", "token_gone for a token this player never had: " & id + else: + view.del id + inc removes + if id in truth.tokens: + let actual = truth.tokens[id] + if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)): + fail "WITHHELD", "token_gone for a token still visible: " & id + of "vision": + var got: seq[(string, seq[Vec])] + for p in m["polys"]: + var pts: seq[Vec] + for q in p["pts"]: pts.add vec(q) + got.add (p["id"].getStr, pts) + let want = polys + var haveIds = initHashSet[string]() + for (id, pts) in got: + haveIds.incl id + var matched = false + for (wid, wpts) in want: + if wid != id: continue + matched = true + if pts.len != wpts.len: + fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices" + else: + for i in 0 ..< pts.len: + # integer px on the wire (6.4): 0.5 px is the documented tolerance + if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6: + fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] & + " not " & $wpts[i] + break + if not matched: + var theirs = false + for (oid, _) in otherPolys: + if oid == id: theirs = true + fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"), + "vision carries a polygon for a token this player does not control: " & id + for (id, _) in want: + if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id + of "explored": + if m["full"].getBool: + # a resync snapshot replaces the set; every cell must be one the recomputation has seen + var cells: seq[(int, int)] + let cols = int(ceil(sceneW / float(cell))) + for row in m["rle"]: + let cy = row[0].getInt + var i = 1 + while i + 1 < row.len: + let x0 = row[i].getInt + let len = row[i + 1].getInt + for k in 0 ..< len: cells.add (x0 + k, cy) + i += 2 + discard cols + exploredSent = initHashSet[int]() + for (cx, cy) in cells: exploredSent.incl cy * int(ceil(sceneW / float(cell))) + cx + else: + for c in m["cells"]: + let cx = c[0].getInt + let cy = c[1].getInt + let k = cy * int(ceil(sceneW / float(cell))) + cx + exploredSent.incl k + else: discard + + # --- the set of tokens the subject should hold at the end of this group --------------------- + for id, actual in truth.tokens: + let want = actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)) + let have = view.hasKey(id) + if want and not have: + fail "WITHHELD", "visible token never sent: " & id & " (group " & g.label & ")" + elif not want and have: + # A token that was never legitimately in view stays a leak under its first class; one that + # was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides, + # so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak. + if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id + elif id notin seenAny and actual.gmOnly and insideAny(polys, actual.pos): + fail "GMONLY_TOKEN", "gm_only token still in view: " & id + else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id & + " (group " & g.label & ")" + elif want and have: + if not samePos(view[id]["pos"], actual.pos): + fail "OWN_VIEW", "stale position for " & id + + # --- the explored set ---------------------------------------------------------------------- + var recomputed: HashSet[int] + let cols = int(ceil(sceneW / float(cell))) + let rows = int(ceil(sceneW / float(cell))) + for (_, pts) in polys: + for (cx, cy) in cellsTouched(pts, float(cell)): + # cells outside the world are not cells: the server drops them too (vision.refresh) + if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue + recomputed.incl cy * cols + cx + for k in recomputed: recomputedSoFar.incl k + var suspect = initCountTable[string]() + for k in exploredSent: + # explored only grows (5.1): a cell seen in an earlier group is legitimately explored now + if k in recomputedSoFar: continue + let cx = k mod cols + let cy = k div cols + if definitelySeen(truth.walls, polys, sceneW, cell, cx, cy): + recomputed.incl k # grazed cell the sampler does see: fine either way + continue + # attribution: a cell only the other player has explored is a presence leak, not a bad cell + let cls = if k in otherExplored: "OTHER_PLAYER" else: "EXPLORED" + suspect.inc(cls) + if suspect[cls] <= 3: + fail cls, "explored cell (" & $cx & "," & $cy & ") is outside the subject's sight (group " & + g.label & ")" + for cls, n in suspect: + if n > 3: fail cls, $n & " explored cells the subject never saw (group " & g.label & ")" + # completeness: every cell the recomputation says is seen must have been sent + var missing = 0 + for k in recomputed: + if k notin exploredSent: + inc missing + if missing <= 3: fail "EXPLORED", "recomputed explored cell never sent: " & $k + if missing > 3: + fail "EXPLORED", $missing & " recomputed explored cells were never sent" + if getEnv("LEAK_DEBUG") != "": + for (id, pts) in polys: + var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1 + for (cx, cy) in cellsTouched(pts, float(cell)): + cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy) + echo " poly ", id, " verts ", pts.len, " cells x ", cx0, "..", cx1, " y ", cy0, "..", cy1, + " group ", g.label, " cell ", cell, " sceneW ", sceneW + + # --- the clear-segment oracle on the polygon itself ----------------------------------------- + for (id, pts) in polys: + if pts.len < 3: continue + var t: TruthToken + for tid, tt in truth.tokens: + if tid == id: t = tt + let o = t.pos + let r = rangeOf(sceneDefault, t) + for i in 0 ..< 64: + for k in [0.3, 0.6, 0.95]: + let p: Vec = (o.x + k * r * cos(2 * PI * i.float / 64), + o.y + k * r * sin(2 * PI * i.float / 64)) + if p.x < 0 or p.y < 0 or p.x > sceneW or p.y > sceneW: continue + if clearLine(truth.walls, o, p) and not inside(pts, p): + fail "GEOMETRY", "polygon " & id & " misses a clear-LOS point " & $p + + if not haveHello: fail "PROTOCOL", "no hello for the subject" + if me == 0: fail "PROTOCOL", "no player id in hello" + if removes == 0: fail "NO_REMOVE", "the scenario never withdrew a token (harness coverage)" + if seenAny.len < 3: fail "WITHHELD", "the scenario never showed the subject 3 tokens" + + for cls, n in classes: echo "FAILCLASS ", cls, " ", n + echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ", + view.len, " tokens in view at the end, ", removes, " withdrawals, ", exploredSent.len, + " explored cells, ", fails, " failures" + quit(if fails > 0: 1 else: 0) + +main() diff --git a/tools/lib.mjs b/tools/lib.mjs index 1c83688..8dd47c1 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -6,6 +6,7 @@ import crypto from 'node:crypto' import fs from 'node:fs' import net from 'node:net' import path from 'node:path' +import { DatabaseSync } from 'node:sqlite' import { fileURLToPath } from 'node:url' export const sleep = ms => new Promise(r => setTimeout(r, ms)) @@ -408,3 +409,34 @@ export async function collectAcks(client, ids, timeoutMs = 5000) { await sleep(5) } } + +// --------------------------------------------------------------------------------------------- +// Slice 5 (#20) fixtures: naming a player out of band. +// +// DESIGN 3.2 gives a player their display name at first sign-in, through `player.setname` - and +// `player.setname` is slice 8 (#23). Until then every non-GM connection is *unnamed*, and 6.1/6.5 +// refuse an unnamed player everything but `conn.ping`: no scene block, no resync, no intents. The +// player-side acceptance of this slice (leak test A and B, WS probing) therefore cannot be reached +// through the product's own surface yet, so the harness writes the name into the DB before the +// connection is opened. That is a fixture, not a product path: the unnamed-player gate itself is +// pinned by tools/tokens.test.mjs (hello without a scene block, `not-allowed` for every intent). +export async function namePlayer(stateDir, playerId, name) { + const dbPath = path.join(stateDir, 'state.db') + let lastError + for (let attempt = 0; attempt < 40; attempt++) { + const db = new DatabaseSync(dbPath) + try { + db.exec('PRAGMA busy_timeout=5000') + db.prepare('UPDATE player SET name = ? WHERE id = ?').run(name, playerId) + const row = db.prepare('SELECT name FROM player WHERE id = ?').get(playerId) + if (!row || row.name !== name) throw new Error(`naming player ${playerId} failed`) + return + } catch (e) { + lastError = e + } finally { + try { db.close() } catch {} + } + await sleep(25) // SQLITE_BUSY while the server holds the write lock: back off and retry + } + throw lastError +} diff --git a/tools/withserver.mjs b/tools/withserver.mjs index d2f34e0..3f56c3b 100644 --- a/tools/withserver.mjs +++ b/tools/withserver.mjs @@ -15,16 +15,25 @@ function nimblePkgs() { } let builtAt = null +const builtCache = new Map() -export function buildServer() { - if (builtAt) return builtAt - fs.mkdirSync(path.dirname(SERVER_BIN), { recursive: true }) +// Build the real binary from the working tree. `defines` adds `-d:` flags (a leak-fault build, +// DESIGN 10.3); each variant lands in its own file so the clean build is never overwritten. +export function buildServer(opts = {}) { + const defines = opts.defines ?? [] + const key = defines.join(',') + const out = opts.out ?? (defines.length === 0 + ? SERVER_BIN + : path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`)) + if (builtCache.has(key)) return builtCache.get(key) + fs.mkdirSync(path.dirname(out), { recursive: true }) const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`, - `-o:${SERVER_BIN}`, path.join('server', 'main.nim')] + ...defines.map(d => `-d:${d}`), `-o:${out}`, path.join('server', 'main.nim')] const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' }) - if (r.status !== 0) throw new Error(`nim c server/main.nim failed:\n${r.stdout}\n${r.stderr}`) - builtAt = SERVER_BIN - return builtAt + if (r.status !== 0) throw new Error(`nim c server/main.nim ${defines.join(' ')} failed:\n${r.stdout}\n${r.stderr}`) + builtAt = out + builtCache.set(key, out) + return out } export function makeStateDir(prefix = 'fffvtt-') { @@ -52,11 +61,12 @@ 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. export async function startServer(opts = {}) { const ownStateDir = opts.stateDir === undefined const stateDir = opts.stateDir ?? makeStateDir() const args = opts.args ?? [] - const bin = buildServer() + const bin = buildServer({ defines: opts.defines }) const port = opts.port ?? await freePort() refuseLivePort(port) fs.mkdirSync(stateDir, { recursive: true }) @@ -64,7 +74,8 @@ export async function startServer(opts = {}) { const logFd = fs.openSync(logPath, 'a') const child = spawn(bin, [`--port=${port}`, `--state-dir=${stateDir}`, `--public-origin=${baseUrl(port)}`, ...args], - { cwd: projectRoot, stdio: ['ignore', logFd, logFd] }) + { cwd: projectRoot, stdio: ['ignore', logFd, logFd], + env: { ...process.env, ...(opts.env ?? {}) } }) const handle = { port, origin: baseUrl(port), stateDir, dbPath: path.join(stateDir, 'state.db'), logPath, child, log: () => fs.readFileSync(logPath, 'utf8'),