import { randomBytes } from "node:crypto"; import type { FastifyInstance } from "fastify"; import type { Db } from "@parking/db"; import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared"; import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js"; import { effectiveModulesFor } from "../modules.js"; import { deviceEvents, type LaneStatusEvent, type LanePresenceEvent, type PlateRecognizedEvent, } from "../device-events.js"; import { enrichEvent } from "../event-enrich.js"; import type { DeviceMonitor } from "../device-monitor.js"; import type { LaneStatus } from "../lane-status.js"; import type { LanePresence } from "../lane-presence.js"; import { getOccupancy } from "../occupancy.js"; // Live booth feed over a WebSocket. The booth UI opens ONE socket and receives // server-pushed updates instead of polling: each signed ledger append (entry, // exit, payment, void) is fanned out, and the recomputed occupancy rides along // so the screen's count stays exact (occupancy is a fold over the same ledger, // never a counter). Printer-status changes are forwarded too. // // Auth: the handshake is a normal GET through Fastify's lifecycle, so the same // HttpOnly JWT cookie that guards the REST API guards this. We verify the JWT and // role here. A browser's WebSocket constructor cannot set custom headers, so the // CSRF double-submit header the REST mutations use is unavailable — which would // leave the socket open to Cross-Site WebSocket Hijacking: a malicious page in the // operator's browser could open ws:///api/ws, the browser would auto-attach // the HttpOnly cookie, and the attacker would receive the live entry/exit/payment // stream. The cookie alone is NOT a control here. So we replace the CSRF check with // an Origin allowlist: the handshake's Origin must be same-origin (or an explicitly // allowed booth UI origin). Non-browser clients (no Origin) are rejected too. // See auth.ts, event-log.ts (emitLedger), capacity-occupancy.md. // // Desktop shell (Tauri) exception — the WS TICKET. The desktop app's HTTP goes // through tauri-plugin-http (reqwest, its own cookie jar) and its WebSocket // through tauri-plugin-websocket (bare tungstenite, NO cookie jar at all), so // the JWT cookie set at login can never ride on the WS handshake — jwtVerify() // would 401 every connect (found 2026-09-04: the desktop live feed reconnected // every 10s forever). The JWT is HttpOnly and must stay out of JS, so instead // the desktop client POSTs /api/ws/ticket (normal cookie + CSRF auth) to get a // single-use, 30-second random ticket bound to its user, and presents it in an // `x-ws-ticket` header on the handshake. A browser page cannot set custom // headers on a WebSocket, so this path is unreachable from a browser and adds // no CSWSH surface; the Origin allowlist still applies to both paths. // WHO may watch, and WHAT they see (venue-modules.md §"Permissions matrix", move 3): // a role connects if it holds ANY watch permission — the core feed/occupancy/device // ones or an effective module's own (carwash:read) — and every pushed message is then // FILTERED per role: a ledger event needs feedPermissionFor(type) (the owning module's, // else event:read); occupancy + the plate backfill need session:read; device / printer / // lane / radar need device:read. `report:read` is the REPORTS screen, not the socket: the // wash desk gets a live queue without the booth's ledger, the booth a feed without reports. type Viewer = { has: (p: Permission) => boolean }; /** Handshake header carrying a desktop WS ticket (see file header). */ const WS_TICKET_HEADER = "x-ws-ticket"; /** A ticket is only good for the connect that immediately follows its issue. */ const WS_TICKET_TTL_MS = 30_000; interface WsTicket { sub: string; roleId: string; expiresAt: number; } /** Outstanding tickets. Tiny (one per desktop connect attempt), in-memory only — * a server restart invalidates them, which is fine: the client just asks for * another on its next reconnect. */ const tickets = new Map(); function issueWsTicket(sub: string, roleId: string): string { const now = Date.now(); for (const [key, t] of tickets) { if (t.expiresAt <= now) tickets.delete(key); } const ticket = randomBytes(32).toString("hex"); tickets.set(ticket, { sub, roleId, expiresAt: now + WS_TICKET_TTL_MS }); return ticket; } /** Single-use: the ticket is removed whether or not it turns out to be valid. */ function consumeWsTicket(ticket: string): WsTicket | null { const t = tickets.get(ticket); if (!t) return null; tickets.delete(ticket); return t.expiresAt > Date.now() ? t : null; } /** * Is the handshake's Origin trusted? Same-origin (Origin host === Host header) is * always allowed; additional origins can be allowlisted via WS_ALLOWED_ORIGINS * (comma-separated) for a booth UI served from a different origin. A missing or * mismatched Origin is rejected — that is the anti-CSWSH control. */ function isAllowedOrigin(origin: string | undefined, host: string | undefined): boolean { if (!origin) return false; // no Origin → not a same-origin browser request let originHost: string; try { originHost = new URL(origin).host; } catch { return false; // malformed Origin } if (host && originHost === host) return true; // same-origin (any scheme/port match via host) const allow = (process.env.WS_ALLOWED_ORIGINS ?? "") .split(",") .map((s) => s.trim()) .filter(Boolean); return allow.includes(origin); } type OutMsg = | { kind: "hello"; occupancy: ReturnType | null; devices: unknown; lanes: LaneStatusEvent | null; radar: LanePresenceEvent | null; } | { kind: "ledger"; event: unknown; occupancy: ReturnType | null } | { kind: "printer-status"; event: unknown } | { kind: "device-status"; event: unknown } | { kind: "lane-status"; lanes: LaneStatusEvent } | { kind: "lane-presence"; radar: LanePresenceEvent } | { kind: "plate-recognized"; plate: PlateRecognizedEvent }; declare module "fastify" { interface FastifyRequest { /** The role the WS preHandler authenticated (ticket or cookie path) — for the handler's filter. */ wsRoleId?: string; } } export async function wsRoutes( app: FastifyInstance, db: Db, deviceMonitor: DeviceMonitor, laneStatus: LaneStatus, lanePresence: LanePresence, ): Promise { // Desktop-only: mint a WS ticket for the signed-in session (see file header). // Ordinary cookie + CSRF auth — the desktop client CAN do that over HTTP (via // tauri-plugin-http), it just can't carry the cookie onto the WebSocket. app.post("/api/ws/ticket", { preHandler: requireAuth }, async (req) => ({ ticket: issueWsTicket(req.user.sub, req.user.roleId), expiresInMs: WS_TICKET_TTL_MS, })); app.get( "/api/ws", { websocket: true, // Origin allowlist (anti-CSWSH, replaces CSRF — see file header) THEN // session (JWT cookie, or a desktop WS ticket) THEN role. Reject a // cross/absent origin before touching either credential, so a hijack // attempt never reaches an authenticated socket. preHandler: async (req) => { if (!isAllowedOrigin(req.headers.origin, req.headers.host)) { throw Object.assign(new Error("forbidden origin"), { statusCode: 403 }); } const rawTicket = req.headers[WS_TICKET_HEADER]; const ticket = Array.isArray(rawTicket) ? rawTicket[0] : rawTicket; let roleId: string; if (ticket !== undefined) { const t = consumeWsTicket(ticket); if (!t) { throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 }); } roleId = t.roleId; } else { await req.jwtVerify(); // reads the HttpOnly cookie (browser path) if (!req.user) { throw Object.assign(new Error("forbidden"), { statusCode: 403 }); } roleId = currentRoleId(req.user.sub) ?? ""; } const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p])); if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 }); req.wsRoleId = roleId; }, }, (socket, req) => { const roleId = req.wsRoleId ?? req.user?.roleId ?? ""; const viewer: Viewer = { has: (p) => roleHasPermissions(roleId, [p]) }; const seesOccupancy = viewer.has("session:read"); const seesDevices = viewer.has("device:read"); const send = (msg: OutMsg) => { // readyState 1 = OPEN; never throw out of an event-bus callback. if (socket.readyState === 1) { try { socket.send(JSON.stringify(msg)); } catch { /* drop on a broken socket */ } } }; // Initial snapshot so the client renders immediately, before any event: // occupancy AND the current device-status set (for the footer). // Each part of the snapshot only for a role that may see it (null otherwise). send({ kind: "hello", occupancy: seesOccupancy ? getOccupancy(db) : null, devices: seesDevices ? deviceMonitor.snapshot() : null, lanes: seesDevices ? laneStatus.snapshot() : null, radar: seesDevices ? lanePresence.snapshot() : null, }); // Subscribe to the live buses. Each handler recomputes occupancy from the // ledger (cheap fold) so the pushed count is always authoritative. const offLedger = deviceEvents.onLedger((event) => { // Per-role filter: the event type's feed permission (module's own, else event:read). if (!viewer.has(feedPermissionFor((event as { type: LedgerEvent["type"] }).type))) return; // Enrich with read-time display fields (subscriber name) before fan-out. const enriched = enrichEvent(db, event as unknown as LedgerEvent); send({ kind: "ledger", event: enriched, occupancy: seesOccupancy ? getOccupancy(db) : null }); }); const offPrinter = deviceEvents.onPrinterStatus((event) => { if (seesDevices) send({ kind: "printer-status", event }); }); // Unified device status (all categories) for the booth footer — pushed on // change; the initial set rode the hello above. const offDevice = deviceEvents.onDeviceStatus((event) => { if (seesDevices) send({ kind: "device-status", event }); }); // Lane busy/free (camera vehicle detection → booth barrier lights). Advisory. const offLane = deviceEvents.onLaneStatus((lanes) => { if (seesDevices) send({ kind: "lane-status", lanes }); }); // Lane RADAR presence (presence-input edge → barrier-light blink). Advisory. const offPresence = deviceEvents.onLanePresence((radar) => { if (seesDevices) send({ kind: "lane-presence", radar }); }); // A late async plate recognition → backfill the badge on the matching feed row. Advisory. const offPlate = deviceEvents.onPlateRecognized((plate) => { if (seesOccupancy) send({ kind: "plate-recognized", plate }); }); socket.on("close", () => { offLedger(); offPrinter(); offDevice(); offLane(); offPresence(); offPlate(); }); }, ); }