server: /join, session cookies, ws auth and gm-key CLI (#17)

This commit is contained in:
2026-11-14 22:13:09 +01:00
parent e612db5826
commit 9d43aef9ed
5 changed files with 815 additions and 21 deletions
+279
View File
@@ -0,0 +1,279 @@
// M3 slice 2 (#17): getting in. Keys, sessions, cookies, the Origin check, connection caps and
// revocation, plus the `fff-vtt gm-key` command. Black-box through the real binary (withserver).
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'
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) => {
const ok = await join(s.origin, gmKey)
assert.equal(ok.status, 303)
assert.equal(ok.location, '/')
assert.match(ok.setCookie, /^fff_session=[0-9a-f]{64}; HttpOnly; Secure; SameSite=Strict; Path=\/$/)
assert.equal(ok.body, '')
assert.equal(ok.headers.get('referrer-policy'), 'no-referrer')
// comparison ignores case, dashes and spaces
for (const variant of [gmKey.toLowerCase(), gmKey.replaceAll('-', ' '), gmKey.replaceAll('-', '')]) {
const r = await join(s.origin, variant)
assert.equal(r.status, 303, `variant refused: ${variant}`)
assert.notEqual(r.cookie, ok.cookie, 'each sign-in issues a fresh session')
}
const wrong = await join(s.origin, 'AAAA-BBBB-CCCC-DDDD-EEEE')
assert.equal(wrong.status, 401)
assert.equal(wrong.setCookie, null)
assert.equal(wrong.body, '')
const missing = await fetch(`${s.origin}/join`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: 'other=x',
})
assert.equal(missing.status, 400)
assert.equal(missing.headers.get('set-cookie'), null)
const wrongType = await fetch(`${s.origin}/join`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key: gmKey }),
})
assert.equal(wrongType.status, 400)
const get = await fetch(`${s.origin}/join`)
assert.equal(get.status, 405)
const huge = await join(s.origin, 'A'.repeat(1100))
assert.equal(huge.status, 400)
})
})
test('no session, an unknown session, or a foreign Origin never upgrades', async () => {
await withGmServer(async (s, gmKey) => {
const { cookie } = await signIn(s.origin, gmKey)
assert.equal((await rawUpgrade(s.origin)).status, 401) // no cookie
assert.equal((await rawUpgrade(s.origin, { cookie: 'fff_session=' + '0'.repeat(64) })).status, 401)
assert.equal((await rawUpgrade(s.origin, { cookie, originHeader: 'https://evil.example' })).status, 403)
assert.equal((await rawUpgrade(s.origin, { cookie, originHeader: null })).status, 403) // missing Origin
assert.equal((await rawUpgrade(s.origin, { cookie })).status, 101)
// Origin is checked before the session: no cookie + bad origin is still 403 (T7 first line)
assert.equal((await rawUpgrade(s.origin, { originHeader: 'https://evil.example' })).status, 403)
})
})
test('one key on several devices: two cookies, one player, one per-player cap', async () => {
await withGmServer(async (s, gmKey) => {
const a = await signIn(s.origin, gmKey)
const b = await signIn(s.origin, gmKey)
assert.notEqual(a.cookie, b.cookie)
const wsA = await openWs(s.origin, a.cookie)
const wsB = await openWs(s.origin, b.cookie)
// three more on device A fill the player's four slots (two sessions count as one player)
const extra = []
for (let i = 0; i < 2; i++) extra.push(await openWs(s.origin, a.cookie))
assert.equal(wsA.closeInfo, null)
assert.equal(wsB.closeInfo, null)
// 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(fifth.closeInfo, null)
assert.equal(wsB.closeInfo, null)
for (const w of [wsB, ...extra, fifth]) w.close()
})
})
test('the 17th connection 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))
// 1 GM + 4 players; fill to 16 without breaching a per-player cap (4+4+4+3+GM)
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('key.replace: old key and old sessions die, live connections close, the new key works', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const player = await createPlayer(gm.ws)
const first = await openAs(s.origin, player.key)
const second = await openAs(s.origin, player.key)
const ack = await gm.ws.request({ t: 'key.replace', id: player.id })
assert.equal(ack.ok, true)
assert.match(ack.key, /^[A-Z2-9]{4}(-[A-Z2-9]{4}){4}$/)
assert.notEqual(ack.key, player.key)
// both live connections of that player are closed, the GM stays
await first.ws.closed
await second.ws.closed
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)
assert.equal((await rawUpgrade(s.origin, { cookie: first.cookie })).status, 401)
assert.equal((await rawUpgrade(s.origin, { cookie: second.cookie })).status, 401)
const fresh = await openAs(s.origin, ack.key)
assert.equal(fresh.ws.closeInfo, null)
fresh.ws.close(); gm.ws.close()
})
})
test('player.remove: key, sessions and connections gone; slot freed; the GM is not removable', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey)
const player = await createPlayer(gm.ws)
const session = await openAs(s.origin, player.key)
const ack = await gm.ws.request({ t: 'player.remove', id: player.id })
assert.equal(ack.ok, true)
await session.ws.closed
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')
const gmId = 1 // the GM is player 1 on a fresh DB
assert.equal((await gm.ws.request({ t: 'player.remove', id: gmId })).code, 'not-allowed')
assert.equal((await gm.ws.request({ t: 'key.replace', id: gmId })).code, 'not-allowed')
// the cap counts unused keys; removing a player frees the slot
const keys = []
for (let i = 0; i < 6; i++) keys.push(await createPlayer(gm.ws))
assert.equal((await gm.ws.request({ t: 'key.create' })).code, 'cap-reached')
await gm.ws.request({ t: 'player.remove', id: keys[0].id })
const replacement = await gm.ws.request({ t: 'key.create' })
assert.equal(replacement.ok, true)
assert.equal(typeof replacement.id, 'number')
gm.ws.close()
})
})
test('a player connection cannot use the GM intents', 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)
assert.equal((await p.ws.request({ t: 'key.create' })).code, 'not-allowed')
assert.equal((await p.ws.request({ t: 'key.replace', id: 1 })).code, 'not-allowed')
assert.equal((await p.ws.request({ t: 'player.remove', id: player.id })).code, 'not-allowed')
p.ws.close(); gm.ws.close()
})
})
test('gm-key: same key on re-run (also while the server runs); --new refuses while it runs and rotates after', async () => {
const stateDir = makeStateDir()
try {
const key1 = gmKeyOf(stateDir)
assert.equal(gmKeyOf(stateDir), key1, 're-run must print the same key')
let s = await startServer({ stateDir })
try {
assert.equal(gmKeyOf(stateDir), key1, 'read-only print works while the server runs')
const before = await join(s.origin, key1)
assert.equal(before.status, 303)
const gm = await openWs(s.origin, before.cookie)
const refused = runGmKey(stateDir, ['--new'])
assert.equal(refused.status, 3)
assert.match(refused.stderr, /running|lock/i)
assert.equal(gmKeyOf(stateDir), key1, 'a refused --new changed nothing')
assert.equal(gm.closeInfo, null, 'the refusal did not touch live sessions')
gm.close()
} finally {
await stopServer(s)
}
const rotated = runGmKey(stateDir, ['--new'])
assert.equal(rotated.status, 0, rotated.stderr)
const key2 = KEY_LINE.exec(rotated.stdout)[1]
assert.notEqual(key2, key1)
assert.equal(gmKeyOf(stateDir), key2)
s = await startServer({ stateDir })
try {
assert.equal((await join(s.origin, key1)).status, 401, 'the old GM key is dead')
assert.equal((await join(s.origin, key2)).status, 303)
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('no key or session token ever reaches the server log', async () => {
await withGmServer(async (s, gmKey) => {
const secrets = [gmKey]
const gm = await openAs(s.origin, gmKey)
secrets.push(gm.cookie ?? '')
const player = await createPlayer(gm.ws)
secrets.push(player.key)
const session = await openAs(s.origin, player.key)
secrets.push(session.cookie.split('=')[1])
const replaced = await gm.ws.request({ t: 'key.replace', id: player.id })
await session.ws.closed
secrets.push(replaced.key)
const again = await openAs(s.origin, replaced.key)
secrets.push(again.cookie.split('=')[1])
again.ws.close(); gm.ws.close()
// give the server a moment to flush its lines
await new Promise(r => setTimeout(r, 50))
const log = s.log()
for (const secret of secrets) {
if (!secret) continue
assert.ok(!log.includes(secret), `secret leaked into the log: ${secret}`)
assert.ok(!log.includes(secret.replaceAll('-', '')), 'secret (normalized) leaked into the log')
}
})
})
+123
View File
@@ -2,6 +2,7 @@
// 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'
@@ -61,3 +62,125 @@ export function listeningSockets(port) {
}
return out
}
// ---------------------------------------------------------------------------------------------
// 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'
}
// 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), { 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 {} },
}
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.
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',
'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))
})
}
+3 -1
View File
@@ -9,7 +9,9 @@ if ! nimble test -y > results/nimble-test.log 2>&1; then
exit 1
fi
cat results/nimble-test.log
node --test tools/*.test.mjs > results/node-test.log 2>&1
# One file at a time: every harness builds and runs the same real binary (run/test/server) and
# starts real servers; serialising removes build/write races. Ports and state dirs are isolated.
node --test --test-concurrency=1 tools/*.test.mjs > results/node-test.log 2>&1
rc=$?
cat results/node-test.log
exit $rc