/** * Arena connection tickets. * * A ticket is a short-lived (30s) JWT minted by the Next app * (`createArenaTicket` in the bomperator actions) and carried in the WebSocket * connect query string, because browsers cannot attach custom headers to a WS * handshake. It proves "this logged-in user id wants to watch/play this match * id" without exposing the Payload session to the arena process. * * Deliberate tradeoff (agreed in the plan): there is no single-use replay * store. The 30s expiry plus the narrow uid+matchId scope is the defense; a * stolen ticket can only impersonate its own seat in its own match for half a * minute. */ import { jwtVerify } from "jose"; export interface ArenaTicketClaims { /** User id of the connecting player. */ uid: number; /** Match the ticket grants access to. */ mid: string; } const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * Verify a ticket signature + expiry and check that the uid/matchId pair is * coherent (positive integer id, uuid match). Returns the claims or null; * never throws. */ export async function verifyArenaTicket( token: string, secret: string, ): Promise { if (!token || !secret) return null; try { // Buffer (not TextEncoder) so the key is a plain Node Uint8Array even when // this runs inside a jsdom test realm with its own intrinsics (jose's // instanceof checks are realm-sensitive). const key = Buffer.from(secret, "utf8"); const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"], clockTolerance: 5, }); const uid = typeof payload.uid === "number" ? payload.uid : Number(payload.uid); const mid = payload.matchId; if (!Number.isInteger(uid) || uid <= 0) return null; if (typeof mid !== "string" || !UUID_RE.test(mid)) return null; return { uid, mid }; } catch { return null; } }