tools: raw WS client and the protocol test group (#18)

lib.mjs gains a node:net WebSocket client (frames, opcodes, masked sends, a close
handshake that mirrors a browser) so the harness can send what the global WebSocket
cannot: oversize, binary, unmasked, bad-opcode and garbage frames, and read Ping/Pong
and the empty close frame. wsUrl/rawUpgrade now carry the required proto query.

withserver.mjs gains the GM-server helpers (gm-key, withGmServer, signIn, openAs) that
auth.test.mjs used to keep privately, so both harnesses share one copy.

protocol.test.mjs is the protocol group of DESIGN 13 M3: hello/n, catalogue types,
proto, unknown type and ignored fields, exactly one ack per reqId, unnamed player,
malformed + binary frames, the flood close, the intent bucket, the 64 KB boundary,
unmasked/bad opcode, server Ping and Pong, the connection cap, and closing-then-1005.
auth.test.mjs now also asserts the closing reason on eviction and revocation.
This commit is contained in:
2026-11-15 08:33:12 +01:00
parent 88dd27e2cc
commit 5e43ffa545
4 changed files with 630 additions and 55 deletions
+228 -4
View File
@@ -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)
}
}