diff --git a/tools/auth.test.mjs b/tools/auth.test.mjs index 2ecbfbc..80506e5 100644 --- a/tools/auth.test.mjs +++ b/tools/auth.test.mjs @@ -3,55 +3,10 @@ import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' -import { spawnSync } from 'node:child_process' -import { buildServer, makeStateDir, startServer, stopServer } from './withserver.mjs' -import { join, openWs, rawUpgrade } from './lib.mjs' +import { gmKeyOf, makeStateDir, parseGmKey, runGmKey, startServer, stopServer, + withGmServer, signIn, openAs } from './withserver.mjs' +import { createPlayer, join, openWs, rawUpgrade } from './lib.mjs' -const KEY_LINE = /GM key(?: \(new\))?: ([A-Z0-9-]+)/ - -function runGmKey(stateDir, extra = []) { - const r = spawnSync(buildServer(), ['gm-key', `--state-dir=${stateDir}`, ...extra], { encoding: 'utf8' }) - return { status: r.status, stdout: r.stdout, stderr: r.stderr } -} - -function gmKeyOf(stateDir) { - const r = runGmKey(stateDir) - assert.equal(r.status, 0, `gm-key failed: ${r.stderr}`) - const m = KEY_LINE.exec(r.stdout) - assert.ok(m, `no GM key in output: ${r.stdout}`) - return m[1] -} - -async function withGmServer(fn) { - const stateDir = makeStateDir() - const gmKey = gmKeyOf(stateDir) - const s = await startServer({ stateDir }) - try { - await fn(s, gmKey, stateDir) - } finally { - await stopServer(s) - fs.rmSync(stateDir, { recursive: true, force: true }) - } -} - -async function signIn(origin, key) { - const r = await join(origin, key) - assert.equal(r.status, 303, `join with a valid key: ${r.status}`) - assert.ok(r.cookie, 'no session cookie') - return r -} - -async function createPlayer(gm) { - const ack = await gm.request({ t: 'key.create' }) - assert.equal(ack.ok, true, JSON.stringify(ack)) - return { id: ack.id, key: ack.key } -} - -async function openAs(origin, key) { - const { cookie } = await signIn(origin, key) - const ws = await openWs(origin, cookie) - return { cookie, ws } -} test('POST /join: cookie flags, and every refusal is a bare status', async () => { await withGmServer(async (s, gmKey) => { @@ -123,7 +78,13 @@ test('one key on several devices: two cookies, one player, one per-player cap', // the fifth connection of the same player (device B) evicts the oldest (wsA) const fifth = await openWs(s.origin, b.cookie) const evicted = await wsA.closed - assert.equal(evicted.code, 1005) // mummy 0.4.8 sends an empty close frame (see DESIGN 3.2 note) + assert.equal(evicted.code, 1005) // mummy 0.4.8 sends an empty close frame (DESIGN 6.5, #18) + // ... so the reason rides the last app message before the close (FIXED, #18) + const last = wsA.messages[wsA.messages.length - 1] + assert.equal(last.t, 'closing') + assert.equal(last.reason, 'evicted') + assert.equal(last.code, 4002) + assert.equal(typeof last.n, 'number') assert.equal(fifth.closeInfo, null) assert.equal(wsB.closeInfo, null) for (const w of [wsB, ...extra, fifth]) w.close() @@ -162,6 +123,13 @@ test('key.replace: old key and old sessions die, live connections close, the new // both live connections of that player are closed, the GM stays await first.ws.closed await second.ws.closed + for (const ws of [first.ws, second.ws]) { + const last = ws.messages[ws.messages.length - 1] + assert.equal(last.t, 'closing') + assert.equal(last.reason, 'revoked') + assert.equal(last.code, 4001) + assert.equal(ws.closeInfo.code, 1005) // the close frame itself carries no code + } assert.equal(gm.ws.closeInfo, null) // the old key and the old cookies are dead; the new key signs in assert.equal((await join(s.origin, player.key)).status, 401) @@ -181,6 +149,7 @@ test('player.remove: key, sessions and connections gone; slot freed; the GM is n const ack = await gm.ws.request({ t: 'player.remove', id: player.id }) assert.equal(ack.ok, true) await session.ws.closed + assert.equal(session.ws.messages[session.ws.messages.length - 1].reason, 'revoked') assert.equal((await join(s.origin, player.key)).status, 401) assert.equal((await rawUpgrade(s.origin, { cookie: session.cookie })).status, 401) assert.equal((await gm.ws.request({ t: 'player.remove', id: player.id })).code, 'not-found') @@ -236,7 +205,7 @@ test('gm-key: same key on re-run (also while the server runs); --new refuses whi const rotated = runGmKey(stateDir, ['--new']) assert.equal(rotated.status, 0, rotated.stderr) - const key2 = KEY_LINE.exec(rotated.stdout)[1] + const key2 = parseGmKey(rotated.stdout) assert.notEqual(key2, key1) assert.equal(gmKeyOf(stateDir), key2) diff --git a/tools/lib.mjs b/tools/lib.mjs index 703e17f..1c83688 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -66,8 +66,10 @@ export function listeningSockets(port) { // --------------------------------------------------------------------------------------------- // Auth helpers (#17): sign-in, cookie/Ws clients, and a raw HTTP upgrade for status checks. -export function wsUrl(origin) { - return origin.replace(/^http/, 'ws') + '/ws' +// 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). +export function wsUrl(origin, proto = 1) { + return origin.replace(/^http/, 'ws') + (proto === null ? '/ws' : `/ws?proto=${proto}`) } // POST /join. redirect: 'manual' so the 303 and its Set-Cookie are visible. @@ -93,7 +95,7 @@ export async function join(origin, key) { 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), { headers }) + const ws = new WebSocket(wsUrl(origin, opts.proto), { headers }) let resolveClosed const closed = new Promise(res => { resolveClosed = res }) let closeInfo = null @@ -116,6 +118,25 @@ export async function openWs(origin, cookie, opts = {}) { }) }, 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 = 5000) { + 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 = 5000) { + return await client.waitFor(m => m && m.t === t, timeoutMs) + }, } ws.onmessage = event => { let msg @@ -147,10 +168,13 @@ function wireOpen(ws, onOpen, onError) { // 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 = 1, null = omit the query parameter, else the value as given. export async function rawUpgrade(origin, opts = {}) { const u = new URL(origin) const key = crypto.randomBytes(16).toString('base64') - const lines = ['GET /ws HTTP/1.1', `Host: ${u.host}`, 'Upgrade: websocket', + const proto = opts.proto === undefined ? 1 : 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}`) @@ -184,3 +208,203 @@ export async function rawUpgrade(origin, opts = {}) { 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 ? 1 : 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 = 5000) { + 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 = 5000) { + 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}`)), 5000) + 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 = 5000) { + 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) + } +} diff --git a/tools/protocol.test.mjs b/tools/protocol.test.mjs new file mode 100644 index 0000000..67f5faa --- /dev/null +++ b/tools/protocol.test.mjs @@ -0,0 +1,327 @@ +// 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, 1) // M3 ships proto 1 (DESIGN 6.2) + assert.equal(hello.role, 'gm') + assert.deepEqual(hello.me, { id: 1, name: 'GM' }) + + 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, 2) + assert.equal((await gm.ws.request({ t: 'conn.ping', ts: 43 })).n, 3) + + // 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.request({ t: 'conn.ping', ts: 7 })).n, 2) + // ... and the first connection's sequence did not move + assert.equal((await gm.ws.request({ t: 'conn.ping', ts: 44 })).n, 4) + for (const m of gm.ws.messages) assert.equal(typeof m.n, 'number', JSON.stringify(m)) + }) +}) + +// The 15 server message types of DESIGN 6.1. 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', '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']) + 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: 1 })).status, 101) + + const raw = await rawWs(s.origin, { cookie, proto: 2 }) + 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') + // a catalogue intent whose slice has not landed still answers exactly once + assert.equal((await gm.ws.request({ t: 'wall.add', scene: 's' })).code, 'unknown-type') + // 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 is refused to a named player too (step 6) + assert.equal((await gm.ws.request({ t: 'key.show', id: 2 })).code, 'unknown-type') + 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`: the next app frame is n = 2 + 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, 2) + 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() + }) +}) diff --git a/tools/withserver.mjs b/tools/withserver.mjs index 72a7710..d2f34e0 100644 --- a/tools/withserver.mjs +++ b/tools/withserver.mjs @@ -5,7 +5,7 @@ import { spawn, spawnSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { baseUrl, freePort, projectRoot, refuseLivePort, sleep } from './lib.mjs' +import { baseUrl, freePort, join, openWs, projectRoot, refuseLivePort, sleep } from './lib.mjs' const SERVER_BIN = path.join(projectRoot, 'run', 'test', 'server') @@ -103,3 +103,58 @@ export async function withServer(fn, opts = {}) { } } } + +// --------------------------------------------------------------------------------------------- +// A server with the GM key already made (#17/#18 harnesses). Kept here, next to the lifecycle, +// so the black-box test files share one copy. + +const KEY_LINE = /GM key(?: \(new\))?: ([A-Z0-9-]+)/ + +// Runs `fff-vtt gm-key` against a state dir (the CLI is part of the product, so it is the source +// of the GM key in every harness). +export function runGmKey(stateDir, extra = []) { + const r = spawnSync(buildServer(), ['gm-key', `--state-dir=${stateDir}`, ...extra], { encoding: 'utf8' }) + return { status: r.status, stdout: r.stdout, stderr: r.stderr } +} + +// The key line of a `gm-key` run: "GM key: XXXX-..." or "GM key (new): XXXX-...". +export function parseGmKey(stdout) { + const m = KEY_LINE.exec(stdout) + if (!m) throw new Error(`no GM key in output: ${stdout}`) + return m[1] +} + +// The GM key of a state dir, created on first call and stable afterwards. +export function gmKeyOf(stateDir) { + const r = runGmKey(stateDir) + if (r.status !== 0) throw new Error(`gm-key failed: ${r.stderr}`) + return parseGmKey(r.stdout) +} + +// A fresh state dir, its GM key and a running server; the dir is removed afterwards. +export async function withGmServer(fn) { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + return await fn(s, gmKey, stateDir) + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +} + +// POST /join with a key that must work, returning the cookie. +export async function signIn(origin, key) { + const r = await join(origin, key) + if (r.status !== 303) throw new Error(`join with a valid key: ${r.status}`) + if (!r.cookie) throw new Error('no session cookie') + return r +} + +// {cookie, ws}: a signed-in WebSocket client of that key. +export async function openAs(origin, key) { + const { cookie } = await signIn(origin, key) + const ws = await openWs(origin, cookie) + return { cookie, ws } +}