From 9d43aef9ed61edc4020f40533e6c4641b7c4accc Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sat, 14 Nov 2026 22:13:09 +0100 Subject: [PATCH] server: /join, session cookies, ws auth and gm-key CLI (#17) --- server/eventlog.nim | 5 +- server/main.nim | 425 ++++++++++++++++++++++++++++++++++++++++++-- tools/auth.test.mjs | 279 +++++++++++++++++++++++++++++ tools/lib.mjs | 123 +++++++++++++ tools/test.sh | 4 +- 5 files changed, 815 insertions(+), 21 deletions(-) create mode 100644 tools/auth.test.mjs diff --git a/server/eventlog.nim b/server/eventlog.nim index 6b7e18c..53bad98 100644 --- a/server/eventlog.nim +++ b/server/eventlog.nim @@ -90,7 +90,7 @@ proc quoteValue(v: string): string = const LevelNames: array[Level, string] = ["DEBUG", "INFO", "WARN", "ERROR"] proc log*(lg: Logger, level: Level, event: string, - fields: openArray[(string, string)] = []) = + fields: openArray[(string, string)] = []) {.gcsafe.} = if level < lg.level: return let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'") var raw = stamp & " " & LevelNames[level] & " " & event @@ -98,4 +98,5 @@ proc log*(lg: Logger, level: Level, event: string, let v = if isSensitiveField(name): "[redacted]" else: value raw.add " " & name & "=" & quoteValue(v) withLock lg.lock: - lg.sink(lg.redactedValue(raw) & "\n") + {.cast(gcsafe).}: + lg.sink(lg.redactedValue(raw) & "\n") diff --git a/server/main.nim b/server/main.nim index 477d5ff..03509f1 100644 --- a/server/main.nim +++ b/server/main.nim @@ -1,30 +1,389 @@ -## fff-vtt entrypoint. M3 slice 1 (#16): config, state dir, SQLite + migration runner, GET /healthz, -## logging. Nothing game-specific yet; later slices add /join, /ws, /tiles here. +## fff-vtt entrypoint. M3 slice 2 (#17): getting in. Config, state dir + data-dir lock, SQLite +## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, and the authenticated `/ws` upgrade +## with connection caps and key/player revocation. Nothing game-specific yet. +## Wire codes/close codes and the rest of the envelope land in slice 3 (#18); this slice carries the +## minimum ack shape (DESIGN 6.1) for the three intents auth needs: key.create, key.replace, +## player.remove. ## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face. -import std/os +import std/[json, locks, options, os, strutils] +import db_connector/db_sqlite import mummy, mummy/routers -import config, db, eventlog +import config, db, eventlog, crypto, auth, conns, instancelock + +const + CookieName* = "fff_session" + ## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED. + MaxJoinBody* = 1024 + ## DESIGN 6.6: the sign-in body is at most 1 KB. + ProtoAck* = "ack" + +type + App = ref object + cfg: Config + lg: Logger + db: DbConn + dbLock: Lock + conns: Conns + instanceLock: InstanceLock + +var appHandle: pointer + ## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}` + ## (mummy's handler types are non-closure procs, so the state cannot be captured). +template app(): App = cast[App](appHandle) + +# --------------------------------------------------------------------------------------------------- +# HTTP helpers + +proc formValue(body, name: string): string = + ## application/x-www-form-urlencoded: first value of `name`, percent-decoded, '+' = space. + for pair in body.split('&'): + let eq = pair.find('=') + let rawName = if eq >= 0: pair[0 ..< eq] else: pair + if rawName != name: continue + let raw = if eq >= 0: pair[eq + 1 .. ^1] else: "" + result = "" + var i = 0 + while i < raw.len: + if raw[i] == '+': + result.add ' ' + inc i + elif raw[i] == '%' and i + 2 < raw.len: + let hex = raw[i + 1 .. i + 2] + try: + result.add char(parseHexInt(hex)) + except ValueError: + result.add raw[i] + inc i + continue + i += 3 + else: + result.add raw[i] + inc i + return + +proc sessionCookie(request: Request): string = + ## First `fff_session` cookie across all Cookie headers (mummy's [] returns only the first header). + for (name, value) in request.headers: + if name.toLowerAscii != "cookie": continue + for part in value.split(';'): + let p = part.strip + if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1] + +proc ackError(ws: WebSocket, reqId: int, code: string) = + ws.send($(%*{"t": ProtoAck, "reqId": reqId, "ok": false, "code": code})) + +proc ackOk(ws: WebSocket, reqId: int, extra: JsonNode = newJObject()) = + var ack = newJObject() + ack["t"] = %ProtoAck + ack["reqId"] = %reqId + ack["ok"] = %true + for key, value in extra: ack[key] = value + ws.send($ack) + +# --------------------------------------------------------------------------------------------------- +# HTTP handlers proc healthz(request: Request) {.gcsafe.} = - ## Liveness only in slice 1. M5 makes it report the global lock as well (DESIGN 11.3). + ## Liveness only in this slice. M5 makes it report the global lock as well (DESIGN 11.3). var headers: HttpHeaders headers["Content-Type"] = "application/json" request.respond(200, headers, """{"status":"ok"}""") +proc join(request: Request) {.gcsafe.} = + ## POST /join: the only way to get a session (DESIGN 3.2, 6.6). The key travels in the body only. + let contentType = request.headers["Content-Type"].toLowerAscii + if not contentType.startsWith("application/x-www-form-urlencoded"): + request.respond(400, body = "") + return + if request.body.len > MaxJoinBody: + request.respond(400, body = "") + return + let key = formValue(request.body, "key") + if key.len == 0 or key.len > MaxJoinBody: + request.respond(400, body = "") + return + + var player: Option[Player] + var token = "" + withLock app.dbLock: + player = findPlayerByKey(app.db, key) + if player.isSome: + token = randomSessionToken() + createSession(app.db, player.get.id, sha256Hex(token)) + if player.isNone: + # No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline). + app.lg.log(lvInfo, "join_refused") + request.respond(401, body = "") + return + + # The token is deliberately never registered for redaction: sessions never expire, so a value + # registry would grow without bound. It is only ever written to the Set-Cookie header; if a future + # call site passes it to the logger, the `cookie`/`session` field-name mask is the net (11.3). + app.lg.log(lvInfo, "join_ok", [("player", $player.get.id)]) + var headers: HttpHeaders + headers["Location"] = "/" + headers["Set-Cookie"] = CookieName & "=" & token & + "; HttpOnly; Secure; SameSite=Strict; Path=/" + headers["Referrer-Policy"] = "no-referrer" + request.respond(303, headers) + +proc wsUpgrade(request: Request) {.gcsafe.} = + ## GET /ws: Origin, then session, then the total cap, then the upgrade (DESIGN 6.5 rows 1-4). + if request.headers["Origin"] != app.cfg.publicOrigin: + request.respond(403, body = "") + return + let token = sessionCookie(request) + if token.len == 0: + request.respond(401, body = "") + return + + var player: Option[Player] + withLock app.dbLock: + player = sessionPlayer(app.db, sha256Hex(token)) + if player.isNone: + request.respond(401, body = "") + return + + if not app.conns.reserve(): + var headers: HttpHeaders + headers["Retry-After"] = "5" + app.lg.log(lvInfo, "conn_refused_total", [("player", $player.get.id)]) + request.respond(503, headers, body = "") + return + + var ws: WebSocket + try: + ws = request.upgradeToWebSocket() + except MummyError: + app.conns.cancelReserve() + request.respond(400, body = "") + return + + let activated = app.conns.activate(player.get.id, player.get.role, ws) + # Close the replacement race: a key.replace between the lookup and the activation must not leave + # a live connection on a revoked session. + var stillValid = false + withLock app.dbLock: + stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome + if not stillValid: + if app.conns.connById(activated.id).isSome: + app.conns.remove(activated.id) + ws.close() + return + if activated.evicted.isSome: + activated.evicted.get.close() + app.lg.log(lvInfo, "conn_evicted", [("player", $player.get.id), + ("evicted_conn", $activated.evictedId.get)]) + app.lg.log(lvInfo, "conn_open", [("player", $player.get.id), ("role", $player.get.role), + ("conn", $activated.id), ("total", $app.conns.activeCount)]) + +# --------------------------------------------------------------------------------------------------- +# WebSocket intents needed by this slice. Slice 3 adds the full envelope, error frames, rate limits +# and unknown-type handling; anything else here is ignored on purpose. + +proc handleIntent(conn: Conn, text: string) {.gcsafe.} = + var node: JsonNode + try: + node = parseJson(text) + except CatchableError: + return + if node.kind != JObject: return + let t = node{"t"} + let reqIdNode = node{"reqId"} + if t.kind != JString or reqIdNode.kind != JInt: return + let reqId = reqIdNode.getInt + + case t.getStr + of "key.create": + if conn.role != prGm: + ackError(conn.ws, reqId, "not-allowed") + return + var created: tuple[id: int, key: string] + var capped = false + withLock app.dbLock: + capped = playerCount(app.db) >= MaxPlayers + if not capped: created = createPlayerWithKey(app.db) + if capped: + ackError(conn.ws, reqId, "cap-reached") + return + app.lg.addSecret(created.key) + app.lg.log(lvInfo, "key_created", [("player", $created.id)]) + ackOk(conn.ws, reqId, %*{"id": created.id, "key": created.key}) + + of "key.replace": + if conn.role != prGm: + ackError(conn.ws, reqId, "not-allowed") + return + let idNode = node{"id"} + if idNode.kind != JInt: + ackError(conn.ws, reqId, "invalid") + return + let id = idNode.getInt + var key: Option[string] + var notFound = false + var notAllowed = false + withLock app.dbLock: + let target = playerById(app.db, id) + if target.isNone: + notFound = true + elif target.get.role == prGm: + notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2) + else: + key = replacePlayerKey(app.db, id) + if notFound: + ackError(conn.ws, reqId, "not-found") + return + if notAllowed: + ackError(conn.ws, reqId, "not-allowed") + return + if key.isNone: + ackError(conn.ws, reqId, "not-found") + return + let closed = app.conns.revokePlayer(id) + for ws in closed: ws.close() + app.lg.addSecret(key.get) + app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)]) + ackOk(conn.ws, reqId, %*{"key": key.get}) + + of "player.remove": + if conn.role != prGm: + ackError(conn.ws, reqId, "not-allowed") + return + let idNode = node{"id"} + if idNode.kind != JInt: + ackError(conn.ws, reqId, "invalid") + return + let id = idNode.getInt + var removed = false + var notFound = false + var notAllowed = false + withLock app.dbLock: + let target = playerById(app.db, id) + if target.isNone: + notFound = true + elif target.get.role == prGm: + notAllowed = true + else: + removed = removePlayer(app.db, id) + if notFound: + ackError(conn.ws, reqId, "not-found") + return + if notAllowed: + ackError(conn.ws, reqId, "not-allowed") + return + if not removed: + ackError(conn.ws, reqId, "not-found") + return + let closed = app.conns.revokePlayer(id) + for ws in closed: ws.close() + app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)]) + ackOk(conn.ws, reqId) + + else: + discard # slice 3 answers unknown-type; this slice only carries the auth intents + +proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} = + case event + of MessageEvent: + let conn = app.conns.connForWs(ws) + if conn.isNone: return + if message.kind == TextMessage: + handleIntent(conn.get, message.data) + of CloseEvent, ErrorEvent: + let conn = app.conns.connForWs(ws) + if conn.isSome: + app.conns.remove(conn.get.id) + app.lg.log(lvDebug, "conn_close", [("player", $conn.get.playerId), + ("conn", $conn.get.id)]) + else: + discard + +# --------------------------------------------------------------------------------------------------- +# Startup and CLI + proc buildRouter(): Router = result.get("/healthz", healthz) + result.post("/join", join) + result.get("/ws", wsUpgrade) -proc main() = +proc cliUsage(): string = + """fff-vtt - server-authoritative vision VTT + +Usage: fff-vtt [options] + fff-vtt gm-key [--new] [options] + +Options: + --public-origin= Browser origin the site is served from (default: http://localhost:8080). + Env: FFF_VTT_PUBLIC_ORIGIN + --port= Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT + --state-dir= Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR + -h, --help Print this help and exit. + +Commands: + gm-key Create the single GM if needed and print the GM key (same key on re-run). + gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server + holds the state-dir lock (stop the server first). + +The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. +""" + +proc runGmKey(rawArgs: seq[string]): int = + var rotate = false + var cfgArgs: seq[string] + for arg in rawArgs: + if arg == "--new": rotate = true + else: cfgArgs.add arg var cfg: Config try: - cfg = parseConfig(commandLineParams()) + cfg = parseConfig(cfgArgs) except ConfigError as e: - stderr.writeLine "fff-vtt: " & e.msg - quit 2 + stderr.writeLine "fff-vtt gm-key: " & e.msg + return 2 if cfg.help: - stdout.write usage() - quit 0 + stdout.write cliUsage() + return 0 + try: + createDir(cfg.stateDir) + except CatchableError as e: + stderr.writeLine "fff-vtt gm-key: cannot create " & cfg.stateDir & ": " & e.msg + return 1 + var lock: InstanceLock + if rotate: + lock = tryAcquire(cfg.stateDir) + if not lock.held: + stderr.writeLine "fff-vtt gm-key --new: the server is running on " & cfg.stateDir & + " (state-dir lock held); stop it first" + return 3 + + var conn: DbConn + try: + conn = openDatabase(cfg.dbPath) + except CatchableError as e: + stderr.writeLine "fff-vtt gm-key: cannot open " & cfg.dbPath & ": " & e.msg + return 1 + defer: close(conn) + try: + discard migrate(conn) + let created = ensureGm(conn, rotate) + if created.rotated: + stdout.writeLine "GM key (new): " & created.key + else: + stdout.writeLine "GM key: " & created.key + stdout.flushFile() + except CatchableError as e: + stderr.writeLine "fff-vtt gm-key: " & e.msg + return 1 + 0 + +proc readRedactionSecrets(db: DbConn, lg: Logger) = + ## The safety net behind "never log keys": register every stored key for redaction. + for row in db.getAllRows(sql"SELECT secret FROM player_key"): + if row.len > 0 and row[0].len >= MinSecretLen: + try: lg.addSecret(row[0]) + except ValueError: discard + +proc runServer(cfg: Config): int = let lg = newLogger() lg.log(lvInfo, "server_start", [("origin", cfg.publicOrigin), ("state_dir", cfg.stateDir), ("bind", BindAddress)]) @@ -32,21 +391,51 @@ proc main() = createDir(cfg.stateDir) except CatchableError as e: lg.log(lvError, "state_dir_failed", [("path", cfg.stateDir), ("error", e.msg)]) - quit 1 - let conn = try: openDatabase(cfg.dbPath) - except CatchableError as e: - lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)]) - quit 1 + return 1 + + var instanceLock = tryAcquire(cfg.stateDir) + if not instanceLock.held: + lg.log(lvError, "state_dir_locked", [("path", cfg.stateDir)]) + return 1 + + var conn: DbConn + try: + conn = openDatabase(cfg.dbPath) + except CatchableError as e: + lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)]) + return 1 let applied = try: migrate(conn) except CatchableError as e: lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)]) - quit 1 + return 1 lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)), ("applied", $applied)]) - let server = newServer(buildRouter().toHandler()) + let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock) + initLock(state.dbLock) + readRedactionSecrets(conn, lg) + appHandle = cast[pointer](state) + + let server = newServer(buildRouter().toHandler(), websocketEvent) lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)]) server.serve(Port(cfg.port), BindAddress) + 0 + +proc main() = + let args = commandLineParams() + if args.len > 0 and args[0] == "gm-key": + quit runGmKey(if args.len > 1: args[1 .. ^1] else: @[]) + + var cfg: Config + try: + cfg = parseConfig(args) + except ConfigError as e: + stderr.writeLine "fff-vtt: " & e.msg + quit 2 + if cfg.help: + stdout.write cliUsage() + quit 0 + quit runServer(cfg) when isMainModule: main() diff --git a/tools/auth.test.mjs b/tools/auth.test.mjs new file mode 100644 index 0000000..2ecbfbc --- /dev/null +++ b/tools/auth.test.mjs @@ -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') + } + }) +}) diff --git a/tools/lib.mjs b/tools/lib.mjs index 57032b9..703e17f 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -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)) + }) +} diff --git a/tools/test.sh b/tools/test.sh index 075e9fb..36021e7 100755 --- a/tools/test.sh +++ b/tools/test.sh @@ -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