// T13 (#76, TESTING 10.3 "Independent traffic audit"): record every WebSocket frame and every HTTP // response the *player browser* receives, then judge that recording with this file's own rules. // // Independence is the point: the banned-key list, the frame catalogue and the geometry checks below // are written here and never imported from the server's `tools/leakcheck.nim` or `BannedAlways`. A // server list that quietly loses an entry must not be able to weaken this proof. // // The scenario is a player who must see a lot of interesting state (own token, an NPC in sight, a // window marker, fog, explored cells, tile requests including refused ones) while the GM authors // every round-1 wall field. A second player and a `gm_only` token sit outside the audited player's // sight; none of their ids may appear in its traffic. import test from 'node:test' import assert from 'node:assert/strict' import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs' import { openAs } from '../../tools/withserver.mjs' import { writeTileGrid } from '../../tools/tilefixture.mjs' import { launchBrowser, newPage, signIn, waitForVisible, withStack } from './stack.mjs' const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 } const OWN = [2048, 2048] const OTHER = [3500, 3500] /** DESIGN 6.1 server -> client rows a *player* may receive. GM-only rows are absent by design. */ const PLAYER_FRAMES = new Set([ 'hello', 'ack', 'error', 'roster', 'vision', 'explored', 'token', 'token_gone', 'character', 'character_gone', 'encountered', 'closing', 'marker', ]) /** * Fields a player must never receive. Own copy, deliberately broader than any server list: every * wall geometry field, the GM-only wall and token columns, and the GM-only status cause. */ const BANNED_KEYS = new Set([ // wall rows and the GM-only wall frames 'wall', 'walls', 'wall_gone', 'a', 'b', 'thickness', 'position', 'height', 'kind', 'blocks_sight', 'blocks_movement', 'sight_dir', 'player_marker', 'door', 'open', 'secret', 'locked', 'label', 'flags', // GM-only token columns 'controller', 'gm_only', 'descriptive_name', 'actual_name', 'reveal_all', 'revealed', 'seen_by', 'source', ]) /** Record the page's own WebSocket frames without changing what the app sees. */ async function recordSockets(page) { await page.addInitScript(() => { window.__audit = { sockets: 0, frames: [], closes: [] } const Native = window.WebSocket class RecordingSocket extends Native { constructor(url, protocols) { super(url, protocols) this.opened = false window.__audit.sockets += 1 this.addEventListener('open', () => { this.opened = true }) this.addEventListener('message', event => { try { window.__audit.frames.push(JSON.parse(event.data)) } catch { window.__audit.frames.push({ t: '', raw: String(event.data).slice(0, 80) }) } }) this.addEventListener('close', event => { window.__audit.closes.push({ code: event.code, reason: event.reason, opened: this.opened }) }) } } window.WebSocket = RecordingSocket }) } const framesOf = page => page.evaluate(() => window.__audit.frames) async function waitForFrames(page, predicate, timeout = 20000) { await page.waitForFunction(predicate, null, { timeout }) } function walkKeys(value, visit) { if (Array.isArray(value)) { for (const item of value) walkKeys(item, visit) return } if (value === null || typeof value !== 'object') return for (const [key, child] of Object.entries(value)) { visit(key) walkKeys(child, visit) } } /** Every explored cell the player was ever told about, from full RLE snapshots and cell diffs. */ function exploredCells(frames) { const cells = new Set() for (const frame of frames) { if (frame.t !== 'explored') continue if (frame.full) { for (const row of frame.rle ?? []) { const cy = row[0] for (let i = 1; i + 1 < row.length; i += 2) { const x0 = row[i] const len = row[i + 1] for (let x = x0; x < x0 + len; x += 1) cells.add(`${x},${cy}`) } } } else { for (const [cx, cy] of frame.cells ?? []) cells.add(`${cx},${cy}`) } } return cells } /** Bounding boxes (cell coordinates) of every vision polygon the player was ever sent. */ function visionBoxes(frames, cell) { const boxes = [] for (const frame of frames) { if (frame.t !== 'vision') continue for (const poly of frame.polys ?? []) { const pts = poly.pts ?? [] if (pts.length === 0) continue const xs = pts.map(([x]) => x) const ys = pts.map(([, y]) => y) boxes.push({ id: poly.id, x0: Math.floor(Math.min(...xs) / cell) - 1, y0: Math.floor(Math.min(...ys) / cell) - 1, x1: Math.ceil(Math.max(...xs) / cell) + 1, y1: Math.ceil(Math.max(...ys) / cell) + 1, }) } } return boxes } function insideAnyBox(cx, cy, boxes) { return boxes.some(b => cx >= b.x0 && cx <= b.x1 && cy >= b.y0 && cy <= b.y1) } /** Judge the player's frame stream. Every rule below returns what it found, so the negative * control can prove each rule can fail, not only that a clean run is empty. */ function frameViolations(frames, { foreignPlayerId = null, foreignTokenIds = [], cell = 32, near = null } = {}) { const offCatalogue = frames.filter(frame => !PLAYER_FRAMES.has(frame.t)) const banned = [] for (const frame of frames) { walkKeys(frame, key => { if (BANNED_KEYS.has(key)) banned.push({ t: frame.t, key }) }) } const ownIds = new Set(frames.filter(f => f.t === 'token' && f.mine === true).map(f => f.id)) const polyIds = new Set(frames.filter(f => f.t === 'vision').flatMap(f => (f.polys ?? []).map(p => p.id))) const offSightPolys = [...polyIds].filter(id => !ownIds.has(id)) const withoutRoster = frames.filter(f => f.t !== 'roster') const idFields = new Set(['id', 'player', 'owner', 'controller', 'seen_by']) const foreignPlayers = [] if (foreignPlayerId !== null) { const visitIdFields = value => { if (Array.isArray(value)) return value.forEach(visitIdFields) if (value === null || typeof value !== 'object') return for (const [key, child] of Object.entries(value)) { if (idFields.has(key)) { const values = Array.isArray(child) ? child : [child] if (values.includes(foreignPlayerId)) foreignPlayers.push({ key, value: child }) } visitIdFields(child) } } withoutRoster.forEach(visitIdFields) } const foreignTokens = foreignTokenIds.filter(id => withoutRoster.some(f => JSON.stringify(f).includes(id))) const boxes = visionBoxes(frames, cell) const explored = exploredCells(frames) const exploredOutside = [] for (const key of explored) { const [cx, cy] = key.split(',').map(Number) if (!insideAnyBox(cx, cy, boxes)) exploredOutside.push([cx, cy]) } const exploredNear = [] if (near) { for (const key of explored) { const [cx, cy] = key.split(',').map(Number) if (Math.abs(cx * cell - near[0]) < 300 && Math.abs(cy * cell - near[1]) < 300) exploredNear.push([cx, cy]) } } return { offCatalogue, banned, ownIds, polyIds, offSightPolys, foreignPlayers, foreignTokens, boxes, explored, exploredOutside, exploredNear } } test('player browser traffic: catalogue-only frames, no wall data, no other player, allowed tiles', { timeout: 240000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const gm = await openAs(origin, gmKey) const hello = await gm.ws.waitText('hello') const walls = await gm.ws.waitText('walls') const scene = hello.scene ?? walls.scene assert.deepEqual(walls.walls, [], 'the seeded scene starts without walls') // The audited player and a second player whose room stays out of Ann's sight. const ann = await createPlayer(gm.ws) await namePlayer(origin, ann.key, 'Ann') const bea = await createPlayer(gm.ws) await namePlayer(origin, bea.key, 'Bea') // Every round-1 wall field is authored around Ann *before* her token exists, so every explored // cell derives from a polygon this page is actually sent (no pre-wall memory). const authored = [ { a: [1848, 2248], b: [2248, 2248], thickness: 20, position: 'left', height: 2.5, label: 'south wall' }, { a: [1848, 1848], b: [1848, 2248], preset: 'door', thickness: 10 }, { a: [2248, 1848], b: [2248, 2248], door: true, secret: true, blocks_sight: true, blocks_movement: true, label: 'hidden door' }, { a: [1748, 1898], b: [1748, 2198], door: true, locked: true }, { a: [1898, 1748], b: [2198, 1748], blocks_sight: true, blocks_movement: true, sight_dir: 'left', player_marker: true }, { a: [1848, 1848], b: [2248, 1848], preset: 'window' }, { a: [2648, 1848], b: [2648, 2248], flags: { note: 'opaque' } }, ] const ids = [] for (const payload of authored) { const ack = await gm.ws.request({ t: 'wall.add', scene: scene.id, ...payload }) assert.equal(ack.ok, true, `wall.add ${JSON.stringify(payload)}: ${JSON.stringify(ack)}`) ids.push(ack.id) } // One sighted token plus an NPC inside its sight, a second player and a GM-only token outside. const own = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'pc', pos: OWN, descriptive_name: 'Ann', actual_name: 'Ann', controller: ann.id, flags: { vision: true }, vision_radius: 300, radius: 20, }) assert.equal(own.ok, true, JSON.stringify(own)) const npc = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'npc', pos: [2128, 2048], descriptive_name: 'Rat', actual_name: 'Giant Rat', }) assert.equal(npc.ok, true, JSON.stringify(npc)) const other = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'pc', pos: OTHER, descriptive_name: 'Bea', actual_name: 'Bea', controller: bea.id, flags: { vision: true }, vision_radius: 300, radius: 20, }) assert.equal(other.ok, true, JSON.stringify(other)) const hidden = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'npc', pos: [1968, 1978], descriptive_name: 'Secret', actual_name: 'Secret', gm_only: true, }) assert.equal(hidden.ok, true, JSON.stringify(hidden)) writeTileGrid(stateDir, { scene: scene.id, artVersion: scene.art_version, size: scene.tile_size, x0: 40, x1: 85, y0: 40, y1: 85, }) const browser = await launchBrowser() try { const { page } = await newPage(browser) const tileTraffic = [] const requests = [] page.on('request', request => requests.push(request.url())) page.on('response', response => { tileTraffic.push({ url: response.url(), status: response.status() }) }) await recordSockets(page) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, ann.key) await waitForVisible(page, '#stage canvas') await page.waitForFunction( () => document.querySelector('#stage canvas')?.dataset.tiles === 'ready', null, { timeout: 30000 }, ) // The whole initial view has arrived (including the marker for the window Ann can see). await waitForFrames(page, () => { const seen = new Set(window.__audit.frames.map(frame => frame.t)) return ['hello', 'roster', 'token', 'vision', 'explored', 'marker', 'encountered'] .every(type => seen.has(type)) }) // GM activity while the page records: edits, a door, a removal, a move of Ann's own token // (new vision + explored cells) and of the NPC (a token update), then an untouched settle. assert.equal((await gm.ws.request({ t: 'wall.update', scene: scene.id, id: ids[0], height: 3 })).ok, true) assert.equal((await gm.ws.request({ t: 'door.set', scene: scene.id, id: ids[1], open: true })).ok, true) assert.equal((await gm.ws.request({ t: 'wall.remove', scene: scene.id, id: ids[6] })).ok, true) assert.equal((await gm.ws.request({ t: 'token.move', id: own.id, pos: [2048, 2160] })).ok, true) assert.equal((await gm.ws.request({ t: 'token.move', id: npc.id, pos: [2100, 2080] })).ok, true) await sleep(500) const frames = await framesOf(page) assert.ok(frames.length > 10, `the audit recorded a real stream: ${frames.length} frames`) const v = frameViolations(frames, { foreignPlayerId: bea.id, foreignTokenIds: [other.id, hidden.id], cell: scene.cell, near: OTHER, }) // 1. Catalogue only: every frame type is a row a player may receive. assert.deepEqual(v.offCatalogue, [], `off-catalogue frames: ${JSON.stringify(v.offCatalogue.slice(0, 3))}`) // 2. No wall field and no GM-only column anywhere in the player's frames, at any depth. assert.deepEqual(v.banned, [], `player frames carried forbidden keys: ${JSON.stringify(v.banned.slice(0, 5))}`) // 3. Vision polygons belong to Ann's own controlled token and nothing else. assert.ok(v.polyIds.size > 0, 'the player received its vision polygons') assert.deepEqual(v.offSightPolys, [], 'a vision polygon for a token Ann does not control') // 4. No other player's or hidden token's id anywhere except the roster's own player list. // Player ids are small integers, so they are checked in id-shaped fields only (a `reqId` // or a coordinate may legitimately equal one); token ids are opaque strings. assert.deepEqual(v.foreignPlayers, [], `another player's id reached the player: ${JSON.stringify(v.foreignPlayers)}`) assert.deepEqual(v.foreignTokens, [], `a token outside Ann's sight reached her: ${JSON.stringify(v.foreignTokens)}`) // 5. Explored is this player's own memory: every cell lies in the bbox of a polygon Ann was // sent, and no cell is anywhere near the other player's room. assert.ok(v.boxes.length > 0, 'historical vision polygons were recorded') assert.ok(v.explored.size > 100, `explored has real content: ${v.explored.size} cells`) assert.deepEqual(v.exploredOutside.slice(0, 5), [], `explored cells outside Ann's own sight: ${v.exploredOutside.length}`) assert.deepEqual(v.exploredNear, [], 'no explored cell near the other player') const explored = v.explored // 6. Tiles: only the product path, only 200/403, and every served tile overlaps a cell Ann // has explored. `/_tiles/` is never reachable from the page. const tileResponses = tileTraffic.filter(r => new URL(r.url).pathname.startsWith('/tiles/')) assert.ok(tileResponses.length > 0, 'the page fetched map tiles') for (const r of tileResponses) { assert.ok([200, 403].includes(r.status), `unexpected tile status ${r.status} for ${r.url}`) } const served = tileResponses.filter(r => r.status === 200) const refused = tileResponses.filter(r => r.status === 403) assert.ok(served.length > 0 && refused.length > 0, 'the scenario has both allowed and refused tiles') for (const r of served) { const path = new URL(r.url).pathname const match = /^\/tiles\/(\d+)\/v(\d+)\/(\d+)_(\d+)\.png$/.exec(path) assert.ok(match, `tile URL not on the catalogue path: ${r.url}`) const tx = Number(match[3]) const ty = Number(match[4]) assert.ok( explored.has(`${tx},${ty}`), `a served tile the player never explored: ${path} (${served.length} served)`, ) } for (const url of requests) { assert.ok(!url.includes('/_tiles/'), `the page requested the internal tile alias: ${url}`) if (url.includes('/tiles/')) { assert.match(new URL(url).pathname, /^\/tiles\/\d+\/v\d+\/\d+_\d+\.png$/, `unexpected tile path ${url}`) } } const direct = await page.evaluate(async () => { const response = await fetch('/_tiles/1/v1/60_60.png') return response.status }) assert.equal(direct, 404, 'a direct /_tiles/ request from the page is refused') // 7. The live socket never closed during the audit. The boot probe's 1006 (the client asks // `/ws` with no session and lands on sign-in) is expected and never opened. const closes = await page.evaluate(() => window.__audit.closes) assert.deepEqual( closes.filter(c => c.opened && c.code !== 1005), [], `the live player socket closed: ${JSON.stringify(closes)}`, ) } finally { await browser.close() gm.ws.close() } }) }) // Negative control: the audit must fail on a build that really leaks. `-d:leakfault` with // `LEAK_FAULT=otherVision` injects another player's vision polygon into this player's `vision` // frame (the server's own fault hook, not a fixture). The rule that catches it is rule 3: a polygon // for a token the player does not control. test('audit rules catch a leaking build (negative control)', { timeout: 180000 }, async () => { await withStack(async ({ origin, gmKey }) => { const gm = await openAs(origin, gmKey) const hello = await gm.ws.waitText('hello') await gm.ws.waitText('walls') const scene = hello.scene const ann = await createPlayer(gm.ws) await namePlayer(origin, ann.key, 'Ann') const bea = await createPlayer(gm.ws) await namePlayer(origin, bea.key, 'Bea') for (const [player, pos, name] of [[ann, [1200, 1200], 'Ann'], [bea, [3000, 3000], 'Bea']]) { const ack = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'pc', pos, descriptive_name: name, actual_name: name, controller: player.id, flags: { vision: true }, vision_radius: 300, radius: 20, }) assert.equal(ack.ok, true, JSON.stringify(ack)) } const browser = await launchBrowser() try { const { page } = await newPage(browser) await recordSockets(page) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, ann.key) await waitForVisible(page, '#stage canvas') await waitForFrames(page, () => (window.__audit.frames ?? []).some(f => f.t === 'vision' && (f.polys ?? []).length >= 2)) const frames = await framesOf(page) const v = frameViolations(frames) assert.ok(v.offSightPolys.length > 0, 'the off-sight polygon rule fired on the leaking build') } finally { await browser.close() gm.ws.close() } }, { server: { defines: ['leakfault'], env: { LEAK_FAULT: 'otherVision' } } }) })