From e514c424fd00ad0be672f67222b7dcf4025afcc1 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 22 Oct 2026 10:46:56 +0000 Subject: [PATCH 1/4] Cap each WebSocket action frame at one legal action A seated player's socket accepted frames up to the ws default of 100 MiB and parsed them in the message handler. The server now sets maxPayload to the compact JSON size of the longest action the engine can mint: PLAY_OPEN with two follow- instance ids and a safe-integer sequence (181 bytes). ws closes a larger frame with 1009 before it emits message, so trailing whitespace after a CONFIRM_HAND does not apply that action. A compact CONFIRM_HAND still applies and is broadcast. The payload error is ignored so the close does not exit the process. The socket wiring now lives in packages/server/src/sockets.ts. Tests: packages/server/tests/action-frame.test.ts. --- packages/server/src/index.ts | 98 +-------------- packages/server/src/sockets.ts | 125 +++++++++++++++++++ packages/server/tests/action-frame.test.ts | 133 +++++++++++++++++++++ 3 files changed, 262 insertions(+), 94 deletions(-) create mode 100644 packages/server/src/sockets.ts create mode 100644 packages/server/tests/action-frame.test.ts diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 9b0342e..250a642 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -1,11 +1,10 @@ +import type { Server } from "node:http"; import { serve } from "@hono/node-server"; -import { GameActionSchema, ENGINE_VERSION, RoleSchema, type Role } from "@clave/engine"; -import { WebSocket, WebSocketServer } from "ws"; -import { z } from "zod"; import { createApp } from "./app.js"; import { RoomDatabase } from "./database.js"; import { RoomCreateLimiter } from "./room-create-limit.js"; import { RoomManager } from "./rooms.js"; +import { attachGameSockets } from "./sockets.js"; const port = Number.parseInt(process.env.PORT ?? "8787", 10); const hostname = process.env.HOST ?? "0.0.0.0"; @@ -14,97 +13,8 @@ const rooms = new RoomManager(database); const app = createApp({ rooms, database, limiter: new RoomCreateLimiter() }); const server = serve({ fetch: app.fetch, port, hostname }); -const sockets = new WebSocketServer({ noServer: true }); -const clients = new Map(); - -function send(socket: WebSocket, payload: unknown): void { - if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(payload)); -} - -function broadcast(code: string): void { - const snapshots = rooms.snapshotsForRoom(code); - for (const [socket, client] of clients) { - if (client.code === code) send(socket, { type: "snapshot", snapshot: snapshots[client.role] }); - } -} - -/** Whether a seat's partner has yet to claim their seat, is connected now, or has dropped away. */ -function partnerPresence(code: string, role: Role): "absent" | "connected" | "away" { - const partner: Role = role === "lead" ? "follow" : "lead"; - for (const client of clients.values()) - if (client.code === code && client.role === partner) return "connected"; - try { - return rooms.availableRole(code) === partner ? "absent" : "away"; - } catch { - return "absent"; - } -} - -function broadcastPresence(code: string): void { - for (const [socket, client] of clients) { - if (client.code === code) - send(socket, { type: "presence", partner: partnerPresence(code, client.role) }); - } -} - -server.on("upgrade", (request, socket, head) => { - try { - const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`); - if (url.pathname !== "/ws") { - socket.destroy(); - return; - } - const code = url.searchParams.get("code")?.toUpperCase() ?? ""; - const role = RoleSchema.parse(url.searchParams.get("role")); - const seatToken = url.searchParams.get("token") ?? ""; - const clientVersion = Number.parseInt(url.searchParams.get("engineVersion") ?? "0", 10); - if (clientVersion !== ENGINE_VERSION) - throw new Error("This game has updated. Reload before reconnecting."); - rooms.authenticate(code, role, seatToken); - sockets.handleUpgrade(request, socket, head, (websocket) => { - clients.set(websocket, { code, role, seatToken }); - sockets.emit("connection", websocket, request); - }); - } catch (error) { - socket.write( - `HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n${error instanceof Error ? error.message : "Unauthorized"}`, - ); - socket.destroy(); - } -}); - -sockets.on("connection", (socket) => { - const client = clients.get(socket); - if (!client) return socket.close(4401, "Seat credentials missing"); - send(socket, { - type: "snapshot", - snapshot: rooms.snapshot(client.code, client.role, client.seatToken), - }); - broadcastPresence(client.code); - - socket.on("message", (raw) => { - try { - const message = z - .object({ - type: z.literal("action"), - sequence: z.number().int().nonnegative(), - action: GameActionSchema, - }) - .parse(JSON.parse(raw.toString())); - rooms.action(client.code, client.role, client.seatToken, message.sequence, message.action); - broadcast(client.code); - } catch (error) { - send(socket, { - type: "error", - message: error instanceof Error ? error.message : "Action rejected.", - }); - } - }); - socket.on("close", () => { - clients.delete(socket); - broadcastPresence(client.code); - }); -}); +// `serve` is typed as HTTP/1 or HTTP/2. This process listens with HTTP/1.1. +const sockets = attachGameSockets(server as Server, rooms); const maintenance = setInterval( () => { diff --git a/packages/server/src/sockets.ts b/packages/server/src/sockets.ts new file mode 100644 index 0000000..f8f7841 --- /dev/null +++ b/packages/server/src/sockets.ts @@ -0,0 +1,125 @@ +import type { Server } from "node:http"; +import { ENGINE_VERSION, GameActionSchema, RoleSchema, type Role } from "@clave/engine"; +import { WebSocket, WebSocketServer } from "ws"; +import { z } from "zod"; +import type { RoomManager } from "./rooms.js"; + +// Compact JSON for one action. PLAY_OPEN is the longest: two engine instance +// ids (`follow-` plus a safe integer) and a safe-integer sequence. `ws` closes +// a larger frame with 1009 before it emits `message`. +const largestInstanceId = `follow-${Number.MAX_SAFE_INTEGER}`; +export const ACTION_FRAME_MAX_BYTES = Buffer.byteLength( + JSON.stringify({ + type: "action", + sequence: Number.MAX_SAFE_INTEGER, + action: { + type: "PLAY_OPEN", + role: "follow", + positionInstanceId: largestInstanceId, + moveInstanceId: largestInstanceId, + }, + }), +); + +export function attachGameSockets(server: Server, rooms: RoomManager): WebSocketServer { + const sockets = new WebSocketServer({ noServer: true, maxPayload: ACTION_FRAME_MAX_BYTES }); + const clients = new Map(); + + function send(socket: WebSocket, payload: unknown): void { + if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(payload)); + } + + function broadcast(code: string): void { + const snapshots = rooms.snapshotsForRoom(code); + for (const [socket, client] of clients) { + if (client.code === code) + send(socket, { type: "snapshot", snapshot: snapshots[client.role] }); + } + } + + /** Whether a seat's partner has yet to claim their seat, is connected now, or has dropped away. */ + function partnerPresence(code: string, role: Role): "absent" | "connected" | "away" { + const partner: Role = role === "lead" ? "follow" : "lead"; + for (const client of clients.values()) + if (client.code === code && client.role === partner) return "connected"; + try { + return rooms.availableRole(code) === partner ? "absent" : "away"; + } catch { + return "absent"; + } + } + + function broadcastPresence(code: string): void { + for (const [socket, client] of clients) { + if (client.code === code) + send(socket, { type: "presence", partner: partnerPresence(code, client.role) }); + } + } + + server.on("upgrade", (request, socket, head) => { + try { + const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`); + if (url.pathname !== "/ws") { + socket.destroy(); + return; + } + const code = url.searchParams.get("code")?.toUpperCase() ?? ""; + const role = RoleSchema.parse(url.searchParams.get("role")); + const seatToken = url.searchParams.get("token") ?? ""; + const clientVersion = Number.parseInt(url.searchParams.get("engineVersion") ?? "0", 10); + if (clientVersion !== ENGINE_VERSION) + throw new Error("This game has updated. Reload before reconnecting."); + rooms.authenticate(code, role, seatToken); + sockets.handleUpgrade(request, socket, head, (websocket) => { + clients.set(websocket, { code, role, seatToken }); + sockets.emit("connection", websocket, request); + }); + } catch (error) { + socket.write( + `HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n${error instanceof Error ? error.message : "Unauthorized"}`, + ); + socket.destroy(); + } + }); + + sockets.on("connection", (socket) => { + const client = clients.get(socket); + if (!client) return socket.close(4401, "Seat credentials missing"); + // `ws` emits `error` and closes with 1009 when a frame exceeds maxPayload. + // Leaving that error unhandled would take down the process. + socket.on("error", (error: Error) => { + if ("code" in error && error.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH") return; + throw error; + }); + send(socket, { + type: "snapshot", + snapshot: rooms.snapshot(client.code, client.role, client.seatToken), + }); + broadcastPresence(client.code); + + socket.on("message", (raw) => { + try { + const message = z + .object({ + type: z.literal("action"), + sequence: z.number().int().nonnegative(), + action: GameActionSchema, + }) + .parse(JSON.parse(raw.toString())); + rooms.action(client.code, client.role, client.seatToken, message.sequence, message.action); + broadcast(client.code); + } catch (error) { + send(socket, { + type: "error", + message: error instanceof Error ? error.message : "Action rejected.", + }); + } + }); + socket.on("close", () => { + clients.delete(socket); + broadcastPresence(client.code); + }); + }); + + return sockets; +} diff --git a/packages/server/tests/action-frame.test.ts b/packages/server/tests/action-frame.test.ts new file mode 100644 index 0000000..61b9875 --- /dev/null +++ b/packages/server/tests/action-frame.test.ts @@ -0,0 +1,133 @@ +import { createServer, type Server } from "node:http"; +import { afterEach, describe, expect, it } from "vitest"; +import { ENGINE_VERSION } from "@clave/engine"; +import { WebSocket, type RawData } from "ws"; +import { RoomDatabase } from "../src/database.js"; +import { RoomManager } from "../src/rooms.js"; +import { ACTION_FRAME_MAX_BYTES, attachGameSockets } from "../src/sockets.js"; + +describe("seat socket action frames", () => { + let database: RoomDatabase | undefined; + let httpServer: Server | undefined; + const openSockets: WebSocket[] = []; + + afterEach(async () => { + for (const socket of openSockets) socket.terminate(); + openSockets.length = 0; + if (httpServer) { + const closing = httpServer; + httpServer = undefined; + await new Promise((resolve, reject) => { + closing.close((error) => (error ? reject(error) : resolve())); + }); + } + database?.close(); + database = undefined; + }); + + async function seatedLead(): Promise<{ + rooms: RoomManager; + socket: WebSocket; + incoming: ReturnType; + code: string; + seatToken: string; + }> { + database = new RoomDatabase(":memory:"); + const rooms = new RoomManager(database); + const lead = rooms.create("lead", true); + rooms.join(lead.code, "follow"); + httpServer = createServer(); + attachGameSockets(httpServer, rooms); + await new Promise((resolve) => { + httpServer!.listen(0, "127.0.0.1", () => resolve()); + }); + const address = httpServer.address(); + if (address === null || typeof address === "string") throw new Error("expected a TCP port"); + const query = new URLSearchParams({ + code: lead.code, + role: "lead", + token: lead.seatToken, + engineVersion: String(ENGINE_VERSION), + }); + const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws?${query}`); + openSockets.push(socket); + const incoming = messageQueue(socket); + await new Promise((resolve, reject) => { + socket.once("open", () => resolve()); + socket.once("error", (error) => reject(error)); + }); + return { rooms, socket, incoming, code: lead.code, seatToken: lead.seatToken }; + } + + function messageQueue(socket: WebSocket): { + nextMessage: () => Promise; + pending: () => unknown[]; + } { + const queue: unknown[] = []; + const waiters: Array<(message: unknown) => void> = []; + socket.on("message", (data) => { + const parsed: unknown = JSON.parse(text(data)); + const waiter = waiters.shift(); + if (waiter) waiter(parsed); + else queue.push(parsed); + }); + return { + nextMessage() { + const queued = queue.shift(); + if (queued !== undefined) return Promise.resolve(queued); + return new Promise((resolve) => waiters.push(resolve)); + }, + pending: () => queue, + }; + } + + function text(data: RawData): string { + if (typeof data === "string") return data; + if (Buffer.isBuffer(data)) return data.toString(); + if (Array.isArray(data)) return Buffer.concat(data).toString(); + return Buffer.from(data).toString(); + } + + const legalAction = JSON.stringify({ + type: "action", + sequence: 0, + action: { type: "CONFIRM_HAND", role: "lead" }, + }); + + it("applies a legal action from the seated player", async () => { + const { rooms, socket, incoming, code, seatToken } = await seatedLead(); + expect(await incoming.nextMessage()).toMatchObject({ + type: "snapshot", + snapshot: { sequence: 0 }, + }); + expect(await incoming.nextMessage()).toMatchObject({ type: "presence", partner: "away" }); + + socket.send(legalAction); + expect(await incoming.nextMessage()).toMatchObject({ + type: "snapshot", + snapshot: { sequence: 1, setupRole: "follow" }, + }); + expect(rooms.snapshot(code, "lead", seatToken).sequence).toBe(1); + }); + + it("closes a larger frame before that action can apply", async () => { + const { rooms, socket, incoming, code, seatToken } = await seatedLead(); + await incoming.nextMessage(); + await incoming.nextMessage(); + + const overflow = ACTION_FRAME_MAX_BYTES + 1 - Buffer.byteLength(legalAction); + expect(overflow).toBeGreaterThan(0); + const oversized = legalAction + " ".repeat(overflow); + expect(Buffer.byteLength(oversized)).toBe(ACTION_FRAME_MAX_BYTES + 1); + + const closed = new Promise((resolve, reject) => { + socket.once("close", (code) => resolve(code)); + socket.once("error", (error) => reject(error)); + }); + socket.send(oversized); + + expect(await closed).toBe(1009); + expect(incoming.pending()).toEqual([]); + expect(rooms.snapshot(code, "lead", seatToken).sequence).toBe(0); + }); +}); From b53460bc37dc803cdbca920d735f1aeb467a01e6 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sun, 29 Nov 2026 12:51:52 -0500 Subject: [PATCH 2/4] Keep malformed socket frames from taking down the server The seat socket error listener rethrew every error except the maxPayload length error. ws starts closing a socket before it emits error, so throwing skipped close cleanup and killed the process: an invalid-UTF-8 frame (WS_ERR_INVALID_UTF8) or a header declaring a length over 2^53 - 1 (WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH) from one seat took down every room. The listener now never throws; length closes stay quiet and other errors are logged with the room code. Tests: keep the reviewers cases - invalid UTF-8 closes only the offending socket with 1007, the crafted over-length header closes 1009 and the server keeps serving, a legal action padded to exactly the cap applies, and every GameAction variant at its largest legal size fits the cap (checked exhaustively against GameActionSchema so a new variant cannot silently outgrow it). --- packages/server/src/sockets.ts | 16 ++- packages/server/tests/action-frame.test.ts | 136 ++++++++++++++++++++- 2 files changed, 145 insertions(+), 7 deletions(-) diff --git a/packages/server/src/sockets.ts b/packages/server/src/sockets.ts index f8f7841..3165b14 100644 --- a/packages/server/src/sockets.ts +++ b/packages/server/src/sockets.ts @@ -85,11 +85,19 @@ export function attachGameSockets(server: Server, rooms: RoomManager): WebSocket sockets.on("connection", (socket) => { const client = clients.get(socket); if (!client) return socket.close(4401, "Seat credentials missing"); - // `ws` emits `error` and closes with 1009 when a frame exceeds maxPayload. - // Leaving that error unhandled would take down the process. + // `ws` starts closing this socket before it emits `error` (1009 over + // maxPayload, 1007 on invalid UTF-8, and so on). Never throw from this + // listener: that skips the `close` cleanup below and, with no + // uncaughtException handler, one malformed frame would take down every + // room. Length closes are the cap working as intended; report the rest. socket.on("error", (error: Error) => { - if ("code" in error && error.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH") return; - throw error; + if ( + "code" in error && + (error.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" || + error.code === "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH") + ) + return; + console.error(`[clave] seat socket error in room ${client.code}: ${error.message}`); }); send(socket, { type: "snapshot", diff --git a/packages/server/tests/action-frame.test.ts b/packages/server/tests/action-frame.test.ts index 61b9875..4ca66c3 100644 --- a/packages/server/tests/action-frame.test.ts +++ b/packages/server/tests/action-frame.test.ts @@ -1,6 +1,6 @@ import { createServer, type Server } from "node:http"; import { afterEach, describe, expect, it } from "vitest"; -import { ENGINE_VERSION } from "@clave/engine"; +import { ENGINE_VERSION, GameActionSchema, type GameAction } from "@clave/engine"; import { WebSocket, type RawData } from "ws"; import { RoomDatabase } from "../src/database.js"; import { RoomManager } from "../src/rooms.js"; @@ -31,6 +31,7 @@ describe("seat socket action frames", () => { incoming: ReturnType; code: string; seatToken: string; + url: string; }> { database = new RoomDatabase(":memory:"); const rooms = new RoomManager(database); @@ -49,14 +50,15 @@ describe("seat socket action frames", () => { token: lead.seatToken, engineVersion: String(ENGINE_VERSION), }); - const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws?${query}`); + const url = `ws://127.0.0.1:${address.port}/ws?${query}`; + const socket = new WebSocket(url); openSockets.push(socket); const incoming = messageQueue(socket); await new Promise((resolve, reject) => { socket.once("open", () => resolve()); socket.once("error", (error) => reject(error)); }); - return { rooms, socket, incoming, code: lead.code, seatToken: lead.seatToken }; + return { rooms, socket, incoming, code: lead.code, seatToken: lead.seatToken, url }; } function messageQueue(socket: WebSocket): { @@ -130,4 +132,132 @@ describe("seat socket action frames", () => { expect(incoming.pending()).toEqual([]); expect(rooms.snapshot(code, "lead", seatToken).sequence).toBe(0); }); + + it("closes only the offending socket on a non-length frame error", async () => { + const { socket, incoming } = await seatedLead(); + await incoming.nextMessage(); + await incoming.nextMessage(); + + const closed = new Promise((resolve) => { + socket.once("close", (code) => resolve(code)); + }); + const sender = ( + socket as unknown as { + _sender: { + send( + data: Buffer, + opts: { binary: boolean; compress: boolean; fin: boolean; mask: boolean }, + cb: () => void, + ): void; + }; + } + )._sender; + sender.send( + Buffer.from([0xc3, 0x28]), + { binary: false, compress: false, fin: true, mask: true }, + () => {}, + ); + + expect(await closed).toBe(1007); + }); + + it("applies a legal action padded to exactly the cap", async () => { + const { rooms, socket, incoming, code, seatToken } = await seatedLead(); + await incoming.nextMessage(); + await incoming.nextMessage(); + const atCap = legalAction + " ".repeat(ACTION_FRAME_MAX_BYTES - Buffer.byteLength(legalAction)); + expect(Buffer.byteLength(atCap)).toBe(ACTION_FRAME_MAX_BYTES); + socket.send(atCap); + expect(await incoming.nextMessage()).toMatchObject({ + type: "snapshot", + snapshot: { sequence: 1 }, + }); + expect(rooms.snapshot(code, "lead", seatToken).sequence).toBe(1); + }); + + it("fits every action variant at its largest legal size within the cap", () => { + // Exhaustive against GameActionSchema below: adding an action variant + // without a maximal entry here fails this test, so the cap cannot + // silently fall behind the longest legal action. Largest instance id + // the engine can mint is `follow-` plus a safe integer; card ids are + // 7 chars (`pos_999`). + const largestInstanceId = `follow-${Number.MAX_SAFE_INTEGER}`; + const largestByType = { + MULLIGAN: { type: "MULLIGAN", role: "follow" }, + CONFIRM_HAND: { type: "CONFIRM_HAND", role: "follow" }, + PLAY_OPEN: { + type: "PLAY_OPEN", + role: "follow", + positionInstanceId: largestInstanceId, + moveInstanceId: largestInstanceId, + }, + PLAY_MOVE: { type: "PLAY_MOVE", role: "follow", moveInstanceId: largestInstanceId }, + TRANSITION: { type: "TRANSITION", role: "follow", positionInstanceId: largestInstanceId }, + PLAY_FLOURISH: { + type: "PLAY_FLOURISH", + role: "follow", + flourishInstanceId: largestInstanceId, + }, + END_DANCE: { type: "END_DANCE", role: "follow" }, + STUMBLE: { type: "STUMBLE", role: "follow", recoveryInstanceId: largestInstanceId }, + BUY_LESSON: { + type: "BUY_LESSON", + role: "follow", + source: "intermediate", + cardId: "pos_999", + }, + LEARN_FROM_PARTNER: { type: "LEARN_FROM_PARTNER", role: "follow", cardId: "pos_999" }, + END_LESSON: { type: "END_LESSON", role: "follow" }, + SIGNAL_CARD: { type: "SIGNAL_CARD", role: "follow", instanceId: largestInstanceId }, + CLEAR_SIGNAL: { type: "CLEAR_SIGNAL", role: "follow" }, + UNDO_TURN: { type: "UNDO_TURN", role: "follow" }, + } satisfies Record; + + const schemaTypes = GameActionSchema.options.map((option) => option.shape.type.value); + expect(Object.keys(largestByType).sort()).toEqual([...schemaTypes].sort()); + + for (const action of Object.values(largestByType)) { + expect(GameActionSchema.parse(action), action.type).toEqual(action); + const frame = JSON.stringify({ + type: "action", + sequence: Number.MAX_SAFE_INTEGER, + action, + }); + expect(Buffer.byteLength(frame), action.type).toBeLessThanOrEqual(ACTION_FRAME_MAX_BYTES); + } + }); + + it("closes a frame declaring a length over 2^53 - 1 and keeps serving", async () => { + const { rooms, socket, incoming, code, seatToken, url } = await seatedLead(); + await incoming.nextMessage(); + await incoming.nextMessage(); + + const closed = new Promise((resolve) => { + socket.once("close", (closeCode) => resolve(closeCode)); + }); + // Masked text frame header declaring a 2^64 - 1 payload length. `ws` + // rejects this with WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH, a sibling + // length error to the maxPayload one; it must not take down the server. + const raw = Buffer.concat([ + Buffer.from([0x81, 0xff]), + Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), + Buffer.from([0x00, 0x00, 0x00, 0x00]), + ]); + (socket as unknown as { _socket: { write: (b: Buffer) => void } })._socket.write(raw); + + expect(await closed).toBe(1009); + expect(rooms.snapshot(code, "lead", seatToken).sequence).toBe(0); + + const second = new WebSocket(url); + openSockets.push(second); + const secondIncoming = messageQueue(second); + await new Promise((resolve, reject) => { + second.once("open", () => resolve()); + second.once("error", (error) => reject(error)); + }); + expect(await secondIncoming.nextMessage()).toMatchObject({ + type: "snapshot", + snapshot: { sequence: 0 }, + }); + }); }); From 9ad0ab601340a08fcb4fd1bef7f20dbf11f465db Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sun, 29 Nov 2026 12:58:25 -0500 Subject: [PATCH 3/4] Keep padded room codes out of the seat socket error log The upgrade handler stored the room code uppercased but untrimmed, while RoomManager.authenticate trims before lookup, so a seat holder could connect with a newline padded onto their real code. That newline then split the socket error log line added with the frame cap. Trim the code the same way at upgrade so the stored code is the canonical room code, with a regression test that connects with a padded code and checks the logged line. --- packages/server/src/sockets.ts | 5 ++- packages/server/tests/action-frame.test.ts | 43 ++++++++++++++++++++-- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/server/src/sockets.ts b/packages/server/src/sockets.ts index 3165b14..b55a5fc 100644 --- a/packages/server/src/sockets.ts +++ b/packages/server/src/sockets.ts @@ -63,7 +63,10 @@ export function attachGameSockets(server: Server, rooms: RoomManager): WebSocket socket.destroy(); return; } - const code = url.searchParams.get("code")?.toUpperCase() ?? ""; + // Trim like RoomManager.authenticate does, so the stored code is the + // canonical room code and cannot carry whitespace (e.g. a newline) + // into log lines or room matching. + const code = url.searchParams.get("code")?.trim().toUpperCase() ?? ""; const role = RoleSchema.parse(url.searchParams.get("role")); const seatToken = url.searchParams.get("token") ?? ""; const clientVersion = Number.parseInt(url.searchParams.get("engineVersion") ?? "0", 10); diff --git a/packages/server/tests/action-frame.test.ts b/packages/server/tests/action-frame.test.ts index 4ca66c3..ea80566 100644 --- a/packages/server/tests/action-frame.test.ts +++ b/packages/server/tests/action-frame.test.ts @@ -1,5 +1,5 @@ import { createServer, type Server } from "node:http"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { ENGINE_VERSION, GameActionSchema, type GameAction } from "@clave/engine"; import { WebSocket, type RawData } from "ws"; import { RoomDatabase } from "../src/database.js"; @@ -12,6 +12,7 @@ describe("seat socket action frames", () => { const openSockets: WebSocket[] = []; afterEach(async () => { + vi.restoreAllMocks(); for (const socket of openSockets) socket.terminate(); openSockets.length = 0; if (httpServer) { @@ -25,7 +26,7 @@ describe("seat socket action frames", () => { database = undefined; }); - async function seatedLead(): Promise<{ + async function seatedLead(codeSuffix = ""): Promise<{ rooms: RoomManager; socket: WebSocket; incoming: ReturnType; @@ -45,7 +46,7 @@ describe("seat socket action frames", () => { const address = httpServer.address(); if (address === null || typeof address === "string") throw new Error("expected a TCP port"); const query = new URLSearchParams({ - code: lead.code, + code: lead.code + codeSuffix, role: "lead", token: lead.seatToken, engineVersion: String(ENGINE_VERSION), @@ -260,4 +261,40 @@ describe("seat socket action frames", () => { snapshot: { sequence: 0 }, }); }); + + it("keeps a whitespace-padded room code out of the socket error log line", async () => { + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + // authenticate() trims the code, so a seat holder can connect with a + // newline padded onto their real code. The stored code must be the + // trimmed canonical code, or that newline splits the error log line. + const { socket, incoming, code } = await seatedLead("\n"); + await incoming.nextMessage(); + await incoming.nextMessage(); + + const closed = new Promise((resolve) => { + socket.once("close", (closeCode) => resolve(closeCode)); + }); + const sender = ( + socket as unknown as { + _sender: { + send( + data: Buffer, + opts: { binary: boolean; compress: boolean; fin: boolean; mask: boolean }, + cb: () => void, + ): void; + }; + } + )._sender; + sender.send( + Buffer.from([0xc3, 0x28]), + { binary: false, compress: false, fin: true, mask: true }, + () => {}, + ); + + expect(await closed).toBe(1007); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith( + `[clave] seat socket error in room ${code}: Invalid WebSocket frame: invalid UTF-8 sequence`, + ); + }); }); From f14edf589e10a643ce2a3dc7307dd5065d58484e Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sun, 29 Nov 2026 13:30:42 -0500 Subject: [PATCH 4/4] Size the frame-cap test for the call actions Master's call work added ADJUST and COVER_CALL to GameActionSchema and gave END_DANCE a callId, so the cap test's maximal entries no longer covered every variant and its exhaustiveness assertion failed on both CI legs. Add both actions at the largest minted instance id, end the dance with call_999 instead of omitting the call, and record the call-id length beside the card-id one. PLAY_OPEN stays the longest legal frame, so the cap itself does not move. --- packages/server/tests/action-frame.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/server/tests/action-frame.test.ts b/packages/server/tests/action-frame.test.ts index ea80566..36c734a 100644 --- a/packages/server/tests/action-frame.test.ts +++ b/packages/server/tests/action-frame.test.ts @@ -181,7 +181,7 @@ describe("seat socket action frames", () => { // without a maximal entry here fails this test, so the cap cannot // silently fall behind the longest legal action. Largest instance id // the engine can mint is `follow-` plus a safe integer; card ids are - // 7 chars (`pos_999`). + // 7 chars (`pos_999`), call ids are 8 chars (`call_999`). const largestInstanceId = `follow-${Number.MAX_SAFE_INTEGER}`; const largestByType = { MULLIGAN: { type: "MULLIGAN", role: "follow" }, @@ -199,7 +199,13 @@ describe("seat socket action frames", () => { role: "follow", flourishInstanceId: largestInstanceId, }, - END_DANCE: { type: "END_DANCE", role: "follow" }, + ADJUST: { type: "ADJUST", role: "follow", positionInstanceId: largestInstanceId }, + END_DANCE: { type: "END_DANCE", role: "follow", callId: "call_999" }, + COVER_CALL: { + type: "COVER_CALL", + role: "follow", + recoveryInstanceId: largestInstanceId, + }, STUMBLE: { type: "STUMBLE", role: "follow", recoveryInstanceId: largestInstanceId }, BUY_LESSON: { type: "BUY_LESSON",