import type { FastifyInstance } from "fastify"; import type { Db } from "@parking/db"; import type { LedgerEvent } from "@parking/shared"; import { roleHasPermissions } from "../auth.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. /** Permission required to watch the live feed (a read-only stream of ledger + * device status). Any role granted `report:read` may watch. */ const WATCH_PERMISSION = "report:read" as const; /** * 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; devices: unknown; lanes: LaneStatusEvent; radar: LanePresenceEvent; } | { kind: "ledger"; event: unknown; occupancy: ReturnType } | { 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 }; export async function wsRoutes( app: FastifyInstance, db: Db, deviceMonitor: DeviceMonitor, laneStatus: LaneStatus, lanePresence: LanePresence, ): Promise { app.get( "/api/ws", { websocket: true, // Origin allowlist (anti-CSWSH, replaces CSRF — see file header) THEN JWT + // role. Reject a cross/absent origin before touching the token, so a hijack // attempt never reaches an authenticated socket. jwtVerify reads the cookie. preHandler: async (req) => { if (!isAllowedOrigin(req.headers.origin, req.headers.host)) { throw Object.assign(new Error("forbidden origin"), { statusCode: 403 }); } await req.jwtVerify(); if (!req.user || !roleHasPermissions(req.user.roleId, [WATCH_PERMISSION])) { throw Object.assign(new Error("forbidden"), { statusCode: 403 }); } }, }, (socket) => { 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). send({ kind: "hello", occupancy: getOccupancy(db), devices: deviceMonitor.snapshot(), lanes: laneStatus.snapshot(), radar: lanePresence.snapshot(), }); // 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) => { // 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: getOccupancy(db) }); }); const offPrinter = deviceEvents.onPrinterStatus((event) => { 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) => { send({ kind: "device-status", event }); }); // Lane busy/free (camera vehicle detection → booth barrier lights). Advisory. const offLane = deviceEvents.onLaneStatus((lanes) => { send({ kind: "lane-status", lanes }); }); // Lane RADAR presence (presence-input edge → barrier-light blink). Advisory. const offPresence = deviceEvents.onLanePresence((radar) => { send({ kind: "lane-presence", radar }); }); // A late async plate recognition → backfill the badge on the matching feed row. Advisory. const offPlate = deviceEvents.onPlateRecognized((plate) => { send({ kind: "plate-recognized", plate }); }); socket.on("close", () => { offLedger(); offPrinter(); offDevice(); offLane(); offPresence(); offPlate(); }); }, ); }