442 lines
18 KiB
JavaScript
442 lines
18 KiB
JavaScript
// 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 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))
|
|
|
|
export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
|
|
|
export const baseUrl = port => `http://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).
|
|
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.
|
|
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 = 5000) {
|
|
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 = 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
|
|
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')), 5000)
|
|
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 = 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 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}`)
|
|
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}`)), 5000)
|
|
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 ? 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)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// 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 }
|
|
}
|