Files
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

430 lines
20 KiB
JavaScript

// Walls r1 (#56, T17, TESTING 10.3 "Door equivalence"): a player cannot tell a secret door from a
// solid wall, nor a locked door from a closed one. Two fresh real servers run ONE scripted sequence
// each; the only difference between their worlds is the switches of the segment under test. Every
// player's complete received frame sequence (hello, roster, vision, explored full+delta, token with
// statuses, encountered, every ack/nack) and the per-tile HTTP status/body sweep must be identical
// after canonicalisation. The positive control is the same script with the segment an OPEN door: it
// must produce a different transcript, otherwise this harness cannot fail.
//
// Canonicalisation is structural, never semantic: the one thing that is necessarily run-local is an
// opaque token id (the server's CSPRNG, DESIGN 8), so ids are mapped to TOK<n> in creation order and
// an encountered list is sorted by that id before comparison (a Table iteration order would
// otherwise vary with the random ids). Nothing else is normalised: `n`, player ids, positions,
// statuses, polygons, explored cells and tile statuses compare byte for byte.
//
// The `secretgap` fault build (LEAK_FAULT=secretgap) makes a secret door stop blocking sight in the
// player-facing computation; the same script must then FAIL as exactly SECRETGAP. A clean build
// passes, and tools/fault.test.mjs already proves the shipped binary carries no fault hook.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, refuseLivePort, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeTileGrid } from './tilefixture.mjs'
const SEG = { a: [600, 500], b: [600, 700] } // the differing segment, identical geometry
const GRID = { x0: 0, x1: 31, y0: 0, y1: 31 }
const canonical = value => {
if (Array.isArray(value)) return value.map(canonical)
if (value && typeof value === 'object') {
return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])]))
}
return value
}
// Map this run's opaque token ids to a stable ordinal, then canonicalise. Applied to player frames
// only: walls never reach a player, and GM frames are not compared.
function canonicalFrames(messages, tokenIds) {
const map = new Map(tokenIds.map((id, i) => [id, `TOK${i + 1}`]))
const rename = node => {
if (Array.isArray(node)) return node.map(rename)
if (node && typeof node === 'object') {
return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, rename(v)]))
}
if (typeof node === 'string' && map.has(node)) return map.get(node)
return node
}
const stable = m => {
const out = rename(m)
if (out && out.t === 'encountered') {
const byId = (x, y) => String(x.id).localeCompare(String(y.id))
if (Array.isArray(out.set)) out.set = [...out.set].sort(byId)
if (Array.isArray(out.del)) out.del = [...out.del].sort()
}
return canonical(out)
}
return messages.map(stable)
}
// ---------------------------------------------------------------------------------------------
// A stack: the real binary and the test nginx in front (the production shape, DESIGN 11.1).
async function stack(opts = {}) {
const stateDir = opts.stateDir ?? makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
refuseLivePort(nginxPort)
const server = await startServer({
stateDir, publicOrigin: httpsBaseUrl(nginxPort),
defines: opts.defines, env: opts.env,
})
const nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort })
return { stateDir, gmKey, server, nginx, origin: nginx.origin }
}
async function stopStack(s) {
if (!s) return
await stopTestNginx(s.nginx)
await stopServer(s.server)
fs.rmSync(s.stateDir, { recursive: true, force: true })
}
// ---------------------------------------------------------------------------------------------
// The one script. `variant` is the segment's switch set; every other action is identical.
async function runScript(ctx, variant, opts = {}) {
const gm = await openAs(ctx.origin, ctx.gmKey)
await gm.ws.waitText('hello')
const scene = (await gm.ws.waitText('walls')).scene
const add = async fields => {
const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
return ack.id
}
const request = async (fields, code) => {
const ack = await gm.ws.request({ t: fields.t, scene, ...fields })
if (code === undefined) assert.equal(ack.ok, true, JSON.stringify(ack))
else {
assert.equal(ack.ok, false, JSON.stringify(ack))
assert.equal(ack.code, code, JSON.stringify(ack))
}
return ack
}
// Common world: a far north wall, a door used for the close-push, and far walls the GM edits.
// `opts.geometry` (stories 29/30, #52) stores non-default thickness/placement/height on the push
// door and on the segment under test; this round those fields are inert by contract.
const geometry = opts.geometry ?? {}
await add({ a: [0, 0], b: [4096, 0], flags: { note: 'north' } })
const pushDoor = await add({ a: [300, 300], b: [300, 400], door: true, ...geometry })
const farWall = await add({ a: [2000, 1000], b: [2500, 1000] })
const farDoor = await add({ a: [2600, 1000], b: [2600, 1200], door: true })
// Two named players, so both sides of the differing segment have a viewer.
const alice = await createPlayer(gm.ws)
await namePlayer(ctx.origin, alice.key, 'Alice')
const bob = await createPlayer(gm.ws)
await namePlayer(ctx.origin, bob.key, 'Bob')
const token = async fields => {
const ack = await gm.ws.request({ t: 'token.create', scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
await gm.ws.waitFor(m => m.t === 'token' && m.id === ack.id)
return ack.id
}
// T1 sees the segment's left side; T2 sees the right side; T3 sits where the segment will be added
// (the GM's add must mark it stuck); T4 is for the close-push.
const t1 = await token({ kind: 'pc', pos: [520, 600], flags: { vision: true },
vision_radius: 300, controller: alice.id,
descriptive_name: 'Alice', actual_name: 'Alice' })
const t2 = await token({ kind: 'pc', pos: [680, 600], flags: { vision: true },
vision_radius: 300, controller: bob.id,
descriptive_name: 'Bob', actual_name: 'Bob' })
const t3 = await token({ kind: 'npc', pos: [615, 600], controller: alice.id,
descriptive_name: 'crate', actual_name: 'crate' })
const t4 = await token({ kind: 'npc', pos: [330, 350], controller: bob.id,
descriptive_name: 'barrel', actual_name: 'barrel' })
const tokenIds = [t1, t2, t3, t4]
const connect = async key => {
const c = await openAs(ctx.origin, key)
await c.ws.waitText('hello')
await c.ws.waitFor(m => m.t === 'explored' && m.full === true)
return c
}
let a = await connect(alice.key)
let b = await connect(bob.key)
// The GM adds the segment under test over T3 (stuck). This is the only world difference.
const segId = await add({ ...SEG, ...variant, ...geometry })
await sleep(60)
// An unrelated token move and unrelated wall/door edits: they must not perturb the player view.
await request({ t: 'token.move', id: t2, pos: [650, 600] })
await request({ t: 'wall.update', id: farWall, b: [2600, 1000] })
await request({ t: 'door.set', id: farDoor, open: true })
await request({ t: 'door.set', id: farDoor, open: false })
const extra = await add({ a: [3000, 3000], b: [3100, 3000] })
await request({ t: 'wall.remove', id: extra })
// Closing a door over a token pushes it aside exactly as today (the zero-thickness gate).
await request({ t: 'door.set', id: pushDoor, open: true })
await request({ t: 'token.move', id: t4, pos: [300, 350] })
await request({ t: 'door.set', id: pushDoor, open: false })
await sleep(40)
const pushed = gm.ws.messages.filter(m => m.t === 'token' && m.id === t4).pop()
assert.ok(Math.abs(pushed.pos[0] - 320) < 1e-3 && pushed.pos[1] === 350,
`closing a door over a token pushes it aside as today: ${JSON.stringify(pushed.pos)}`)
const gmWall = id => gm.ws.messages.filter(m => m.t === 'wall' && m.id === id).pop()
// The GM's door intent on the differing segment: refused `invalid` for a wall, a secret or a
// locked door; an ordinary closed door opens. GM-side only, so no player frame changes with it.
if (opts.segmentOpen === 'invalid') {
await request({ t: 'door.set', id: segId, open: true }, 'invalid')
} else if (opts.segmentOpen === 'ok') {
await request({ t: 'door.set', id: segId, open: true })
}
// Player moves: along, into and across the segment; one accepted, collision and over-cap nacks.
const move = async (client, id, pos, ok) => {
const ack = await client.ws.request({ t: 'token.move', id, pos })
assert.equal(ack.ok, ok, JSON.stringify(ack))
return ack
}
await move(a, t1, [570, 600], true)
const crossAlice = await move(a, t1, [640, 600], !!opts.crosses)
if (!opts.crosses) {
assert.deepEqual(crossAlice.pos, [570, 600], 'the uniform nack carries the old position only')
assert.equal(crossAlice.code, undefined, 'the uniform nack names no cause')
}
await move(a, t1, [520, 600], true)
const overCap = await move(a, t1, [2000, 600], false)
assert.equal(overCap.code, undefined)
await move(a, t1, [-10, 600], false)
const crossBob = await move(b, t2, [560, 600], !!opts.crosses)
if (!opts.crosses) {
assert.deepEqual(crossBob.pos, [650, 600])
assert.equal(crossBob.code, undefined)
}
await move(b, t2, [650, 600], true)
await move(b, t2, [3000, 600], false)
await sleep(80)
const framesA1 = [...a.ws.messages]
const framesB1 = [...b.ws.messages]
// A resync/reconnect: the whole state is rebuilt on a fresh connection.
a.ws.close(); b.ws.close()
await Promise.all([a.ws.closed, b.ws.closed])
a = await connect(alice.key)
b = await connect(bob.key)
await sleep(100)
const sceneBlock = gm.ws.messages.find(m => m.t === 'hello' && m.scene)?.scene
const art = sceneBlock?.art_version ?? 1
const frames = {
alice: canonicalFrames([...framesA1, ...a.ws.messages], tokenIds),
bob: canonicalFrames([...framesB1, ...b.ws.messages], tokenIds),
}
const cookies = { alice: a.cookie, bob: b.cookie }
a.ws.close(); b.ws.close(); gm.ws.close()
await Promise.all([a.ws.closed, b.ws.closed])
assert.equal(art, 1, 'the v1 art version is pinned (DESIGN 3.3)')
return { frames, cookies, scene, art, pushed: pushed.pos,
stored: { pushDoor: gmWall(pushDoor), seg: gmWall(segId) } }
}
// Every tile of the checked rectangle, as status + bytes. The fixture bytes are per-(x,y), so a
// status difference and a substituted body both show up. Independent of the WS transcript.
async function tileSweep(ctx, scene, art, cookie) {
const out = []
for (let y = GRID.y0; y <= GRID.y1; y++) {
for (let x = GRID.x0; x <= GRID.x1; x++) {
const r = await fetch(`${ctx.origin}/tiles/${scene}/v${art}/${x}_${y}.png`,
{ headers: { Cookie: cookie } })
const body = Buffer.from(await r.arrayBuffer())
out.push(`${x},${y}:${r.status}:${body.toString('base64')}`)
}
}
return out
}
// No difference -> []. Any player-frame or tile difference is the one class this obligation has.
function equivalenceClasses(a, b) {
const classes = new Set()
if (JSON.stringify(a.frames.alice) !== JSON.stringify(b.frames.alice)) classes.add('SECRETGAP')
if (JSON.stringify(a.frames.bob) !== JSON.stringify(b.frames.bob)) classes.add('SECRETGAP')
if (JSON.stringify(a.tiles.alice) !== JSON.stringify(b.tiles.alice)) classes.add('SECRETGAP')
if (JSON.stringify(a.tiles.bob) !== JSON.stringify(b.tiles.bob)) classes.add('SECRETGAP')
return [...classes]
}
// Runs one two-server pair end to end: identical script, one differing segment.
async function runPair(aVariant, bVariant, opts = {}) {
const dirs = [makeStateDir(), makeStateDir()]
const stacks = []
try {
for (const dir of dirs) {
// Fixture tiles for the whole rectangle: every tile the gate may allow has real bytes.
writeTileGrid(dir, { scene: 1, artVersion: 1, size: 32, ...GRID })
}
stacks.push(await stack({ ...(opts.a ?? {}), stateDir: dirs[0] }))
stacks.push(await stack({ ...(opts.b ?? {}), stateDir: dirs[1] }))
const runs = []
for (const [i, variant] of [aVariant, bVariant].entries()) {
const run = await runScript(stacks[i], variant, {
...opts,
geometry: opts.geometry?.[i] ?? null,
segmentOpen: opts.segmentOpen?.[i] ?? null,
crosses: opts.crosses?.[i] ?? false,
})
run.tiles = {
alice: await tileSweep(stacks[i], run.scene, run.art, run.cookies.alice),
bob: await tileSweep(stacks[i], run.scene, run.art, run.cookies.bob),
}
runs.push(run)
}
return { a: runs[0], b: runs[1] }
} finally {
for (const s of stacks.reverse()) await stopStack(s)
}
}
// ---------------------------------------------------------------------------------------------
// The equivalence pairs (TESTING 10.3 T17): secret vs wall, secret+locked vs wall, locked vs closed.
const PAIRS = [
{ name: 'a secret door is a solid wall',
a: {}, b: { door: true, secret: true }, segmentOpen: ['invalid', 'invalid'] },
{ name: 'a secret+locked door is a solid wall',
a: {}, b: { door: true, secret: true, locked: true }, segmentOpen: ['invalid', 'invalid'] },
{ name: 'a locked door is a closed door',
a: { door: true }, b: { door: true, locked: true }, segmentOpen: [null, null] },
]
for (const pair of PAIRS) {
test(`door equivalence: ${pair.name}`, async () => {
const { a, b } = await runPair(pair.a, pair.b, { segmentOpen: pair.segmentOpen })
assert.ok(a.frames.alice.length > 20, 'the script produced real player coverage')
assert.ok(a.tiles.alice.some(s => s.includes(':200:')), 'the sweep allowed some tiles')
assert.ok(a.tiles.alice.some(s => s.includes(':403:')), 'the sweep refused some tiles')
assert.deepEqual(equivalenceClasses(a, b), [],
`${pair.name}: one differing segment must give identical player frames and tile statuses`)
})
}
test('inert geometry: stored thickness, placement and height change neither the door push nor a player byte (#52)',
async () => {
// Stories 29/30: thickness, placement and height are accepted, stored and echoed by the GM's
// frames, but in this round every stored value behaves exactly like zero thickness / centre /
// full height. The defaults run and the geometry run play the same script; the push position
// and every player frame and tile must be identical.
const GEOMETRY = { thickness: 256, position: 'left', height: 1 }
const { a, b } = await runPair({}, {}, { geometry: [null, GEOMETRY] })
for (const [label, wall] of [['closed door', b.stored.pushDoor],
['wall segment', b.stored.seg]]) {
assert.deepEqual(
{ thickness: wall.thickness, position: wall.position, height: wall.height }, GEOMETRY,
`${label}: the non-default geometry is stored and echoed by the GM frame`)
}
assert.ok(Math.abs(a.pushed[0] - 320) < 1e-3 && a.pushed[1] === 350,
`the baseline close-push is the zero-thickness result: ${JSON.stringify(a.pushed)}`)
assert.deepEqual(b.pushed, a.pushed,
'stored thickness, placement and height change the door push by nothing')
assert.ok(b.tiles.alice.some(s => s.includes(':200:')), 'the sweep allowed some tiles')
assert.deepEqual(equivalenceClasses(a, b), [],
'the geometry run and the defaults run must give identical player frames and tile statuses')
})
test('door equivalence positive control: an open door produces a different transcript', async () => {
const { a, b } = await runPair({}, { door: true, open: true },
{ segmentOpen: ['invalid', 'ok'], crosses: [false, true] })
assert.notDeepEqual(equivalenceClasses(a, b), [],
'the harness must be able to fail: an open (passable, transparent) segment differs')
})
test('fault secretgap: the equivalence group fails as exactly SECRETGAP', async () => {
// One side is the fault build; the secret door stops blocking sight for players there, so the
// same script must be caught. Nothing else may be reported.
const { a, b } = await runPair({}, { door: true, secret: true }, {
segmentOpen: ['invalid', 'invalid'],
b: { defines: ['leakfault'], env: { LEAK_FAULT: 'secretgap' } },
})
assert.deepEqual(equivalenceClasses(a, b), ['SECRETGAP'])
})
// ---------------------------------------------------------------------------------------------
// The door-only open path (DESIGN 5.8, 6.1, 6.5): GM refusals name no cause; every door refuses a
// player with `not-allowed` whatever its settings.
test('door.set: secret and locked refuse opening, closing is allowed, players are refused every door', async () => {
const dir = makeStateDir()
let s
try {
s = await stack()
const gm = await openAs(s.origin, s.gmKey)
await gm.ws.waitText('hello')
const scene = (await gm.ws.waitText('walls')).scene
const add = async fields => {
const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
return ack.id
}
const setDoor = async (id, open, code) => {
const ack = await gm.ws.request({ t: 'door.set', scene, id, open })
if (code === undefined) assert.equal(ack.ok, true, JSON.stringify(ack))
else {
assert.equal(ack.ok, false, JSON.stringify(ack))
assert.equal(ack.code, code, JSON.stringify(ack))
// No refusal names a cause (DESIGN 5.8, 6.5): one static code and the frame number only.
assert.deepEqual(Object.keys(ack).sort(), ['code', 'n', 'ok', 'reqId', 't'])
assert.ok(!/secret|locked|door|wall|solid/i.test(JSON.stringify(ack)), JSON.stringify(ack))
}
return ack
}
const fixedWindow = await add({ a: [10, 10], b: [100, 10], blocks_sight: false,
blocks_movement: true })
const plainDoor = await add({ a: [10, 20], b: [100, 20], door: true })
const secret = await add({ a: [10, 30], b: [100, 30], door: true, secret: true })
const locked = await add({ a: [10, 40], b: [100, 40], door: true, locked: true })
const both = await add({ a: [10, 50], b: [100, 50], door: true, secret: true, locked: true })
// A fixed window/non-door has no open state at all, in either direction.
await setDoor(fixedWindow, true, 'invalid')
await setDoor(fixedWindow, false, 'invalid')
// A secret door is always closed: opening is refused, closing is a no-op and allowed.
await setDoor(secret, true, 'invalid')
await setDoor(secret, false)
// A locked door refuses only opening; closing is allowed (it is already closed).
await setDoor(locked, true, 'invalid')
await setDoor(locked, false)
await setDoor(both, true, 'invalid')
await setDoor(both, false)
// An ordinary closed door still opens.
await setDoor(plainDoor, true)
// Clearing the cause lets the same door open; the lock/secret never reaches a player.
await gm.ws.request({ t: 'wall.update', scene, id: locked, locked: false })
await setDoor(locked, true)
// A locked opening window is still see-through, but its leaf refuses to open until unlocked;
// once the lock is cleared the same intent opens it exactly like a door (#57).
const lockedWindow = await add({ a: [10, 60], b: [100, 60], blocks_sight: false,
door: true, locked: true })
await setDoor(lockedWindow, true, 'invalid')
await gm.ws.request({ t: 'wall.update', scene, id: lockedWindow, locked: false })
await setDoor(lockedWindow, true)
const player = await createPlayer(gm.ws)
await namePlayer(s.origin, player.key, 'Dora')
const p = await openAs(s.origin, player.key)
await p.ws.waitText('hello')
for (const id of [plainDoor, secret, locked, both, lockedWindow]) {
for (const open of [true, false]) {
const ack = await p.ws.request({ t: 'door.set', scene, id, open })
assert.equal(ack.ok, false, JSON.stringify(ack))
assert.equal(ack.code, 'not-allowed', JSON.stringify(ack))
assert.ok(!/secret|locked|door|wall|solid/i.test(JSON.stringify(ack)), JSON.stringify(ack))
}
}
p.ws.close(); gm.ws.close()
} finally {
await stopStack(s)
}
})