Files
FFF_vtt_frozen/tools/tiles.test.mjs
T
SirStone 1dff520f31 test: TLS + HTTP/2 test vhost with the client dist served at /
The test nginx is now the production shape of DESIGN 11.1 and the browser
gate's real path (#66, spec #63 decision 6): TLS-only listener with
http2 on, a self-signed certificate generated per run (tools/tlsdev.mjs,
added to the process's default CA list so verification stays on), the
client dist at / with SPA fallback, index no-cache and a year-immutable
/assets/ cache, and the tile gate's internal /_tiles/ still unreachable.

Existing tile/doors/oneway/wallbehaviour harnesses point their server's
public origin at the https vhost, so they prove the same listener the
browser uses. tools/vhost.test.mjs is the independent node:http2 client
(cert SANs, ALPN h2, cache headers, SPA fallback, direct /_tiles/ 404);
e2e/h2.test.mjs drives devbox chromium via playwright-core and asserts
the page reports h2 (`devbox run e2e`, npm deps outside tools/).

Root devbox gains chromium + openssl. Harness builds use a worktree-local
nimcache so parallel worktrees stop corrupting each other's objects.

Refs #66
2026-11-20 23:11:05 +01:00

505 lines
26 KiB
JavaScript

// M3 slice 9 (#24): the map-tile gate through the real binary and the test nginx (DESIGN 3.3, 6.6,
// 10.1, 10.2, 11.1, 13 group "tiles"). This file is the group's leak check (d) and its smoke
// tile-steal checks:
// - every gate decision over a whole tile region is compared with an INDEPENDENT explored oracle
// (clear-segment sampling over the GM's walls and the player token's vision radius, no server
// cell code involved): allowed => the oracle can see a point in the cell, and a cell the oracle
// is sure about must be allowed;
// - a tile behind a wall and a tile of another player are refused; a player with no sight state
// gets nothing, while the GM gets any in-range tile;
// - direct /_tiles/ is 404 (nginx `internal`), malformed/out-of-range/stale-version paths are 404,
// an unauthenticated or unknown session is 403, and traversal shapes never reach a file.
// Fixture tiles come from tools/tilefixture.mjs, generated in the test's state dir; none is committed.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { isPng, pngBytes, tileDir, writeTileGrid, writeTiles } from './tilefixture.mjs'
// ---------------------------------------------------------------------------------------------
// A stack: real server + test nginx in front (the production shape of 11.1). The server's configured
// public origin is the nginx origin, so WS connections through the proxy pass the Origin check.
async function withTileStack(fn) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
const s = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let ngx
try {
ngx = await startTestNginx({ backendPort: s.port, stateDir, port: nginxPort })
return await fn({ s, gmKey, ngx, stateDir })
} finally {
await stopTestNginx(ngx)
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
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 }
}
async function addWall(gm, fields) {
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
// The GM's wall effect frame is the truth source for the oracle (the connect snapshot predates it).
const frame = await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
return { ack, frame }
}
// A named player who controls one token with vision at (300, 300), radius 400, and a wall at x=400
// splitting the view. The player's explored grid is then produced by the server's own resync.
// `wallFields` lets a test make that segment a see-through window without changing anything else.
async function sceneWithVision(s, gmKey, ngx, wallFields = {}) {
const gm = await gmConnect(ngx.origin, gmKey)
const player = await createPlayer(gm.ws)
await namePlayer(ngx.origin, player.key, 'Alice')
const wall = await addWall(gm, { a: [400, 100], b: [400, 700], ...wallFields })
const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc',
pos: [300, 300], flags: { vision: true },
vision_radius: 400, controller: player.id,
descriptive_name: 'Alice', actual_name: 'Alice' })
assert.equal(created.ok, true, JSON.stringify(created))
const token = await gm.ws.waitFor(m => m.t === 'token' && m.id === created.id)
const seen = await openAs(ngx.origin, player.key)
await seen.ws.waitText('hello')
const explored = await seen.ws.waitFor(m => m.t === 'explored' && m.full === true)
return { gm, player, token, seenCtx: seen, explored, scene: gm.scene, artVersion: exploredArt(gm),
wallsFrame: { walls: [wall.frame] } }
}
// art_version is in the GM's hello (views.sceneBlock, DESIGN 6.1).
function exploredArt(gm) {
const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene)
return hello.scene.art_version
}
// ---------------------------------------------------------------------------------------------
// The independent explored oracle (DESIGN 10.2). Nothing here uses the server's explored cells: the
// inputs are the GM's wall truth, the token position and its vision radius. A cell is
// sure = holds a lattice point inside the inscribed 64-gon (radius*cos(pi/64) - 0.5 px) whose
// line of sight stays > 0.5 px away from every blocking wall -> the gate must allow it;
// maybe = holds a point within radius + 0.5 px that no blocking wall properly crosses -> a gate
// that allows the tile is not inventing disclosure.
const Tol = 0.5
function segDist(p, a, b) {
const ex = b.x - a.x
const ey = b.y - a.y
const l2 = ex * ex + ey * ey
const t = l2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2))
return Math.hypot(p.x - a.x - t * ex, p.y - a.y - t * ey)
}
function orient(a, b, c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
function properCross(p, q, a, b) {
const d1 = orient(p, q, a), d2 = orient(p, q, b), d3 = orient(a, b, p), d4 = orient(a, b, q)
return d1 * d2 < 0 && d3 * d4 < 0
}
function segGap(p, q, a, b) {
if (properCross(p, q, a, b)) return 0
return Math.min(segDist(p, a, b), segDist(q, a, b), segDist(a, p, q), segDist(b, p, q))
}
function blockingWalls(wallsFrame, opts = {}) {
// The oracle's own reading of the sight switches (#57): a wall blocks sight only while its
// `blocks_sight` switch is on and it is not an open door. A window is see-through along its whole
// drawn length. `ignoreBlocksSight` is the negative control: it restores the old
// `door/open`-only rule, under which a window would wrongly block.
return wallsFrame.walls
.filter(w => (opts.ignoreBlocksSight || w.blocks_sight !== false) && !(w.door && w.open))
.map(w => ({ a: { x: w.a[0], y: w.a[1] }, b: { x: w.b[0], y: w.b[1] } }))
}
// sure/maybe for one tile-sized cell (tile_size == cell in v1, Q4).
function oracleCell({ o, radius, walls, cell, x, y }) {
const rin = radius * Math.cos(Math.PI / 64) - Tol
const x0 = x * cell, y0 = y * cell
let sure = false, maybe = false
const n = 16
for (let j = 0; j <= n && !(sure && maybe); j++) {
for (let i = 0; i <= n; i++) {
const p = { x: x0 + (cell * i) / n, y: y0 + (cell * j) / n }
const d = Math.hypot(p.x - o.x, p.y - o.y)
if (!maybe && d <= radius + Tol) {
let clear = true
for (const w of walls) if (properCross(o, p, w.a, w.b)) { clear = false; break }
if (clear) maybe = true
}
if (!sure && d <= rin) {
let clear = true
for (const w of walls) if (segGap(o, p, w.a, w.b) <= Tol) { clear = false; break }
if (clear) sure = true
}
if (sure && maybe) break
}
}
return { sure, maybe }
}
// The explored cells the player was sent (full RLE frame), for a self-consistency cross-check.
function exploredSet(frame) {
const set = new Set()
for (const row of frame.rle) {
const cy = row[0]
for (let i = 1; i < row.length; i += 2) {
for (let k = 0; k < row[i + 1]; k++) set.add(`${row[i] + k},${cy}`)
}
}
return set
}
const tileUrl = (scene, art, x, y) => `/tiles/${scene}/v${art}/${x}_${y}.png`
async function getTile(origin, path, cookie) {
return await fetch(`${origin}${path}`, { headers: cookie ? { Cookie: cookie } : {} })
}
// ---------------------------------------------------------------------------------------------
test('tile gate: leak check (d) matches the independent explored oracle', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
const ctx = await sceneWithVision(s, gmKey, ngx)
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const cell = scene.cell
const tile = scene.tile_size
assert.equal(tile, cell, 'v1 pins tile_size = cell = 32 (Q4)')
// Fixtures for the whole checked rectangle: every tile the gate may allow has real bytes behind
// the internal alias, so a 200 always has a body to compare.
const x0 = 0, x1 = 31, y0 = 0, y1 = 31
const files = writeTileGrid(stateDir, { scene: scene.id, artVersion: ctx.artVersion, size: tile,
x0, x1, y0, y1 })
assert.equal(files.length, (x1 - x0 + 1) * (y1 - y0 + 1))
const walls = blockingWalls(ctx.wallsFrame)
const o = { x: ctx.token.pos[0], y: ctx.token.pos[1] }
const radius = ctx.token.vision_radius
assert.equal(radius, 400)
const explored = exploredSet(ctx.explored)
const cookie = ctx.seenCtx.cookie
let requests = 0, allowed = 0, sureCount = 0, maybeCount = 0, maybeRefused = 0, failures = 0
const allowedSet = new Set()
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const vis = oracleCell({ o, radius, walls, cell, x, y })
if (vis.sure) sureCount++
if (vis.maybe) maybeCount++
const r = await getTile(ngx.origin, tileUrl(scene.id, ctx.artVersion, x, y), cookie)
requests++
const fail = msg => { failures++; assert.fail(`tile ${x},${y} (sure=${vis.sure} maybe=${vis.maybe}): ${msg}`) }
if (r.status === 200) {
allowed++
allowedSet.add(`${x},${y}`)
// allowed => the oracle can see something in the cell (no invented disclosure)
if (!vis.maybe) fail('allowed although the oracle cannot see any point in the cell')
const body = Buffer.from(await r.arrayBuffer())
if (!isPng(body)) fail('a 200 did not carry PNG bytes')
const want = fs.readFileSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), `${x}_${y}.png`))
if (!body.equals(want)) fail('served bytes are not the requested tile')
if (r.headers.get('x-accel-redirect') !== null) fail('X-Accel-Redirect leaked to the client')
if ((r.headers.get('cache-control') ?? '') !== 'private') fail('Cache-Control is not private')
} else if (r.status === 403) {
if (vis.sure) fail('refused although the oracle is sure the cell is visible')
if (vis.maybe) maybeRefused++
} else {
fail(`unexpected status ${r.status}`)
}
}
if (failures > 0) break
}
// Self-consistency: the gate's allowed set is exactly the explored cells of the region (the gate
// and the view use the same set; the independent check above is what proves the set is right).
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
assert.equal(allowedSet.has(`${x},${y}`), explored.has(`${x},${y}`),
`tile ${x},${y}: gate disagrees with the player's explored frame`)
}
}
// Coverage and the documented tolerance at the polygon edge (10.2: superset/subset with a
// stated tolerance; the rasterizer skips a cell touched only along its min-x/min-y line).
assert.ok(sureCount > 20, `the oracle sampled too little (sure=${sureCount})`)
assert.ok(allowed > 20, `the gate allowed too few tiles (allowed=${allowed})`)
assert.ok(maybeRefused <= Math.max(2, Math.floor(maybeCount * 0.02)),
`too many maybe-visible cells refused: ${maybeRefused}/${maybeCount}`)
// Negative control for the oracle itself: a far cell is neither sure nor maybe, the token's own
// cell is both. A checker that says "maybe" everywhere would prove nothing.
assert.deepEqual(oracleCell({ o, radius, walls, cell, x: 110, y: 110 }),
{ sure: false, maybe: false })
const own = oracleCell({ o, radius, walls, cell, x: 9, y: 9 })
assert.equal(own.sure, true)
assert.equal(own.maybe, true)
// A wall is real: cells just behind it (x=13..15, y=9, right of x=400) are out of sight.
for (const bx of [14, 15]) {
assert.equal(oracleCell({ o, radius, walls, cell, x: bx, y: 9 }).maybe, false,
`cell ${bx},9 is behind the wall and must not be visible`)
}
console.log(`tile leak (d): ${requests} requests, ${allowed} allowed, ${sureCount} sure, ` +
`${maybeRefused} maybe-refused, ${failures} failures`)
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
test('tile gate: a window is see-through along its drawn length (#57)', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
// A fixed window: the same segment as the solid-wall scenario, `blocks_sight:false` and no door,
// so nothing about the change is a door opening. The token still sits 100 px west of it.
const ctx = await sceneWithVision(s, gmKey, ngx,
{ blocks_sight: false, blocks_movement: true })
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const cell = scene.cell
const tile = scene.tile_size
const frame = ctx.wallsFrame.walls[0]
assert.equal(frame.kind, 'window')
assert.equal(frame.blocks_sight, false)
assert.equal(frame.blocks_movement, true)
assert.equal(frame.door, false, 'the fixed form has no open state')
writeTileGrid(stateDir, { scene: scene.id, artVersion: ctx.artVersion, size: tile,
x0: 0, x1: 31, y0: 0, y1: 31 })
const o = { x: ctx.token.pos[0], y: ctx.token.pos[1] }
const radius = ctx.token.vision_radius
const seenThrough = blockingWalls(ctx.wallsFrame)
const opaque = blockingWalls(ctx.wallsFrame, { ignoreBlocksSight: true })
// Cells just east of x=400 are behind the drawn window. The oracle (own reading of
// `blocks_sight`) can see them; a window treated as opaque could not, which is the control.
for (const bx of [13, 14, 15]) {
assert.equal(oracleCell({ o, radius, walls: seenThrough, cell, x: bx, y: 9 }).maybe, true,
`cell ${bx},9 must be visible through the window`)
assert.equal(oracleCell({ o, radius, walls: opaque, cell, x: bx, y: 9 }).maybe, false,
`control: cell ${bx},9 must be hidden if the window wrongly blocked sight`)
}
// The gate agrees with the see-through oracle: those cells are allowed.
const cookie = ctx.seenCtx.cookie
for (const bx of [14, 15]) {
const r = await getTile(ngx.origin, tileUrl(scene.id, ctx.artVersion, bx, 9), cookie)
await r.arrayBuffer()
assert.equal(r.status, 200, `tile ${bx},9 behind the window must be allowed`)
}
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
test('tile gate: refusals, direct /_tiles, malformed and out-of-range paths', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
const ctx = await sceneWithVision(s, gmKey, ngx)
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
writeTiles(stateDir, { scene: scene.id, artVersion: ctx.artVersion,
tiles: [[9, 9], [110, 110], [127, 127]] })
const ok = tileUrl(scene.id, ctx.artVersion, 9, 9)
const unseen = tileUrl(scene.id, ctx.artVersion, 110, 110)
// The GM's own session is the differential control for every refusal below.
const gmCookie = ctx.gm.cookie
assert.equal((await getTile(ngx.origin, ok, gmCookie)).status, 200)
assert.equal((await getTile(ngx.origin, unseen, gmCookie)).status, 200)
assert.equal((await getTile(ngx.origin, tileUrl(scene.id, ctx.artVersion, 127, 127), gmCookie)).status,
200, 'the GM may have the last tile of the grid')
// Session rules: no cookie / unknown cookie / another player -> 403 on a tile Alice can see.
assert.equal((await getTile(ngx.origin, ok)).status, 403, 'no session is refused')
assert.equal((await getTile(ngx.origin, ok, 'fff_session=' + '0'.repeat(64))).status, 403,
'an unknown session is refused')
const bob = await createPlayer(ctx.gm.ws)
const bobSigned = await namePlayer(ngx.origin, bob.key, 'Bob')
const bobCookie = bobSigned.cookie
assert.equal((await getTile(ngx.origin, ok, bobCookie)).status, 403,
'another player cannot fetch Alice\'s tile')
// negative control: Bob may fetch his own explored tile once he has sight
const bobSeen = await openAs(ngx.origin, bob.key)
await bobSeen.ws.waitText('hello')
await bobSeen.ws.waitFor(m => m.t === 'explored' && m.full === true)
assert.equal((await getTile(ngx.origin, ok, bobSeen.cookie)).status, 403,
'a player with no vision token still has nothing explored')
bobSeen.ws.close()
// Direct /_tiles/ is internal: 404 even though the file exists, for every identity.
assert.ok(fs.existsSync(path.join(tileDir(stateDir, scene.id, ctx.artVersion), '9_9.png')))
for (const cookie of [undefined, ctx.seenCtx.cookie, gmCookie]) {
assert.equal((await getTile(ngx.origin, `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`, cookie)).status,
404, 'the internal alias is not reachable directly')
}
assert.equal((await getTile(ngx.origin, '/_tiles/')).status, 404)
// The gate's own answer, directly from Nim (before nginx consumes it).
const gate = await getTile(s.origin, ok, ctx.seenCtx.cookie)
assert.equal(gate.status, 200)
assert.equal(gate.headers.get('x-accel-redirect'), `/_tiles/${scene.id}/v${ctx.artVersion}/9_9.png`)
assert.equal(gate.headers.get('cache-control'), 'private')
assert.equal((await gate.text()), '', 'Nim sends the decision, not the bytes')
const refused = await getTile(s.origin, unseen, ctx.seenCtx.cookie)
assert.equal(refused.status, 403)
assert.equal(refused.headers.get('x-accel-redirect'), null)
// Malformed components: 404 whatever the session (the URL is parsed first), including for the GM.
const malformed = [
`/tiles/${scene.id}/v${ctx.artVersion}/00_0.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/0_01.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/+1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.PNG`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.png.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1`,
`/tiles/${scene.id}/v${ctx.artVersion}/1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1_2.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1__1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/_1_1.png`,
`/tiles/${scene.id}/v01/1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}x/1_1.png`,
`/tiles/${scene.id}/${ctx.artVersion}/1_1.png`,
`/tiles/0${scene.id}/v${ctx.artVersion}/1_1.png`,
`/tiles/${scene.id}/v9999999999/1_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/123456_1.png`,
`/tiles/${scene.id}/v${ctx.artVersion}/1_1.png/extra`,
]
for (const p of malformed) {
assert.equal((await getTile(ngx.origin, p, ctx.seenCtx.cookie)).status, 404, p)
assert.equal((await getTile(ngx.origin, p, gmCookie)).status, 404, `${p} (GM)`)
}
// Out of range, wrong scene and a stale art version: 404.
for (const p of [
tileUrl(scene.id, ctx.artVersion, 128, 0),
tileUrl(scene.id, ctx.artVersion, 0, 128),
tileUrl(scene.id, ctx.artVersion, 99999, 9),
tileUrl(scene.id, ctx.artVersion + 1, 9, 9),
tileUrl(scene.id + 1, ctx.artVersion, 9, 9),
]) {
assert.equal((await getTile(ngx.origin, p, ctx.seenCtx.cookie)).status, 404, p)
assert.equal((await getTile(ngx.origin, p, gmCookie)).status, 404, `${p} (GM)`)
}
// Traversal and encoding shapes never produce a file: the gate parses integers and builds the
// internal path itself (T12). Encoded slashes survive URL normalisation and reach the server.
for (const p of [
`/tiles/${scene.id}/v${ctx.artVersion}/..%2f..%2f..%2fstate.db`,
`/tiles/${scene.id}/v${ctx.artVersion}/%2e%2e%2f%2e%2e%2fstate.db`,
`/tiles/${scene.id}/v${ctx.artVersion}/9_9.png%00`,
`/tiles/${scene.id}/v${ctx.artVersion}/..%5c..%5cstate.db`,
]) {
const r = await getTile(ngx.origin, p, ctx.seenCtx.cookie)
assert.ok([400, 404].includes(r.status), `${p} -> ${r.status}`)
}
// A method that is not GET is never a tile (mummy's router answers 405 for the known path).
assert.ok([404, 405].includes((await fetch(`${ngx.origin}${ok}`, { method: 'POST',
headers: { Cookie: ctx.seenCtx.cookie } })).status))
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
// #31: `app.scene` is swapped (not mutated) by `scene.set` under the global lock. A handler that
// reads it twice can see two different records in one request; a read outside the lock races the
// assignment itself. This pins the shape of the two HTTP handlers that touch it (the WS handlers all
// run under the lock), because a data race is otherwise only visible to a sanitiser.
test('every handler reads app.scene at most once, under the lock (#31)', async () => {
const source = fs.readFileSync(path.join(projectRoot, 'server', 'main.nim'), 'utf8')
// The body of a proc: from its `proc name` line to the next top-level `proc`.
const bodyOf = name => {
const start = source.indexOf(`proc ${name}(`)
assert.ok(start > 0, `proc ${name} not found`)
const rest = source.slice(start + 1)
const next = rest.indexOf('\nproc ')
return rest.slice(0, next < 0 ? undefined : next)
}
for (const handler of ['tileGate', 'checkScene']) {
// Code only: the comments explain the rule and would count as reads.
const body = bodyOf(handler).split('\n').filter(l => !l.trim().startsWith('#')).join('\n')
const reads = body.split('app.scene').length - 1
assert.equal(reads, 1, `${handler} must read app.scene once (found ${reads})`)
const readAt = body.indexOf('app.scene')
const lockAt = body.indexOf('withLock app.dbLock')
assert.ok(lockAt >= 0 && lockAt < readAt,
`${handler} must take the lock before it reads app.scene`)
}
})
test('concurrent scene edits and tile requests answer whole tiles, never a mixture (#31)', async () => {
await withTileStack(async ({ s, gmKey, ngx, stateDir }) => {
const ctx = await sceneWithVision(s, gmKey, ngx)
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const url = tileUrl(scene.id, ctx.artVersion, 9, 9)
const want = writeTiles(stateDir, { scene: scene.id, artVersion: ctx.artVersion,
tiles: [[9, 9]] })
const expected = fs.readFileSync(want[0])
// The explored tile Alice may fetch; the gate may refuse it while a wall edit hides the cell,
// so both 200 and 403 are whole answers, and a 200 must be exactly the fixture bytes.
let allowed = 0
let refused = 0
const fetchTile = async () => {
const r = await getTile(ngx.origin, url, ctx.seenCtx.cookie)
assert.ok([200, 403].includes(r.status), `unexpected status ${r.status}`)
if (r.status === 200) {
allowed++
assert.ok(Buffer.from(await r.arrayBuffer()).equals(expected),
'a 200 must be one whole tile, not a mix of two scene records')
} else {
refused++
}
}
// Editors: `scene.set` (a full resync) and wall edits that change the explored grid, while the
// fetches run. Every edit is acked before the next one: they are serialised by the global lock.
const edits = (async () => {
for (let i = 0; i < 20; i++) {
assert.equal((await ctx.gm.ws.request({ t: 'scene.set', scene: scene.id,
name: `Cave ${i}` })).ok, true)
const w = await ctx.gm.ws.request({ t: 'wall.add', scene: scene.id,
a: [380, 200], b: [380, 420] })
assert.equal(w.ok, true, JSON.stringify(w))
assert.equal((await ctx.gm.ws.request({ t: 'wall.remove', scene: scene.id,
id: w.id })).ok, true)
}
})()
const fetches = (async () => {
for (let i = 0; i < 200; i++) await fetchTile()
})()
await Promise.all([edits, fetches])
assert.ok(allowed + refused === 200, `every request answered (${allowed} + ${refused})`)
assert.ok(allowed > 0, 'the request shape was fetchable at least once')
// The server is alive and still answers its own health after the interleaving.
assert.equal((await fetch(`${s.origin}/healthz`)).status, 200)
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
})
})
test('fixture tiles are generated by the helper and none is committed', async () => {
// The repo owns no PNG: tiles are generated per test into a state dir (DESIGN 13 M3).
const tracked = spawnSync('git', ['ls-files', '*.png'], { cwd: projectRoot, encoding: 'utf8' })
assert.equal(tracked.status, 0, tracked.stderr)
assert.equal(tracked.stdout.trim(), '', `committed PNG fixtures found:\n${tracked.stdout}`)
const stateDir = makeStateDir()
try {
const one = writeTiles(stateDir, { scene: 1, artVersion: 1, tiles: [[3, 4]] })
assert.equal(one.length, 1)
assert.equal(path.dirname(one[0]), tileDir(stateDir, 1, 1))
assert.ok(path.relative(projectRoot, one[0]).startsWith('..'), 'the fixture is outside the repo tree')
const bytes = fs.readFileSync(one[0])
assert.ok(isPng(bytes))
assert.equal(bytes.readUInt32BE(16), 32, '32 px tiles (DESIGN 3.3, #24)')
assert.equal(bytes.readUInt32BE(20), 32)
// two tiles differ, so a byte comparison in a test means something
const other = writeTiles(stateDir, { scene: 1, artVersion: 1, tiles: [[3, 5]] })
assert.ok(!bytes.equals(fs.readFileSync(other[0])))
// the writer itself emits a signature and the pinned dimensions
assert.ok(isPng(pngBytes(32, [1, 2, 3])))
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})