// Node realm on purpose: this drives the real http/ws server, and jose's // key-type checks are realm-sensitive (a jsdom realm's Uint8Array intrinsics // differ from the externalized jose module's). import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { WebSocket } from "ws"; import { SignJWT } from "jose"; import { INTER_ROUND_COUNTDOWN_TICKS, TICK_MS } from "@/lib/minigames/bomperator/constants"; import type { BomperatorView } from "@/lib/minigames/bomperator/types"; import type { ServerMessage } from "@/arena/protocol"; import { startArena, type ArenaHandle } from "@/arena/server"; /** * End-to-end arena test: boots the real server on an ephemeral port with its * wall-clock tick loop running, connects two real WebSocket clients with real * minted tickets, plays a scripted round, and asserts snapshot progression + * input application over the sockets. This is the proof the WS path works * against the same module the unit suite pins. */ const TEST_SECRET = "test-arena-secret-0123456789"; let handle: ArenaHandle; let base: string; beforeAll(async () => { handle = await startArena({ port: 0, secret: TEST_SECRET, autoTick: true }); base = `http://127.0.0.1:${handle.port}`; }, 30_000); afterAll(async () => { await handle?.close(); }); async function mintTicket(uid: number, matchId: string): Promise { // Buffer key: realm-safe under vitest's jsdom (see src/arena/tickets.ts). const key = Buffer.from(TEST_SECRET, "utf8"); return new SignJWT({ uid, matchId }) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime("30s") .sign(key); } interface Envelope { success: boolean; data?: T; error?: string; } async function arenaPost(path: string, body: unknown): Promise> { const response = await fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json", "x-arena-secret": TEST_SECRET }, body: JSON.stringify(body), }); return (await response.json()) as Envelope; } /** A connected socket that records every server frame it receives. */ class TestClient { readonly ws: WebSocket; readonly messages: ServerMessage[] = []; private waiters: Array<() => void> = []; constructor(ws: WebSocket) { this.ws = ws; ws.on("message", (raw: Buffer) => { this.messages.push(JSON.parse(raw.toString("utf8")) as ServerMessage); for (const wake of this.waiters.splice(0)) wake(); }); } snapshots(): BomperatorView[] { return this.messages .filter((m): m is Extract => m.t === "snapshot") .map((m) => m.view); } latest(): BomperatorView | undefined { const all = this.snapshots(); return all[all.length - 1]; } send(message: object): void { this.ws.send(JSON.stringify(message)); } /** Resolve on the next frame matching the predicate (already-arrived ones count). */ async waitForFrame(predicate: (m: ServerMessage) => boolean, timeoutMs = 10_000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { const found = this.messages.find(predicate); if (found) return found; if (Date.now() > deadline) throw new Error("timed out waiting for frame"); await new Promise((resolve) => { const timer = setTimeout(resolve, Math.min(50, deadline - Date.now())); this.waiters.push(() => { clearTimeout(timer); resolve(); }); }); } } /** Resolve once a snapshot with version > `above` arrives. */ async nextSnapshot(above: number, timeoutMs = 10_000): Promise { const frame = await this.waitForFrame( (m) => m.t === "snapshot" && m.view.version > above, timeoutMs, ); return (frame as Extract).view; } close(): void { this.ws.close(); } } async function connectClient(uid: number, matchId: string, ticket?: string): Promise { const jwt = ticket ?? (await mintTicket(uid, matchId)); const ws = new WebSocket(`${base.replace("http", "ws")}/ws?ticket=${jwt}`); const client = new TestClient(ws); await new Promise((resolve, reject) => { ws.once("open", resolve); ws.once("error", () => reject(new Error("socket rejected"))); ws.once("close", () => reject(new Error("socket closed during handshake"))); }); client.send({ t: "join" }); return client; } describe("arena server over real websockets", () => { it( "plays a scripted round: join, start, tick progression, input application, ping", async () => { // Health first. const health = await fetch(`${base}/health`); expect(health.ok).toBe(true); // Lifecycle through the REST surface (what the Next actions proxy to). const created = await arenaPost<{ matchId: string }>("/matches", { userId: 7001, name: "Host", roundTarget: 1, }); expect(created.success).toBe(true); const matchId = created.data!.matchId; const joined = await arenaPost("/matches/join", { matchId, userId: 7002, name: "Guest", }); expect(joined.success).toBe(true); expect(joined.data!.players).toHaveLength(2); const started = await arenaPost("/matches/start", { matchId, userId: 7001, }); expect(started.success).toBe(true); expect(started.data!.phase).toBe("countdown"); // Two real sockets with real tickets. const host = await connectClient(7001, matchId); const guest = await connectClient(7002, matchId); const first = await host .waitForFrame((m) => m.t === "snapshot") .then((f) => (f as Extract).view); expect(first.yourSeat).toBe(0); expect(["countdown", "battle"]).toContain(first.phase); // Snapshot progression: the wall-clock loop advances versions on its own. const progressed = await host.nextSnapshot(first.version); expect(progressed.version).toBeGreaterThan(first.version); // Wait for the countdown to end (real time, ~3s at 20 Hz). let view = progressed; const battleDeadline = Date.now() + (INTER_ROUND_COUNTDOWN_TICKS + 60) * TICK_MS; while (view.phase !== "battle" && Date.now() < battleDeadline) { view = await host.nextSnapshot(view.version); } expect(view.phase).toBe("battle"); // Input over the socket: move right, expect ack and applied movement. const seq = 7; const beforeX = view.players[0]!.x; host.send({ t: "input", dir: "right", seq }); const ack = await host.waitForFrame((m) => m.t === "ack" && m.seq === seq); expect(ack.t).toBe("ack"); // Poll snapshots until the move shows up in server truth (movement is // grid-locked: leaving the spawn cell takes a few ticks). let moved = view; const moveDeadline = Date.now() + 3_000; while (Date.now() < moveDeadline) { moved = await host.nextSnapshot(moved.version); if (moved.players[0]!.x > beforeX + 0.2 && (moved.players[0]!.lastInputSeq ?? 0) >= seq) break; } expect(moved.players[0]!.x).toBeGreaterThan(beforeX + 0.2); expect(moved.players[0]!.lastInputSeq).toBeGreaterThanOrEqual(seq); // Guest sees the host move too (fan-out to both sockets). let guestView = guest.latest()!; const guestDeadline = Date.now() + 3_000; while (guestView.players[0]!.x <= beforeX + 0.2 && Date.now() < guestDeadline) { guestView = await guest.nextSnapshot(guestView.version); } expect(guestView.players[0]!.x).toBeGreaterThan(beforeX + 0.2); // Ping/pong RTT probe echoes the client timestamp. const t0 = Date.now(); host.send({ t: "ping", ts: t0 }); const pong = await host.waitForFrame((m) => m.t === "pong"); expect(pong.t === "pong" && pong.ts).toBe(t0); host.close(); guest.close(); }, 60_000, ); it("rejects an unverifiable ticket at connect time", async () => { await expect(connectClient(7001, "00000000-0000-4000-8000-000000000000", "garbage")).rejects.toThrow(); }); it("refuses REST calls without the shared secret", async () => { const response = await fetch(`${base}/matches`, { method: "POST", body: "{}" }); expect(response.status).toBe(401); }); });