// Shared by the Node harnesses (DESIGN 10.4: Node 26, built-ins only, no npm deps). // The global WebSocket accepts a non-standard {headers} second argument; wsheaders.test.mjs // re-verifies on the wire that Cookie and Origin reach the server (the old "Node 22" note in // the prototype's lib.mjs was stale; here the pin is the devbox node 26). import crypto from 'node:crypto' import { spawnSync } from 'node:child_process' import fs from 'node:fs' import net from 'node:net' import path from 'node:path' import { fileURLToPath } from 'node:url' export const sleep = ms => new Promise(r => setTimeout(r, ms)) // Harness patience, not an assertion. The Node suite runs test files in parallel, so on a busy host // an ack can be late without being wrong; a test fails when the answer never comes, not when it // arrives after 5 s. Tests that assert *latency* keep their own explicit budgets. export const HARNESS_TIMEOUT_MS = 15000 export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) // Wall helpers shared by the harnesses (the leak driver's scenario coverage and any test that reads // GM wall frames). The leak checker keeps its own copies on purpose: the oracle must be independent // of the harness, not share code with it. export const isWindow = w => w.blocks_sight === false && w.blocks_movement === true export const anchorOf = w => [Math.round((w.a[0] + w.b[0]) / 2), Math.round((w.a[1] + w.b[1]) / 2)] // --------------------------------------------------------------------------------------------- // Shared Nim build cache for the Node harnesses and the client e2e. // // Every Node test *file* is its own process (node --test), and with --test-concurrency > 1 the // files run at the same time. Each used to build its own copy of the real server binary (and the // leak checker) into run/test/, so concurrent files raced on the output and its nimcache, and a // serial run paid the ~1.8 s compile once per file. The cache is keyed by the source bytes plus // the flags, guarded by an exclusive lock file, and published with rename(2), so: // * one file builds, every other file waits for it and then reuses the same binary; // * an unchanged tree (the next run) skips the compiler entirely; // * a partial binary never becomes visible under the final name. // run/ is gitignored; the per-variant nimcache under run/nimcache keeps two checkouts on one host // from writing each other's object files. export function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } function nimFiles(dir, out = []) { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, entry.name) if (entry.isDirectory()) nimFiles(p, out) else if (entry.name.endsWith('.nim')) out.push(p) } return out } // Hash of the inputs a build depends on: every .nim under `roots`, plus nim.cfg and the flags. export function sourceFingerprint(roots, extra = '') { const files = [] for (const root of roots) { const p = path.join(projectRoot, root) if (fs.existsSync(p) && fs.statSync(p).isDirectory()) files.push(...nimFiles(p)) else files.push(p) } files.push(path.join(projectRoot, 'nim.cfg')) files.sort() const h = crypto.createHash('sha256') h.update(extra) for (const f of files) { h.update(path.relative(projectRoot, f)) h.update('\0') h.update(fs.readFileSync(f)) h.update('\0') } return h.digest('hex') } function acquireLock(lockPath, timeoutMs = 180000) { const deadline = Date.now() + timeoutMs for (;;) { try { const fd = fs.openSync(lockPath, 'wx') fs.writeSync(fd, String(process.pid)) fs.closeSync(fd) return } catch (e) { if (e.code !== 'EEXIST') throw e try { // A crashed process leaves its lock behind: a lock older than 10 minutes is stale. if (Date.now() - fs.statSync(lockPath).mtimeMs > 600000) { fs.rmSync(lockPath, { force: true }); continue } } catch {} if (Date.now() > deadline) throw new Error(`build lock ${lockPath} was not released in ${timeoutMs} ms`) sleepSync(50) } } } // Build `out` from `roots` once per (source, flags) pair. `nimArgs(tmpOut)` returns the compiler // arguments with -o pointing at a temporary file. Returns `out`. export function cachedNimBuild({ out, roots, extra = '', nimArgs }) { fs.mkdirSync(path.dirname(out), { recursive: true }) const stampPath = `${out}.stamp` const stamp = `${sourceFingerprint(roots, extra)}\n${path.basename(out)}\n` const fresh = () => { if (!fs.existsSync(out)) return false try { return fs.readFileSync(stampPath, 'utf8') === stamp } catch { return false } } if (fresh()) return out const lockPath = `${out}.lock` acquireLock(lockPath) try { if (fresh()) return out const tmp = `${out}.tmp-${process.pid}` const r = spawnSync('nim', nimArgs(tmp), { cwd: projectRoot, encoding: 'utf8' }) if (r.status !== 0) { fs.rmSync(tmp, { force: true }) throw new Error(`nim ${nimArgs(tmp).join(' ')} failed:\n${r.stdout ?? ''}\n${r.stderr ?? ''}`) } fs.renameSync(tmp, out) fs.writeFileSync(stampPath, stamp) return out } finally { fs.rmSync(lockPath, { force: true }) } } export const baseUrl = port => `http://127.0.0.1:${port}` // The test nginx is TLS-only (#66): its origin is https, and its generated certificate is added to // this process's default CA list by tools/nginx.mjs. The backend server keeps its plain-http origin. export const httpsBaseUrl = port => `https://127.0.0.1:${port}` // Ports of a live dev session: never let a test stack touch them (prototype withserver.sh rule). export function refuseLivePort(port) { if ([8088, 8080, 9000].includes(port)) throw new Error(`refusing live port ${port}`) } export async function freePort() { const srv = net.createServer() await new Promise((res, rej) => { srv.once('error', rej); srv.listen(0, '127.0.0.1', res) }) const { port } = srv.address() await new Promise(res => srv.close(res)) return port } function decodeIPv4(hex) { const b = [] for (let i = 0; i < 8; i += 2) b.unshift(parseInt(hex.slice(i, i + 2), 16)) return b.join('.') } function decodeIPv6(hex) { // /proc/net/tcp6 stores four 32-bit words, each little-endian. const words = [] for (let w = 0; w < 4; w++) { const h = hex.slice(w * 8, w * 8 + 8) words.push(h.slice(6, 8) + h.slice(4, 6) + h.slice(2, 4) + h.slice(0, 2)) } let groups = [] for (const w of words) groups.push(w.slice(0, 4), w.slice(4, 8)) const compact = groups.join(':').replace(/(^|:)0(:0)+(:|$)/, '::') return compact } // Listening sockets of this host, from /proc (Linux only; the server side is NixOS). export function listeningSockets(port) { const out = [] for (const [file, proto] of [['/proc/net/tcp', 'tcp'], ['/proc/net/tcp6', 'tcp6']]) { let text try { text = fs.readFileSync(file, 'utf8') } catch { continue } for (const line of text.trim().split('\n').slice(1)) { const f = line.trim().split(/\s+/) if (f.length < 4 || f[3] !== '0A') continue // 0A = LISTEN const [addrHex, portHex] = f[1].split(':') if (parseInt(portHex, 16) !== port) continue out.push({ proto, hex: addrHex, addr: proto === 'tcp' ? decodeIPv4(addrHex) : decodeIPv6(addrHex) }) } } return out } // --------------------------------------------------------------------------------------------- // Auth helpers (#17): sign-in, cookie/Ws clients, and a raw HTTP upgrade for status checks. // The proto query is required from slice 3 on (DESIGN 6.2: missing or non-integer -> HTTP 400). // proto: null omits the query entirely (the 400 test). The default is the build's proto (2, #54). export function wsUrl(origin, proto = 2) { return origin.replace(/^http/, 'ws') + (proto === null ? '/ws' : `/ws?proto=${proto}`) } // POST /join. redirect: 'manual' so the 303 and its Set-Cookie are visible. export async function join(origin, key) { const r = await fetch(`${origin}/join`, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ key }).toString(), }) const setCookie = r.headers.get('set-cookie') return { status: r.status, location: r.headers.get('location'), setCookie, cookie: setCookie ? setCookie.split(';')[0] : null, headers: r.headers, body: await r.text(), } } // A WebSocket client that tracks acks by reqId and exposes a `closed` promise. export async function openWs(origin, cookie, opts = {}) { const headers = { Origin: opts.originHeader === undefined ? origin : opts.originHeader } if (cookie) headers.Cookie = cookie const ws = new WebSocket(wsUrl(origin, opts.proto), { headers }) let resolveClosed const closed = new Promise(res => { resolveClosed = res }) let closeInfo = null const client = { ws, closed, get closeInfo() { return closeInfo }, messages: [], nextReqId: 1, pending: new Map(), request(payload, timeoutMs = HARNESS_TIMEOUT_MS) { const reqId = client.nextReqId++ return new Promise((resolve, reject) => { const timer = setTimeout(() => { client.pending.delete(reqId) reject(new Error(`no ack for reqId ${reqId}`)) }, timeoutMs) client.pending.set(reqId, { resolve, timer }) ws.send(JSON.stringify({ ...payload, reqId })) }) }, close() { try { ws.close() } catch {} }, sendText(objOrText) { ws.send(typeof objOrText === 'string' ? objOrText : JSON.stringify(objOrText)) }, // First already-received or future message matching pred (the server's frames are async). async waitFor(pred, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const hit = client.messages.find(pred) if (hit) return hit if (closeInfo) throw new Error(`connection closed before a matching message: ` + `${JSON.stringify(closeInfo)} after ${client.messages.length} messages`) if (Date.now() > deadline) throw new Error(`no matching message in ${timeoutMs} ms; saw: ` + JSON.stringify(client.messages.slice(-4))) await sleep(10) } }, async waitText(t, timeoutMs = HARNESS_TIMEOUT_MS) { return await client.waitFor(m => m && m.t === t, timeoutMs) }, } ws.onmessage = event => { let msg try { msg = JSON.parse(event.data) } catch { client.messages.push(event.data); return } client.messages.push(msg) if (msg.t === 'ack' && client.pending.has(msg.reqId)) { const waiter = client.pending.get(msg.reqId) client.pending.delete(msg.reqId) clearTimeout(waiter.timer) waiter.resolve(msg) } } ws.onclose = event => { closeInfo = { code: event.code, reason: event.reason } resolveClosed(closeInfo) } await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('websocket open timeout')), HARNESS_TIMEOUT_MS) wireOpen(ws, () => { clearTimeout(timer); resolve() }, e => { clearTimeout(timer); reject(e) }) }) ws.onerror = () => {} // post-open errors surface as a close return client } function wireOpen(ws, onOpen, onError) { ws.onopen = onOpen ws.onerror = () => onError(new Error('websocket failed to open')) } // Raw HTTP upgrade attempt (node:net): lets a test read the status line before the 101. // originHeader: undefined = the server origin, null = omit the header, string = send it. // proto: undefined = 2 (the build's proto), null = omit the query parameter, else as given. export async function rawUpgrade(origin, opts = {}) { const u = new URL(origin) const key = crypto.randomBytes(16).toString('base64') const proto = opts.proto === undefined ? 2 : opts.proto const path = proto === null ? '/ws' : `/ws?proto=${proto}` const lines = [`GET ${path} HTTP/1.1`, `Host: ${u.host}`, 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Key: ${key}`, 'Sec-WebSocket-Version: 13'] if (opts.cookie !== undefined) lines.push(`Cookie: ${opts.cookie}`) if (opts.originHeader !== null) lines.push(`Origin: ${opts.originHeader ?? origin}`) return await new Promise((resolve, reject) => { const sock = net.createConnection(Number(u.port), '127.0.0.1') let buf = '' let settled = false const finish = (err, value) => { if (settled) return settled = true clearTimeout(timer) sock.destroy() if (err) reject(err) else resolve(value) } const timer = setTimeout(() => finish(new Error(`raw upgrade timeout; got: ${buf}`)), HARNESS_TIMEOUT_MS) sock.on('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n')) sock.on('data', chunk => { buf += chunk.toString('latin1') if (!buf.includes('\r\n\r\n')) return const head = buf.split('\r\n\r\n')[0] const [statusLine, ...rest] = head.split('\r\n') const status = Number(statusLine.split(' ')[1]) const headers = {} for (const line of rest) { const i = line.indexOf(':') if (i > 0) headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim() } finish(null, { status, headers, head }) }) sock.on('error', e => finish(e)) }) } // --------------------------------------------------------------------------------------------- // #18: a raw WebSocket client (node:net) that speaks frames, so a test can see control frames // (Ping/Pong/Close and their codes) and send frames no browser API allows: oversize, binary, // unmasked, garbage text. The browser client above is the default; this one is for the protocol // group. const OP_TEXT = 0x1, OP_BINARY = 0x2, OP_CLOSE = 0x8, OP_PING = 0x9, OP_PONG = 0xa export const opcodes = { text: OP_TEXT, binary: OP_BINARY, close: OP_CLOSE, ping: OP_PING, pong: OP_PONG } function clientFrame(opcode, payload, masked = true) { const len = payload.length const head = [] head.push(0x80 | opcode) // FIN + opcode const maskBit = masked ? 0x80 : 0 if (len < 126) head.push(maskBit | len) else if (len < 65536) head.push(maskBit | 126) else head.push(maskBit | 127) const parts = [Buffer.from(head)] if (len >= 126 && len < 65536) { const ext = Buffer.alloc(2); ext.writeUInt16BE(len); parts.push(ext) } else if (len >= 65536) { const ext = Buffer.alloc(8); ext.writeBigUInt64BE(BigInt(len)); parts.push(ext) } if (!masked) { parts.push(payload); return Buffer.concat(parts) } const mask = crypto.randomBytes(4) const body = Buffer.alloc(len) for (let i = 0; i < len; i++) body[i] = payload[i] ^ mask[i % 4] parts.push(mask, body) return Buffer.concat(parts) } // Pull whole frames out of a byte buffer. Returns {frames, rest}; every frame is // {opcode, payload: Buffer, text: string|null, masked}. function decodeFrames(buf) { const frames = [] let pos = 0 while (buf.length - pos >= 2) { const b0 = buf[pos], b1 = buf[pos + 1] const opcode = b0 & 0x0f const masked = (b1 & 0x80) !== 0 let len = b1 & 0x7f let off = pos + 2 if (len === 126) { if (buf.length < off + 2) break len = buf.readUInt16BE(off); off += 2 } else if (len === 127) { if (buf.length < off + 8) break len = Number(buf.readBigUInt64BE(off)); off += 8 } const maskLen = masked ? 4 : 0 if (buf.length < off + maskLen + len) break let payload = buf.subarray(off + maskLen, off + maskLen + len) if (masked) { const mask = buf.subarray(off, off + 4) const out = Buffer.alloc(len) for (let i = 0; i < len; i++) out[i] = payload[i] ^ mask[i % 4] payload = out } const frame = { opcode, payload, masked, text: null } if (opcode === OP_TEXT || opcode === OP_CLOSE) { // close reasons are UTF-8 too; a text frame must parse to be interesting frame.text = payload.toString('utf8') } frames.push(frame) pos = off + maskLen + len } return { frames, rest: buf.subarray(pos) } } export async function rawWs(origin, opts = {}) { const u = new URL(origin) const proto = opts.proto === undefined ? 2 : opts.proto const path = proto === null ? '/ws' : `/ws?proto=${proto}` const key = crypto.randomBytes(16).toString('base64') const lines = [`GET ${path} HTTP/1.1`, `Host: ${u.host}`, 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Key: ${key}`, 'Sec-WebSocket-Version: 13'] if (opts.cookie !== undefined) lines.push(`Cookie: ${opts.cookie}`) if (opts.originHeader !== null) lines.push(`Origin: ${opts.originHeader ?? origin}`) const sock = net.createConnection(Number(u.port), '127.0.0.1') sock.on('error', () => {}) // a server-side drop surfaces as 'close', which the test asserts on const client = { sock, frames: [], head: '', messages: [], // parsed text frames that are JSON, for parity with openWs closed: null, closedInfo: null, pendingClose: null, closeSent: false, sendText(objOrText) { const text = typeof objOrText === 'string' ? objOrText : JSON.stringify(objOrText) sock.write(clientFrame(OP_TEXT, Buffer.from(text, 'utf8'))) }, sendBinary(buf) { sock.write(clientFrame(OP_BINARY, Buffer.from(buf))) }, sendFrame(opcode, payload, masked = true) { sock.write(clientFrame(opcode, Buffer.from(payload), masked)) }, sendRaw(buf) { sock.write(buf) }, sendPong(payload) { client.sendFrame(OP_PONG, payload) }, sendClose(code = 1000) { const body = Buffer.alloc(2); body.writeUInt16BE(code) client.sendFrame(OP_CLOSE, body) }, // First already-received or future frame matching pred. Rejects after timeoutMs. async waitFor(pred, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const hit = client.frames.find(pred) if (hit) return hit if (client.closeEvent) throw new Error(`connection closed before a matching frame: ` + `${JSON.stringify(client.closeEvent)} after ${client.frames.length} frames`) if (Date.now() > deadline) throw new Error(`no matching frame in ${timeoutMs} ms; saw: ` + JSON.stringify(client.frames.map(f => ({ opcode: f.opcode, text: f.text })))) await sleep(5) } }, async waitText(t, timeoutMs = HARNESS_TIMEOUT_MS) { const frame = await client.waitFor(f => f.opcode === OP_TEXT && f.text && JSON.parse(f.text).t === t, timeoutMs) return JSON.parse(frame.text) }, get closeEvent() { return client.closedInfo }, close() { try { sock.destroy() } catch {} }, } client.closed = new Promise(resolve => { sock.on('close', () => { const info = client.pendingClose ?? { code: 1006, reason: '', tcpClosed: true } client.closedInfo = info resolve(info) }) }) await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error(`raw websocket handshake timeout; head: ${client.head}`)), HARNESS_TIMEOUT_MS) let buf = Buffer.alloc(0) let open = false sock.on('connect', () => sock.write(lines.join('\r\n') + '\r\n\r\n')) sock.on('data', chunk => { buf = Buffer.concat([buf, chunk]) if (!open) { const idx = buf.indexOf('\r\n\r\n') if (idx < 0) return client.head = buf.subarray(0, idx).toString('latin1') const status = Number(client.head.split('\r\n')[0].split(' ')[1]) buf = buf.subarray(idx + 4) if (status !== 101) { clearTimeout(timer) sock.destroy() reject(new Error(`expected 101, got ${status}: ${client.head}`)) return } open = true clearTimeout(timer) resolve() } const { frames, rest } = decodeFrames(buf) buf = rest for (const frame of frames) { if (frame.opcode === OP_CLOSE) { // RFC 6455: an empty close payload means "no status" -> a browser reports 1005 const code = frame.payload.length >= 2 ? frame.payload.readUInt16BE(0) : 1005 const reason = frame.payload.length > 2 ? frame.payload.subarray(2).toString('utf8') : '' client.pendingClose = { code, reason, tcpClosed: false } // Answer the close handshake like a browser does; mummy force-closes after 10 s otherwise. if (!client.closeSent) { client.closeSent = true try { client.sendClose(code === 1005 ? 1000 : code) } catch {} } } client.frames.push(frame) if (frame.opcode === OP_TEXT) { try { client.messages.push(JSON.parse(frame.text)) } catch {} } } }) sock.on('close', () => { if (!open) { clearTimeout(timer); reject(new Error(`socket closed during handshake: ${client.head}`)) } }) }) return client } // key.create from a GM connection: the ack shape of DESIGN 6.1. export async function createPlayer(gm) { const ack = await gm.request({ t: 'key.create' }) if (ack.ok !== true) throw new Error(`key.create refused: ${JSON.stringify(ack)}`) return { id: ack.id, key: ack.key } } // Wait until every reqId in `ids` has an ack; returns the ack messages. Lets a test assert // "exactly one ack" instead of trusting a promise per request. export async function collectAcks(client, ids, timeoutMs = HARNESS_TIMEOUT_MS) { const deadline = Date.now() + timeoutMs for (;;) { const acks = client.messages.filter(m => m && m.t === 'ack' && ids.includes(m.reqId)) if (acks.length >= ids.length) return acks if (Date.now() > deadline) throw new Error(`only ${acks.length}/${ids.length} acks arrived`) await sleep(5) } } // --------------------------------------------------------------------------------------------- // Slice 8 (#23): naming a player through the product's own intent. // // DESIGN 3.2 gives a player their display name at first sign-in through `player.setname`, which // slice 8 builds. The harness therefore names a player the way a browser does: sign in with the // player key, open a connection, send `player.setname`, wait for the ack and for the second `hello` // (6.1: the player's connections get `hello` + a full resync), then close the naming connection. // Nothing here writes to the DB out of band: the old `node:sqlite` fixture is gone, so a harness can // only reach a named player through the wire. export async function namePlayer(origin, key, name) { const signed = await join(origin, key) if (signed.status !== 303 || !signed.cookie) { throw new Error(`sign-in for namePlayer failed: ${signed.status}`) } const ws = await openWs(origin, signed.cookie) await ws.waitText('hello') const from = ws.messages.length const ack = await ws.request({ t: 'player.setname', name }) if (ack.ok !== true) { ws.close() throw new Error(`player.setname refused for "${name}": ${JSON.stringify(ack)}`) } // 6.1/6.3: `hello` again with `me.name`, then `roster` and the resync. Waiting for the second // hello pins the effect, not just the ack. const hello = await ws.waitFor((m, i) => i >= from && m.t === 'hello') await ws.waitFor((m, i) => i >= from && m.t === 'roster') ws.close() await ws.closed return { hello, ack, cookie: signed.cookie } }