Files
FFF_vtt_frozen/tools/leak.mjs
T
SirStone 8e045b0ac8 names: per-player reveal, one encountered write path, link by update (#27, #29, #30)
name.reveal wrote the subject's actual name into the encountered row of every
player who had met it: the SQL had no player predicate, so the leak was silent
live and visible only after a restart. rewriteEncountered is now the one path
that keeps a snapshot in step with its subject: it rewrites the SQLite row and
the live in-memory entry together from the name rule, takes onlyPlayer for
name.reveal (every player for reveal_all), and also runs on a rename, a link
change and an owner change, so the wire and a post-restart reload cannot
disagree (#30). The DB-only renameEncountered*/revealEncountered* helpers are
gone, which is what let the two stores drift.

token.update {character_id} now drops the token's own two names as part of the
link patch (#29): a plain token can be linked, names supplied with a link stay
invalid and unlinking still needs both names.

Tests: tcharacters covers the per-player row, the DB/memory equality, the link
handover; restart.test.mjs builds three named players, reveals to one of them
and asserts the rows directly and the whole resync over SIGTERM/SIGKILL, plus a
mid-session rename; leak.mjs/leakcheck.nim pit two players on the same subject
and pin each entry's expected name (STALE_NAME). Mutations e1-e3 and the
repointed b2 pin the three rules.
2026-11-15 14:26:07 +01:00

391 lines
19 KiB
JavaScript

// 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)
// - slice 7 (#22): props written into all three buckets on a token the subject can see, a
// GM-sourced status, a walls-sourced stuck from a new wall, a resize, and a prop.unset — every
// frame of the group is checked for the bucket and the `source` it must not carry
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. Every intent a client sends
// is logged too (`k:'intent'`): the checker needs it to tell an intended controller change from one
// a character edit caused (the CONTROLLER_CHANGE class, DESIGN 10.3).
async function connect(origin, key, who, log, group) {
const { cookie } = await signIn(origin, key)
const ws = await openWs(origin, cookie)
return {
who, ws, logged: 0, log,
request(fields) {
log({ k: 'intent', g: group(), who, t: fields.t, f: fields })
return ws.request(fields)
},
}
}
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, () => g)
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.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.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 characters = {}
const move = async (client, id, pos) => {
const ack = await client.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(origin, playerA.key, 'Subject A')
await namePlayer(origin, playerB.key, '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, () => g)
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, () => g)
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.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.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.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.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.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.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.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.request({ t: 'door.set', scene, id: wallIds[1], open: false })
if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`)
})
// Slice 7 (#22): a token the subject can see, in every bucket and with a status. N2 sits 60 px
// north-east of A, so every frame of these groups is one the subject receives.
await group('GM creates N2 in view', async () => {
await createToken('N2', { kind: 'item', pos: [660, 600], descriptive_name: 'a rune',
actual_name: 'The Rune' })
})
for (const [bucket, value] of [['public', 'cold'], ['owner', 3], ['gm', 'the duke']]) {
await group(`GM writes the ${bucket} prop of N2`, async () => {
const ack = await gm.request({ t: 'prop.set', target: 'token', id: ids.N2, bucket,
key: 'aura', value })
if (ack.ok !== true) throw new Error(`prop.set refused: ${JSON.stringify(ack)}`)
})
}
await group('GM sets a GM-sourced status on N2', async () => {
const ack = await gm.request({ t: 'status.set', id: ids.N2, status: 'squeezed' })
if (ack.ok !== true) throw new Error(`status.set refused: ${JSON.stringify(ack)}`)
})
await group('GM resizes N2', async () => {
const resized = await gm.request({ t: 'token.resize', id: ids.N2, radius: 45 })
if (resized.ok !== true) throw new Error(`token.resize refused: ${JSON.stringify(resized)}`)
})
await group('GM adds a wall over N2 (stuck, source walls)', async () => {
await addWall({ a: [700, 560], b: [700, 660], kind: 'wall' })
})
await group('GM unsets the public prop of N2', async () => {
const unset = await gm.request({ t: 'prop.unset', target: 'token', id: ids.N2,
bucket: 'public', key: 'aura' })
if (unset.ok !== true) throw new Error(`prop.unset refused: ${JSON.stringify(unset)}`)
})
await group('GM clears the GM-sourced status of N2', async () => {
const cleared = await gm.request({ t: 'status.clear', id: ids.N2, status: 'squeezed',
source: 'GM' })
if (cleared.ok !== true) throw new Error(`status.clear refused: ${JSON.stringify(cleared)}`)
})
await group('GM removes the wall over N2', async () => {
const ack = await gm.request({ t: 'wall.remove', scene,
id: wallIds[wallIds.length - 1] })
if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`)
})
// Slice 8 (#23): characters, names and the encountered list. Every group here is one the subject
// receives: A is in the room, and C1's token is placed next to A's own.
await group('GM creates a character owned by the other player', async () => {
const ack = await gm.request({ t: 'character.create', descriptive_name: 'a cloaked figure',
actual_name: 'Lady Vex', owner: playerB.id })
if (ack.ok !== true) throw new Error(`character.create refused: ${JSON.stringify(ack)}`)
characters.C1 = ack.id
})
await group('GM puts a token of the character in the subject sight', async () => {
const ack = await gm.request({ t: 'token.create', scene, kind: 'pc', pos: [600, 560],
character_id: characters.C1 })
if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`)
ids.C1 = ack.id
})
// #27/#30: a second player meets the same token of the same character, so the transcript carries
// two encountered lists whose names can be compared independently (leakcheck runs once per
// subject). The later rename and reveals must reach this player's snapshot too, and a reveal to
// the *other* player must not.
await group('GM walks the other player into the room again', async () => {
expectAck(await move(gm, ids.B, [650, 700]), true)
})
// One mutation per group (the driver's contract): the checker evaluates a group as one state, so
// two prop writes in one group would compare an intermediate frame against the final truth.
for (const [bucket, value] of [['public', 'noble'], ['owner', 4], ['gm', 'the duke']]) {
await group(`GM writes the ${bucket} prop of the character`, async () => {
const ack = await gm.request({ t: 'prop.set', target: 'character', id: characters.C1, bucket,
key: 'rank', value })
if (ack.ok !== true) throw new Error(`prop.set refused: ${JSON.stringify(ack)}`)
})
}
await group('GM renames the character', async () => {
const ack = await gm.request({ t: 'character.update', id: characters.C1,
descriptive_name: 'a tall stranger' })
if (ack.ok !== true) throw new Error(`character.update refused: ${JSON.stringify(ack)}`)
})
await group('GM reveals the actual name to the subject only', async () => {
const ack = await gm.request({ t: 'name.reveal', subject: 'character', id: characters.C1,
player: playerA.id })
if (ack.ok !== true) throw new Error(`name.reveal refused: ${JSON.stringify(ack)}`)
})
await group('GM reveals the actual name to everyone', async () => {
const ack = await gm.request({ t: 'name.reveal_all', subject: 'character', id: characters.C1 })
if (ack.ok !== true) throw new Error(`name.reveal_all refused: ${JSON.stringify(ack)}`)
})
await group('GM hands the character to the subject (controllers must not move)', async () => {
const ack = await gm.request({ t: 'character.reassign', id: characters.C1, owner: playerA.id })
if (ack.ok !== true) throw new Error(`character.reassign refused: ${JSON.stringify(ack)}`)
})
await group('GM gives the character back to the other player', async () => {
const ack = await gm.request({ t: 'character.reassign', id: characters.C1, owner: playerB.id })
if (ack.ok !== true) throw new Error(`character.reassign refused: ${JSON.stringify(ack)}`)
})
await group('GM reveals a plain token actual name to the subject', async () => {
const ack = await gm.request({ t: 'name.reveal', subject: 'token', id: ids.N2,
player: playerA.id })
if (ack.ok !== true) throw new Error(`name.reveal refused: ${JSON.stringify(ack)}`)
})
await group('GM reveals that plain token to everyone', async () => {
const ack = await gm.request({ t: 'name.reveal_all', subject: 'token', id: ids.N2 })
if (ack.ok !== true) throw new Error(`name.reveal_all refused: ${JSON.stringify(ack)}`)
})
await group('GM walks the other player out again', async () => {
expectAck(await move(gm, ids.B, [420, 1500]), true)
})
await group('GM hides the character token (the encountered entry stays, greyed)', async () => {
const ack = await gm.request({ t: 'token.update', id: ids.C1, gm_only: true })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM shows it again', async () => {
const ack = await gm.request({ t: 'token.update', id: ids.C1, gm_only: false })
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
})
await group('GM removes the character token (the entry stays, greyed)', async () => {
const ack = await gm.request({ t: 'token.remove', id: ids.C1 })
if (ack.ok !== true) throw new Error(`token.remove refused: ${JSON.stringify(ack)}`)
})
await group('GM removes one encountered entry of the subject', async () => {
const ack = await gm.request({ t: 'encountered.remove', player: playerA.id, id: ids.N2 })
if (ack.ok !== true) throw new Error(`encountered.remove 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, characters }
}
function expectAck(ack, ok) {
const got = ack.ok === true
if (got !== ok) throw new Error(`unexpected ack: ${JSON.stringify(ack)}`)
return ack
}