tools: WS probing and the token wire tests (#20)

tools/probing.test.mjs re-runs the M2 T8 probing test over the wire with a hostile
client: over-cap probes always get the one uniform nack (old position, no code), two
servers whose walls differ only beyond cap + token radius answer 90 identical
probes identically, and a wall inside that bound does change the replies, so the
harness is shown able to fail. It stays inside the 6.4 burst, so no probe is a rate
limit.

tools/tokens.test.mjs pins the wire behaviour of the slice: the 6.1 acks and codes,
the controller-only and GM-only rules, the connect resync order, the unnamed-player
gate, the door push and a restart.

tools/mutation.sh gains aa-af: the egress ignoring the view rule, gm_only and the
owner arm of the rule, a missing token_gone, a GM-only field in a player frame, and
explored forgetting cells.
This commit is contained in:
2026-11-15 09:35:29 +01:00
parent 959412ff09
commit cae20d7c89
3 changed files with 586 additions and 2 deletions
+24 -2
View File
@@ -12,6 +12,9 @@
# t: wall removal renumbers next_wall_id (the dense-id design, #3) | u: the id counter is not loaded from the DB
# v: the id counter is never written to the DB | w: a wall may stay open | x: zero-length walls accepted
# y: wall endpoints unchecked against the world bounds | z: door.set on a plain wall accepted | z2: persisted `open` loaded inverted
# aa: the egress sends every token (LOS and gm_only ignored) | ab: gm_only ignored in the view rule
# ac: a controlled token is not always visible | ad: no token_gone when a token leaves view
# ae: a player token frame carries the GM-only `kind` | af: explored forgets the cells outside the current polygon
# Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order.
# Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected
# test are run per mutation (control runs all). Debug build. Wrapped in systemd-inhibit (sleep:idle) when that works.
@@ -54,7 +57,13 @@ LOG=$PWD/results/mutation.log
JOBS=${MUTATION_JOBS:-$(( $(nproc) / 4 ))}; [ "$JOBS" -ge 1 ] || JOBS=1
export FFF_MUTATION=1
T=$(mktemp -d -t fffmut.XXXXXX)
PIDS=()
PAA="the set of tokens follows the visibility rule"
AB="a gm_only token inside the LOS is not visible"
AC="a controlled token is always visible"
AD="leaving view sends"
AE="no GM-only field"
AF="moving adds cells and never forgets"
IDS=()
cleanup() { trap - EXIT INT TERM; local p; for p in "${PIDS[@]}"; do kill -TERM -- "-$p" 2>/dev/null; done; wait 2>/dev/null; rm -rf "$T"; }
trap cleanup EXIT; trap 'exit 130' INT; trap 'exit 143' TERM
NEW="shared endpoint: no leak at the vertex|'<' apex|every segment endpoint|rays nudged past a corner"
@@ -74,6 +83,12 @@ P="refill is continuous"
Q="reqId boundaries"
R="nine malformed frames are tolerated"
S="the frame counter starts at 1"
AA="the set of tokens follows the visibility rule"
AB="a gm_only token inside the LOS is not visible"
AC="a controlled token is always visible"
AD="leaving view sends"
AE="no GM-only field"
AF="moving adds cells and never forgets"
IDS=()
run() {
while [ "$(jobs -rp | wc -l)" -ge "$JOBS" ]; do wait -n; done
@@ -112,9 +127,16 @@ run x "zero-length walls accepted" server/world.nim 's/ (rec\.a\.x != rec\.b\.x
run y "wall endpoints unchecked against the world bounds" server/world.nim 's/p\.x >= 0 and p\.y >= 0 and p\.x <= sc\.w and p\.y <= sc\.h/p.x >= 0 and p.y >= 0/' "both endpoints must be inside"
run z "door.set accepted on a plain wall" server/world.nim '/if sc.walls\[idx.get\].kind != wkDoor: return waNotDoor/d' "wrong kinds are their own"
run z2 "persisted open state loaded inverted" server/world.nim 's/open: row\[6\] == "1",/open: row[6] == "0",/' "round-trip through a reload"
# slice 5 (#20): the view rule, the egress diff and the explored set
run aa "the egress ignores LOS, gm_only and ownership" server/views.nim 's/^ if not pv\.visibleTo(t, playerId): continue$/ if false: continue/' "$AA"
run ab "gm_only ignored by the view rule" server/vision.nim '/^ if t\.gmOnly: return false$/d' "$AB"
run ac "a controlled token is not always visible" server/vision.nim '/^ if t\.owner == playerId: return true$/d' "$AC"
run ad "no token_gone when a token leaves the view" server/views.nim 's/^ result\.add tokenGoneFrame(id)$/ discard/' "$AD"
run ae "a player token frame carries the GM-only kind" server/views.nim 's/ "statuses": \[\], "props": props/ "statuses": [], "props": props, "kind": "npc"/' "$AE"
run af "explored forgets cells outside the current polygon" server/vision.nim 's/^ for idx in added: pv\.explored\.incl idx$/ pv.explored = added/' "$AF"
wait
rc=0; : > "$LOG"
for id in control a b c d1 d2 e f g h i j k l m n o p q r s t u v w x y z z2; do
for id in control a b c d1 d2 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af; do
[ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG"
if [ -f "$T/$id/verdict" ]; then tee -a "$LOG" < "$T/$id/verdict"; [ "$(cat "$T/$id/rc")" = 0 ] || rc=1
else echo "$id: NO RESULT (job killed?)" | tee -a "$LOG"; rc=1; fi
+163
View File
@@ -0,0 +1,163 @@
// M3 slice 5 (#20), test group "probing" (DESIGN 3.4 T8, 10.3, 5.5; H26): the in-process T8 test of
// M2, re-run over the real wire with a hostile client.
//
// Attacker model: a player who controls one token and may send `token.move` with any destination.
// The only thing they learn is the shape of the reply: `{ok:true, pos}` or the uniform nack
// `{ok:false, pos:<old>}` (5.5, T9). Claims, over WS:
// P1 a probe longer than the step cap always gets the same nack, whatever the walls are;
// P2 two scenes that differ only in walls farther than cap + token radius from every position the
// token ever occupied produce IDENTICAL reply sequences, however many probes;
// P3 negative control: a wall INSIDE that bound does change the replies (the harness can fail);
// P4 nacks mutate nothing: the token never moves when refused.
// The rate limit (30/s, burst 100) is a transport bound of 6.4, not the oracle: the run stays inside
// the burst so every probe is answered as an intent.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { createPlayer, namePlayer, openWs, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, signIn, startServer, stopServer } from './withserver.mjs'
import { projectRoot } from './lib.mjs'
const CAP = 400 // the scene's vision_radius_default, also the step cap (5.5)
const RADIUS = 20 // the scene's token radius
const BOUND = CAP + RADIUS // no wall beyond this distance from any visited position is observable
const START = [1000, 2000]
const PROBES = 90 // inside the 100-intent burst of 6.4
// Deterministic xorshift, so both runs send exactly the same probe sequence when the replies agree.
function makeRng(seed) {
let s = BigInt(seed)
return {
next() {
s ^= (s << 13n) & 0xffffffffffffffffn
s ^= s >> 7n
s ^= (s << 17n) & 0xffffffffffffffffn
s &= 0xffffffffffffffffn
return Number(s >> 11n) / Number(1n << 53n)
},
}
}
async function setup(farWalls, nearWalls = []) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
const gm = await openWs(s.origin, (await signIn(s.origin, gmKey)).cookie)
await gm.waitText('hello')
const scene = (await gm.waitText('walls')).scene
const addWall = async fields => {
const ack = await gm.request({ t: 'wall.add', scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
}
for (const w of nearWalls) await addWall(w)
for (const w of farWalls) await addWall(w)
const player = await createPlayer(gm)
await namePlayer(stateDir, player.id, 'Prober')
const tok = await gm.request({ t: 'token.create', scene, kind: 'pc', pos: START,
descriptive_name: 'prober', actual_name: 'Prober',
controller: player.id, flags: { vision: true } })
const a = await openWs(s.origin, (await signIn(s.origin, player.key)).cookie)
await a.waitText('hello')
await sleep(100)
return { s, gm, a, stateDir, tokenId: tok.id, playerId: player.id }
}
async function teardown(ctx) {
try { ctx.gm.close(); ctx.a.close() } catch {}
await stopServer(ctx.s)
fs.rmSync(ctx.stateDir, { recursive: true, force: true })
}
// Runs the probe sequence and returns the replies plus what else the client saw.
async function probe(ctx) {
const rng = makeRng(20261115)
const replies = []
let pos = START
let overCap = 0
let acks = 0
let nacks = 0
const badNacks = []
for (let i = 0; i < PROBES; i++) {
const over = i % 3 !== 0 // two over-cap probes for every one inside the cap
const angle = rng.next() * 2 * Math.PI
const len = over ? CAP + 1 + rng.next() * 400 : rng.next() * CAP
const dest = [
Math.min(4095, Math.max(0, pos[0] + len * Math.cos(angle))),
Math.min(4095, Math.max(0, pos[1] + len * Math.sin(angle))),
]
const distance = Math.hypot(dest[0] - pos[0], dest[1] - pos[1])
const ack = await ctx.a.request({ t: 'token.move', id: ctx.tokenId, pos: dest })
replies.push({ ok: ack.ok, pos: ack.pos, code: ack.code })
if (ack.ok) {
acks++
pos = ack.pos
} else {
nacks++
if (distance > CAP + 1e-9) {
overCap++
// P1: one shape, the old position, no reason (5.5, T9). A code or a moved token would leak.
if (ack.code !== undefined || ack.pos[0] !== pos[0] || ack.pos[1] !== pos[1]) {
badNacks.push({ i, distance, ack })
}
}
}
}
return { replies, pos, overCap, acks, nacks, badNacks }
}
const farA = [
{ a: [3000, 1000], b: [3000, 3000], kind: 'wall' },
{ a: [3200, 1200], b: [3400, 2600], kind: 'door', open: false },
]
const farB = [
{ a: [3050, 2400], b: [3600, 2400], kind: 'wall' },
{ a: [3100, 1500], b: [3100, 1900], kind: 'door', open: true },
{ a: [3800, 1000], b: [3900, 3900], kind: 'wall' },
]
// Inside the bound relative to START: 150 px east.
const nearExtra = [{ a: [1150, 1900], b: [1150, 2100], kind: 'wall' }]
test('probing over WS: walls beyond cap + radius change no reply', async () => {
fs.mkdirSync(path.join(projectRoot, 'results'), { recursive: true })
const a = await setup(farA, nearExtra)
const b = await setup(farB, nearExtra)
try {
const ra = await probe(a)
const rb = await probe(b)
assert.ok(ra.acks > 5 && ra.nacks > 5, `the run must both move and be refused: ${JSON.stringify(ra)}`)
assert.ok(ra.overCap > 40, `the run must be mostly over-cap probes: ${ra.overCap}`)
assert.deepEqual(ra.badNacks, [], 'P1: an over-cap probe got state (a code or a moved token)')
const shape = r => r.replies.map(x => `${x.ok}|${x.pos[0]}|${x.pos[1]}`)
assert.deepEqual(shape(ra), shape(rb),
'P2: the reply sequence depends on walls beyond the bound')
assert.deepEqual(ra.replies.filter(r => r.code !== undefined), [],
'no probe was refused by the rate limit: the burst covers the run')
// P4: nacks never moved the token, and the server's own view agrees with the last ack
await sleep(150)
const gmTokens = b.gm.messages.filter(m => m.t === 'token' && m.id === b.tokenId)
const last = gmTokens[gmTokens.length - 1]
assert.deepEqual(last.pos, rb.pos, 'P4: the token ended where the last ack said')
fs.appendFileSync(path.join(projectRoot, 'results', 'probing.log'),
`probes=${PROBES} acks=${ra.acks} nacks=${ra.nacks} overCap=${ra.overCap} ` +
`identical=true\n`)
} finally {
await teardown(a)
await teardown(b)
}
})
test('probing over WS: a wall inside the bound does change the replies (the harness can fail)', async () => {
const plain = await setup(farA)
const extra = await setup(farA, nearExtra)
try {
const rp = await probe(plain)
const re = await probe(extra)
const shape = r => r.replies.map(x => `${x.ok}|${x.pos[0]}|${x.pos[1]}`)
assert.notDeepEqual(shape(rp), shape(re),
'P3: a wall within the bound must be observable through the replies')
} finally {
await teardown(plain)
await teardown(extra)
}
})
+399
View File
@@ -0,0 +1,399 @@
// M3 slice 5 (#20): tokens and sight over the real wire. The 6.1 acks and codes of
// token.create/update/move/remove, the GM-only and controller-only rules, the `vision`/`explored`
// resync and the token_gone paths, the unnamed-player gate of 6.1/6.5, the door push of 5.5, and a
// restart that brings every token back. The exhaustive leak/fault proof is tools/leak.test.mjs.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { createPlayer, namePlayer, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer, withGmServer } from './withserver.mjs'
const stripN = msg => { const { n, ...rest } = msg; return rest }
async function gmConnect(origin, gmKey) {
const conn = await openAs(origin, gmKey)
await conn.ws.waitText('hello')
const walls = await conn.ws.waitText('walls')
return { ...conn, scene: walls.scene, walls }
}
// A named player: naming is the harness fixture of lib.mjs until slice 8 brings player.setname.
async function namedPlayer(stateDir, gm, name) {
const player = await createPlayer(gm.ws)
await namePlayer(stateDir, player.id, name)
return player
}
async function playerConnect(origin, player, expectTokens = 0) {
const conn = await openAs(origin, player.key)
await conn.ws.waitText('hello')
if (expectTokens > 0) await conn.ws.waitFor(m => m.t === 'token', 5000)
return conn
}
const tokenFrames = ws => ws.messages.filter(m => m.t === 'token')
test('token.create: ack with the id, the token to the GM, invisible to a player out of range', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const player = await namedPlayer(s.stateDir, gm, 'Alice')
const p = await playerConnect(s.origin, player)
const ack = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'a grumpy man', actual_name: 'Lord Vex' })
assert.equal(ack.ok, true)
assert.equal(typeof ack.id, 'string')
assert.equal(ack.id.length, 12, 'ids are 12 characters (DESIGN 8)')
assert.match(ack.id, /^[A-Za-z0-9_-]{12}$/)
assert.equal(ack.code, undefined)
const gmView = await gm.ws.waitFor(m => m.t === 'token' && m.id === ack.id)
assert.equal(gmView.scene, gm.scene)
assert.deepEqual(gmView.pos, [400, 400])
assert.equal(gmView.name, 'a grumpy man', 'the descriptive name is what a recipient sees')
assert.equal(gmView.radius, 20, 'the scene token_radius_default (#4, slice 7)')
assert.equal(gmView.mine, false)
assert.equal(gmView.kind, 'pc')
assert.equal(gmView.controller, null)
assert.equal(gmView.gm_only, false)
assert.deepEqual(gmView.flags, {})
assert.equal(gmView.actual_name, 'Lord Vex')
assert.equal(gmView.descriptive_name, 'a grumpy man')
assert.deepEqual(Object.keys(gmView.props).sort(), ['gm', 'owner', 'public'])
assert.deepEqual(gmView.statuses, [])
// the player controls nothing and the token is far away: nothing reaches that connection
await sleep(150)
assert.equal(tokenFrames(p.ws).length, 0, 'a player must not learn about an unseen token')
p.ws.close(); gm.ws.close()
})
})
test('token.create validation: the 6.1 table and the fields this slice cannot honour', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const scene = gm.scene
const player = await namedPlayer(s.stateDir, gm, 'Alice')
const base = { kind: 'npc', pos: [100, 100], descriptive_name: 'a thing', actual_name: 'Thing' }
const invalid = [
{ ...base, descriptive_name: '' },
{ ...base, descriptive_name: ' padded' },
{ ...base, actual_name: 'tab\there' },
{ ...base, descriptive_name: 'x'.repeat(65) },
{ ...base, kind: '' },
{ ...base, pos: [-1, 100] },
{ ...base, pos: [5000, 100] },
{ ...base, pos: [1] },
{ ...base, pos: ['1', '2'] },
{ ...base, gm_only: 'yes' },
{ ...base, flags: [1, 2] },
{ ...base, vision_radius: 0 },
{ ...base, vision_radius: 'big' },
{ ...base, radius: 30 }, // slice 7 (#4)
{ ...base, props: { public: {} } }, // slice 7 (#22)
{ ...base, character_id: 'abc' }, // slice 8 (#23)
{ ...base, controller: 'alice' },
]
for (const fields of invalid) {
const ack = await gm.ws.request({ t: 'token.create', scene, ...fields })
assert.equal(ack.ok, false, JSON.stringify(fields))
assert.equal(ack.code, 'invalid', JSON.stringify(fields))
assert.equal(ack.id, undefined, 'a refusal carries no state')
}
// lookups (6.5 step 8) and the scene check
assert.equal((await gm.ws.request({ t: 'token.create', scene: scene + 1, ...base })).code, 'not-found')
assert.equal((await gm.ws.request({ t: 'token.create', scene: '1', ...base })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'token.create', scene, ...base, controller: 99 })).code,
'not-found')
// a GM controller is stored as GM-controlled, and the GM's own player id means the same thing
const viaGm = await gm.ws.request({ t: 'token.create', scene, ...base, controller: 1 })
assert.equal(viaGm.ok, true)
const view = await gm.ws.waitFor(m => m.t === 'token' && m.id === viaGm.id)
assert.equal(view.controller, null)
gm.ws.close(); player.ws?.close?.()
})
})
test('token.move: controller only, uniform nack, and one code for unknown and not-yours', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
const bob = await namedPlayer(s.stateDir, gm, 'Bob')
const mine = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'Alice', actual_name: 'Alice',
controller: alice.id, flags: { vision: true } })
const theirs = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [500, 500], descriptive_name: 'Bob', actual_name: 'Bob',
controller: bob.id })
const a = await playerConnect(s.origin, alice, 1)
const own = await a.ws.waitFor(m => m.t === 'token' && m.id === mine.id)
assert.equal(own.mine, true)
assert.deepEqual(own.props && Object.keys(own.props).sort(), ['owner', 'public'])
const ok = await a.ws.request({ t: 'token.move', id: mine.id, pos: [600, 400] })
assert.equal(ok.ok, true)
assert.deepEqual(ok.pos, [600, 400])
const moved = await a.ws.waitFor(m => m.t === 'token' && m.id === mine.id && m.pos[0] === 600)
assert.deepEqual(moved.pos, [600, 400])
// over the step cap: the uniform refusal, old position, no code (5.5, T9)
const far = await a.ws.request({ t: 'token.move', id: mine.id, pos: [1400, 400] })
assert.equal(far.ok, false)
assert.equal(far.code, undefined, 'a move refusal carries no code')
assert.deepEqual(far.pos, [600, 400])
// another player's token and an unknown id are the same refusal for a player
for (const id of [theirs.id, 'does-not-exist']) {
const ack = await a.ws.request({ t: 'token.move', id, pos: [700, 500] })
assert.equal(ack.ok, false, id)
assert.equal(ack.code, 'not-allowed', id)
assert.equal(ack.pos, undefined, 'no position oracle for a non-controlled token')
}
// the GM's missing target is not-found, and an out-of-bounds GM move is the uniform nack
assert.equal((await gm.ws.request({ t: 'token.move', id: 'nope', pos: [0, 0] })).code, 'not-found')
const gmVoid = await gm.ws.request({ t: 'token.move', id: mine.id, pos: [-50, 0] })
assert.equal(gmVoid.ok, false)
assert.equal(gmVoid.code, undefined)
assert.deepEqual(gmVoid.pos, [600, 400])
// the GM moves anyone's token, past the cap and through walls
const gmMove = await gm.ws.request({ t: 'token.move', id: mine.id, pos: [3000, 3000] })
assert.equal(gmMove.ok, true)
a.ws.close(); gm.ws.close()
})
})
test('token.update: controller, gm_only, names, flags and the codes of 6.5', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
const own = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 400],
descriptive_name: 'Alice', actual_name: 'Alice',
controller: alice.id, flags: { vision: true } })
const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'npc',
pos: [450, 400], descriptive_name: 'a guard',
actual_name: 'Captain Vex' })
const a = await playerConnect(s.origin, alice, 2)
const seen = await a.ws.waitFor(m => m.t === 'token' && m.id === created.id)
assert.equal(seen.name, 'a guard')
assert.equal(seen.mine, false)
assert.equal(seen.vision_radius, undefined, 'only the controller gets the step cap field')
// gm_only takes it away from a player who could see it (6.1)
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id, gm_only: true })).ok, true)
const gone = await a.ws.waitFor(m => m.t === 'token_gone' && m.id === created.id)
assert.deepEqual(stripN(gone), { t: 'token_gone', id: created.id })
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id, gm_only: false })).ok, true)
await a.ws.waitFor(m => m.t === 'token' && m.id === created.id && m.name === 'a guard')
// a rename reaches whoever may see the token; the GM keeps both names
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id,
descriptive_name: 'a tall guard' })).ok, true)
const renamed = await a.ws.waitFor(m => m.t === 'token' && m.id === created.id &&
m.name === 'a tall guard')
assert.equal(renamed.actual_name, undefined, 'the actual name has no egress path (slice 8)')
// the controller change flips `mine` and hands over the step-cap field
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id,
controller: alice.id })).ok, true)
const handed = await a.ws.waitFor(m => m.t === 'token' && m.id === created.id && m.mine === true)
assert.equal(handed.vision_radius, null)
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id, controller: null })).ok, true)
await a.ws.waitFor(m => m.t === 'token' && m.id === created.id && m.mine === false)
// codes: a fieldless patch and a character link are invalid, a bad target is not-found
for (const patch of [{}, { character_id: null }, { kind: '' }, { descriptive_name: '' },
{ controller: 'alice' }, { vision_radius: 0 }, { flags: 3 }]) {
const ack = await gm.ws.request({ t: 'token.update', id: created.id, ...patch })
assert.equal(ack.ok, false, JSON.stringify(patch))
assert.equal(ack.code, 'invalid', JSON.stringify(patch))
}
assert.equal((await gm.ws.request({ t: 'token.update', id: 'nope', gm_only: true })).code,
'not-found')
assert.equal((await gm.ws.request({ t: 'token.update', id: created.id, controller: 42 })).code,
'not-found')
a.ws.close(); gm.ws.close()
})
})
test('token.remove: token_gone to whoever knew it, not-found after', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 400],
descriptive_name: 'Alice', actual_name: 'Alice',
controller: alice.id, flags: { vision: true } })
const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'item',
pos: [450, 400], descriptive_name: 'a lamp',
actual_name: 'Lantern' })
const a = await playerConnect(s.origin, alice, 2)
await gm.ws.waitFor(m => m.t === 'token' && m.id === created.id)
assert.equal((await gm.ws.request({ t: 'token.remove', id: created.id })).ok, true)
await a.ws.waitFor(m => m.t === 'token_gone' && m.id === created.id)
await gm.ws.waitFor(m => m.t === 'token_gone' && m.id === created.id)
assert.equal((await gm.ws.request({ t: 'token.remove', id: created.id })).code, 'not-found')
a.ws.close(); gm.ws.close()
})
})
test('connect resync: GM gets walls then every token; a player vision, explored, then its tokens', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
const visible = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'npc',
pos: [450, 400], descriptive_name: 'a wolf',
actual_name: 'Fang' })
const far = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'npc',
pos: [3500, 3500], descriptive_name: 'a chest',
actual_name: 'Vault' })
const mine = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [3000, 3000], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
await sleep(200)
// a fresh GM connection: hello (scene block + extra), walls, then every token
const gm2 = await openAs(s.origin, gmKey)
const hello = await gm2.ws.waitText('hello')
assert.equal(hello.role, 'gm')
assert.equal(hello.scene.id, gm.scene)
assert.equal(hello.scene.cell, 32)
assert.equal(hello.scene.vision_radius_default, 400)
assert.deepEqual(hello.extra, {})
assert.equal(hello.n, 1)
const order = gm2.ws.messages.map(m => m.t)
assert.deepEqual(order.slice(0, 2), ['hello', 'walls'])
assert.equal(order.filter(t => t === 'token').length, 3)
assert.equal(order.includes('vision'), false, 'the GM never gets vision polygons')
assert.equal(order.includes('explored'), false, 'the GM never gets explored cells')
assert.deepEqual([...new Set(gm2.ws.messages.map(m => m.n))].length, gm2.ws.messages.length,
'every frame carries its own n')
// a fresh player connection: hello, vision, explored (full), then the tokens it may see
const a = await playerConnect(s.origin, alice, 1)
await sleep(150)
const aOrder = a.ws.messages.map(m => m.t)
assert.deepEqual(aOrder.slice(0, 3), ['hello', 'vision', 'explored'])
const explored = a.ws.messages[2]
assert.equal(explored.full, true)
assert.ok(Array.isArray(explored.rle))
const ids = tokenFrames(a.ws).map(m => m.id).sort()
assert.deepEqual(ids, [mine.id].sort(),
'a player gets only what it controls or sees (its own token is far away: controlled)')
assert.equal(ids.includes(far.id), false)
const vision = a.ws.messages[1]
assert.equal(vision.polys.length, 1)
assert.equal(vision.polys[0].id, mine.id)
for (const pt of vision.polys[0].pts) {
assert.equal(Number.isInteger(pt[0]) && Number.isInteger(pt[1]), true, 'integer px (6.4)')
}
a.ws.close(); gm2.ws.close(); gm.ws.close()
})
})
test('an unnamed player gets nothing but hello, and every intent is refused (6.1, 6.5 step 5)', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const player = await createPlayer(gm.ws) // no name: slice 8 brings player.setname
const p = await playerConnect(s.origin, player)
const hello = await p.ws.waitText('hello')
assert.deepEqual(Object.keys(hello).sort(), ['me', 'n', 'proto', 'role', 't'])
assert.equal(hello.me.name, null)
const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [400, 400], descriptive_name: 'x', actual_name: 'X',
controller: player.id, flags: { vision: true } })
await sleep(150)
assert.equal(p.ws.messages.length, 1, 'nothing but hello: no scene block, no resync')
const ack = await p.ws.request({ t: 'token.move', id: created.id, pos: [500, 400] })
assert.equal(ack.ok, false)
assert.equal(ack.code, 'not-allowed')
p.ws.close(); gm.ws.close()
})
})
test('door closing pushes an overlapped token aside (5.5), and the push is a normal token update',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
const door = await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 400], b: [500, 700],
kind: 'door' })
const tok = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [300, 550], descriptive_name: 'Alice',
actual_name: 'Alice', controller: alice.id,
flags: { vision: true } })
const a = await playerConnect(s.origin, alice, 1)
// the GM drops the token onto the door line, then closes the door on it
assert.equal((await gm.ws.request({ t: 'token.move', id: tok.id, pos: [500, 550] })).ok, true)
await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id && m.pos[0] === 500)
assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id: door.id, open: true })).ok,
true)
assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id: door.id, open: false })).ok,
true)
const pushed = await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id && m.pos[0] !== 500)
// pushed perpendicular to the door by the minimal distance that clears the token radius
assert.equal(pushed.pos[0] < 480 || pushed.pos[0] > 520, true, JSON.stringify(pushed.pos))
assert.equal(Math.abs(pushed.pos[1] - 550) < 1e-6, true, 'the push keeps the along-axis position')
// and the new position is what a restart loads
const gmToken = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.pos[0] === pushed.pos[0])
assert.deepEqual(gmToken.pos, pushed.pos)
a.ws.close(); gm.ws.close()
})
})
test('restart: tokens, positions and controllers come back with the same view', async () => {
const stateDir = makeStateDir()
try {
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
let ids
try {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(stateDir, gm, 'Alice')
const t1 = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'Alice', actual_name: 'Alice',
controller: alice.id, flags: { vision: true } })
const t2 = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'npc',
pos: [600, 550], descriptive_name: 'a guard',
actual_name: 'Vex' })
assert.equal((await gm.ws.request({ t: 'token.move', id: t2.id, pos: [620, 560] })).ok, true)
ids = { t1: t1.id, t2: t2.id, alice }
gm.ws.close()
} finally {
await stopServer(s)
}
s = await startServer({ stateDir })
try {
const gm = await gmConnect(s.origin, gmKey)
const tokens = await gm.ws.waitFor(m => m.t === 'token' && m.id === ids.t2)
assert.deepEqual(tokens.pos, [620, 560])
await gm.ws.waitFor(m => m.t === 'token' && m.id === ids.t1)
const a = await playerConnect(s.origin, ids.alice, 1)
await sleep(150)
assert.equal(tokenFrames(a.ws).length, 2, 'both tokens are in the restored view')
a.ws.close(); gm.ws.close()
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('player.remove hands the player\'s tokens to the GM (3.2)', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const alice = await namedPlayer(s.stateDir, gm, 'Alice')
const tok = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [400, 400],
descriptive_name: 'Alice', actual_name: 'Alice',
controller: alice.id, flags: { vision: true } })
const before = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id)
assert.equal(before.controller, alice.id)
assert.equal((await gm.ws.request({ t: 'player.remove', id: alice.id })).ok, true)
const after = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id &&
m.controller === null)
assert.equal(after.controller, null)
assert.equal(after.mine, false)
gm.ws.close()
})
})