Files
FFF_vtt_frozen/tools/protocol.test.mjs
T
SirStone edd4437f7e feat(walls): player markers — emission, opaque ids, storage, resync (#59)
A wall that is player_marker:true and derives window sends a player one
anchor (the drawn midpoint, integer px) and an opaque per-player 12-char id
once any point of its segment enters that player's vision polygon. Markers
live in PlayerVision like explored, persist to marker_seen in the same
derived-memory transaction, load before the first connection and resync as a
full set after explored; the GM and other players never receive one.

- markers.nim: emission gate, visible-extent test, id mint, anchor, marker_seen I/O.
- views/main: PlayerView markers + full/diff frames, refresh sync, startup load.
- markers.test.mjs: window preset, switch off, solid wall, any-part anchor,
  walk-away/door/lost sight, full-after-explored, per-player privacy, GM none.
- leakcheck: marker allowed type + independent visible-extent oracle with a
  positive control (a marked window the subject sees).
- restart: marked window in the fixture; marker set and marker_seen rows
  identical before/after SIGTERM and SIGKILL.
- protocol/tviews: catalogue and frame order pin the 16th message.

Retraction, re-earning and MARKER_* faults are #60.

Ref #59
2026-11-19 23:27:26 +01:00

341 lines
16 KiB
JavaScript

// M3 slice 3 (#18): the WS protocol shell. Black-box through the real binary (withserver):
// hello + the per-connection `n` counter, the proto version check, one ack per intent, refusal
// codes, the intent rate limit, the malformed flood, the 64 KB inbound frame limit, the server
// Ping, the connection cap and the `closing`-then-1005 close semantics (DESIGN 6, 6.2, 6.4, 6.5).
import test from 'node:test'
import assert from 'node:assert/strict'
import { withGmServer, signIn, openAs } from './withserver.mjs'
import { collectAcks, createPlayer, openWs, opcodes, rawUpgrade, rawWs, sleep } from './lib.mjs'
// Sends `count` conn.ping intents with explicit reqIds and returns their acks.
async function pingMany(client, count, startReq = 1000) {
const ids = []
for (let i = 0; i < count; i++) {
const reqId = startReq + i
ids.push(reqId)
client.sendText({ t: 'conn.ping', reqId, ts: reqId })
}
return collectAcks(client, ids)
}
test('hello is the first frame; n counts server frames per connection, never globally', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const hello = await gm.ws.waitText('hello')
assert.deepEqual(gm.ws.messages[0], hello, 'hello is the first frame')
assert.equal(hello.n, 1) // starts at 1 on the connection's first frame
assert.equal(hello.proto, 2) // proto 2 is the wall-model build (DESIGN 6.2)
assert.equal(hello.role, 'gm')
assert.deepEqual(hello.me, { id: 1, name: 'GM' })
// 6.3: the roster, then the GM wall snapshot (slice 4, DESIGN 6.1 `walls`)
assert.equal((await gm.ws.waitText('roster')).n, 2)
assert.equal((await gm.ws.waitText('walls')).n, 3)
const first = await gm.ws.request({ t: 'conn.ping', ts: 42 })
assert.equal(first.ok, true)
assert.equal(first.ts, 42) // the ack echoes ts
assert.equal(first.n, 4)
assert.equal((await gm.ws.request({ t: 'conn.ping', ts: 43 })).n, 5)
// a second connection of the same player counts on its own (H25: no global counter)
const other = await openWs(s.origin, gm.cookie)
assert.equal((await other.waitText('hello')).n, 1)
assert.equal((await other.waitText('roster')).n, 2)
assert.equal((await other.waitText('walls')).n, 3)
assert.equal((await other.request({ t: 'conn.ping', ts: 7 })).n, 4)
// ... and the first connection's sequence did not move
assert.equal((await gm.ws.request({ t: 'conn.ping', ts: 44 })).n, 6)
for (const m of gm.ws.messages) assert.equal(typeof m.n, 'number', JSON.stringify(m))
})
})
// The 16 server message types of DESIGN 6.1 (15 M3 + `marker`, 6.2 proto 2). A client must ignore
// unknown server types (6.2), but the server itself never invents one: this pins the direction that
// is testable without a client.
const SERVER_TYPES = new Set(['hello', 'ack', 'error', 'roster', 'walls', 'wall', 'wall_gone',
'vision', 'explored', 'marker', 'token', 'token_gone', 'character', 'character_gone',
'encountered', 'closing'])
test('every server frame carries a catalogue type (nothing outside the wire catalogue)', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
await gm.ws.waitText('hello')
await gm.ws.request({ t: 'conn.ping', ts: 1 })
await gm.ws.request({ t: 'nope.nope' })
await gm.ws.sendText('{')
await sleep(100)
const seen = new Set(gm.ws.messages.map(m => m.t))
assert.deepEqual([...seen].sort(), ['ack', 'error', 'hello', 'roster', 'walls'])
for (const m of gm.ws.messages) assert.ok(SERVER_TYPES.has(m.t), `off-catalogue type ${m.t}`)
assert.ok(!seen.has('event'), '`event` is reserved and not built (DESIGN 9)')
gm.ws.close()
})
})
test('proto: absent or non-integer is HTTP 400; a different proto is 101 + closing 4003, no hello',
async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
assert.equal((await rawUpgrade(s.origin, { cookie, proto: null })).status, 400)
assert.equal((await rawUpgrade(s.origin, { cookie, proto: 'x' })).status, 400)
assert.equal((await rawUpgrade(s.origin, { cookie, proto: '1.0' })).status, 400)
assert.equal((await rawUpgrade(s.origin, { cookie, proto: 2 })).status, 101)
const raw = await rawWs(s.origin, { cookie, proto: 1 })
const closing = await raw.waitText('closing')
assert.equal(closing.reason, 'proto-mismatch')
assert.equal(closing.code, 4003)
assert.equal(closing.n, 1)
assert.ok(!raw.frames.some(f => f.opcode === opcodes.text && JSON.parse(f.text).t === 'hello'),
'a proto mismatch must not get hello or any state')
const close = await raw.closed
assert.equal(close.code, 1005) // the app code could not ride the close frame
})
})
test('an unknown type is refused, unknown fields are ignored, and every intent gets one ack',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
assert.equal((await gm.ws.request({ t: 'token.teleport', id: 'x' })).code, 'unknown-type')
assert.equal((await gm.ws.request({ t: '' })).code, 'unknown-type')
assert.equal((await gm.ws.request({ t: 'TOKEN.MOVE', id: 'x' })).code, 'unknown-type')
// `scene.set` (slice 10) is built: it answers on its own fields, no `unknown-type` gap is left
assert.equal((await gm.ws.request({ t: 'scene.set', scene: 1 })).code, 'invalid') // no field
// a built intent answers on its own fields instead
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token', id: 'x',
player: 2 })).code, 'not-found')
assert.equal((await gm.ws.request({ t: 'character.create' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'scene.set' })).code, 'invalid') // no scene
// an intent whose slice HAS landed answers on its fields (empty token.create = invalid)
assert.equal((await gm.ws.request({ t: 'token.create', scene: 1 })).code, 'invalid')
// the reserved FFF hook is refused for everyone and is never ok
const act = await gm.ws.request({ t: 'act.do', actor: 1, action: 'x', args: {} })
assert.equal(act.ok, false)
assert.equal(act.code, 'no-rules')
// unknown fields are ignored, and the server's own `n` wins over a forged one
const forged = await gm.ws.request({ t: 'conn.ping', ts: 5, junk: { a: 1 }, n: 999 })
assert.equal(forged.ok, true)
assert.equal(forged.ts, 5)
assert.notEqual(forged.n, 999)
// a missing or mistyped field is `invalid`, never a crash
assert.equal((await gm.ws.request({ t: 'conn.ping' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'conn.ping', ts: '5' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'key.replace' })).code, 'invalid')
assert.equal((await gm.ws.request({ t: 'key.replace', id: '2' })).code, 'invalid')
// reqId 0 and 2^31-1 are in range (DESIGN 6)
const ids = [0, 2147483647, 5000, 5001, 5002, 5003]
for (const reqId of ids) gm.ws.sendText({ t: 'conn.ping', reqId, ts: 1 })
const acks = await collectAcks(gm.ws, ids)
for (const reqId of ids) {
assert.equal(acks.filter(a => a.reqId === reqId).length, 1, `reqId ${reqId} acked once`)
}
})
})
test('an unnamed player: hello with a null name, ping works, everything else is not-allowed',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const player = await createPlayer(gm.ws)
const p = await openAs(s.origin, player.key)
const hello = await p.ws.waitText('hello')
assert.equal(hello.t, 'hello')
assert.equal(hello.role, 'player')
assert.equal(hello.me.id, player.id)
assert.equal(hello.me.name, null) // no name yet: asked once at first sign-in
assert.equal((await p.ws.request({ t: 'conn.ping', ts: 1 })).ok, true)
// step 5 of 6.5, before the role and unknown-type checks
assert.equal((await p.ws.request({ t: 'player.rename', id: player.id })).code, 'not-allowed')
assert.equal((await p.ws.request({ t: 'token.move', id: 'abcdefghijkl' })).code, 'not-allowed')
// a GM-only intent sent by a player is refused (step 6), named or not
assert.equal((await p.ws.request({ t: 'key.show', id: player.id })).code, 'not-allowed')
p.ws.close(); gm.ws.close()
})
})
test('readable frames that are not intents get error malformed; the tenth inside 10 s closes',
async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
const raw = await rawWs(s.origin, { cookie })
await raw.waitText('hello')
const garbage = [
'not json',
'',
'[]',
'123',
'{"t":"conn.ping"}',
'{"t":1,"reqId":1}',
'{"t":"conn.ping","reqId":"1"}',
'{"t":"conn.ping","reqId":-1}',
'{"reqId":1}',
]
for (const text of garbage) raw.sendText(text)
// binary counts as malformed too (DESIGN 6)
raw.sendBinary(Buffer.from('{"t":"conn.ping","reqId":1}'))
// 9 text + 1 binary = 10 malformed frames: the flood rule fires on the tenth
const closing = await raw.waitText('closing')
assert.equal(closing.reason, 'malformed-flood')
assert.equal(closing.code, 1008)
const errors = raw.frames.filter(f => f.opcode === opcodes.text && JSON.parse(f.text).t === 'error')
assert.equal(errors.length, 9, 'nine error frames, then the closing frame')
for (const e of errors) assert.equal(JSON.parse(e.text).code, 'malformed')
const close = await raw.closed
assert.equal(close.code, 1005)
})
})
test('nine malformed frames in a row are tolerated: the connection stays open', async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
const raw = await rawWs(s.origin, { cookie })
await raw.waitText('hello')
for (let i = 0; i < 9; i++) raw.sendText('nope')
await raw.waitFor(f => f.opcode === opcodes.text && JSON.parse(f.text).t === 'error', 5000)
await sleep(100)
assert.equal(raw.frames.filter(f => f.opcode === opcodes.text && JSON.parse(f.text).t === 'error').length, 9)
assert.equal(raw.closeEvent, null)
raw.sendText({ t: 'conn.ping', reqId: 77, ts: 3 })
const ack = await raw.waitText('ack')
assert.equal(ack.reqId, 77)
assert.equal(ack.ok, true)
raw.close()
})
})
test('the intent bucket: ~100 free, then rate-limited, connection open, nothing applied',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const first = await gm.ws.request({ t: 'key.create' })
assert.equal(first.ok, true)
const acks = await pingMany(gm.ws, 120)
const ok = acks.filter(a => a.ok).length
const limited = acks.filter(a => a.code === 'rate-limited').length
assert.equal(ok + limited, 120)
// one token went to the key.create above, so the burst covers ~99 more
assert.ok(ok >= 99 && ok <= 106, `burst of ~100 then refused, saw ${ok} ok`)
assert.ok(limited >= 14, `expected the excess refused, saw ${limited}`)
for (const a of acks) if (a.code) assert.equal(a.code, 'rate-limited')
// an intent refused by the bucket is never applied (no rollback needed: each intent is atomic)
const refused = await gm.ws.request({ t: 'key.create' })
assert.equal(refused.ok, false)
assert.equal(refused.code, 'rate-limited')
// ... and the connection stays open (6.4)
assert.equal(gm.ws.closeInfo, null)
// a malformed frame with an empty bucket answers `error rate-limited` (6.5 step 3)
gm.ws.sendText('not json')
await sleep(50)
assert.ok(gm.ws.messages.some(m => m.t === 'error' && m.code === 'rate-limited'),
`no error rate-limited in ${JSON.stringify(gm.ws.messages.slice(-3))}`)
// the bucket refills at 30/s, and the refused key.create left no row behind
await sleep(300)
const after = await gm.ws.request({ t: 'key.create' })
assert.equal(after.ok, true)
assert.equal(after.id, first.id + 1, 'the rate-limited key.create created nothing')
})
})
test('an inbound frame over 64 KB drops the TCP connection with no close frame', async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
const over = await rawWs(s.origin, { cookie })
await over.waitText('hello')
over.sendFrame(opcodes.text, Buffer.alloc(64 * 1024 + 1, 0x20))
const info = await over.closed
assert.equal(info.code, 1006) // no close frame at all (DESIGN 6.5 row 9)
assert.equal(info.tcpClosed, true)
// the boundary is exact: 64 KB is a message (and refused as malformed JSON), 64 KB + 1 is not
const exact = await rawWs(s.origin, { cookie })
await exact.waitText('hello')
exact.sendFrame(opcodes.text, Buffer.alloc(64 * 1024, 0x20))
const err = await exact.waitText('error')
assert.equal(err.code, 'malformed')
assert.equal(exact.closeEvent, null)
exact.close()
// a frame the RFC forbids (unmasked, bad opcode) also drops the connection
for (const send of [
c => c.sendFrame(opcodes.text, Buffer.from('{"t":"conn.ping","reqId":1}'), false),
c => c.sendFrame(0x3, Buffer.from('x')),
]) {
const bad = await rawWs(s.origin, { cookie })
await bad.waitText('hello')
send(bad)
assert.equal((await bad.closed).code, 1006)
}
})
})
test('the server pings the connection and answers a client Ping with a Pong', async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
const raw = await rawWs(s.origin, { cookie })
await raw.waitText('hello')
const ping = await raw.waitFor(f => f.opcode === opcodes.ping)
assert.equal(ping.payload.toString(), '1') // seq, echoed by the client's Pong
raw.sendPong(ping.payload)
// mummy delivers inbound Pings to the handler and does not reply itself, so the server does
raw.sendFrame(opcodes.ping, Buffer.from('hello'))
const pong = await raw.waitFor(f => f.opcode === opcodes.pong && f.payload.toString() === 'hello')
assert.ok(pong)
// control frames are not counted by `n`: hello = 1, roster = 2, walls = 3, this ack = 4
raw.sendText({ t: 'conn.ping', reqId: 900, ts: 5 })
const ack = await raw.waitText('ack')
assert.equal(ack.reqId, 900)
assert.equal(ack.ok, true)
assert.equal(ack.n, 4)
raw.close()
})
})
test('connection cap: the 17th upgrade is refused with 503 and Retry-After: 5', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const players = []
for (let i = 0; i < 4; i++) players.push(await openAs(s.origin, (await createPlayer(gm.ws)).key))
const conns = [gm.ws]
for (let i = 0; i < 4; i++) {
conns.push(players[i].ws)
for (let j = 0; j < (i === 3 ? 2 : 3); j++) conns.push(await openWs(s.origin, players[i].cookie))
}
assert.equal(conns.length, 16)
const refused = await rawUpgrade(s.origin, { cookie: players[0].cookie })
assert.equal(refused.status, 503)
assert.equal(refused.headers['retry-after'], '5')
for (const w of conns) w.close()
})
})
test('the closing frame is the last app message before the empty close frame', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const player = await createPlayer(gm.ws)
const sessions = [await openAs(s.origin, player.key), await openAs(s.origin, player.key)]
// a third and fourth connection fill the cap; the fifth evicts the oldest (4002)
sessions.push(await openAs(s.origin, player.key), await openAs(s.origin, player.key))
const fifth = await openWs(s.origin, sessions[0].cookie)
const oldest = sessions[0].ws
const evicted = await oldest.closed
const last = oldest.messages[oldest.messages.length - 1]
assert.equal(last.t, 'closing')
assert.equal(last.reason, 'evicted')
assert.equal(last.code, 4002)
assert.equal(evicted.code, 1005)
assert.equal(evicted.reason, '') // the reason is not in the close frame
assert.equal(fifth.closeInfo, null)
for (const w of sessions.slice(1).map(x => x.ws).concat([fifth, gm.ws])) w.close()
})
})