f31e57b4ae
The live activity feed flagged anomalies with no explanation and showed opaque session keys. Make events self-describing and clickable. - Clickable feed rows → read-only event-detail modal: humanized fields, entry/exit snapshots, and signed-chain provenance collapsed behind an audit disclosure (operator sees the story, auditor expands for crypto). - Localized reason codes (backend i18n): the signed ledger now carries a stable REASON_CODE + params (+ English fallback) instead of free-text English. The UI translates via reason.<code> catalogs in sq/en, so an Albanian operator reads Albanian — from the same immutable event. Adding a language is a catalog change, no re-signing. (@parking/shared REASON_CODES, reasonPayload; entry/exit/subscription flows emit codes.) - Subscriber-name resolution: a SUBSESS-… occurrence now shows the subscription holder's name (fallback "Abonent"/"Subscriber"). Resolved read-time server-side (events API + WS push) as a non-signed subscriberLabel; cached with invalidation on subscription edit/delete. - Failed-snapshot visibility: a camera that was attempted but unreachable now shows a "⚠ camera unreachable" tile instead of a silent gap. The snapshots API returns failures[] from telemetry, filtered so a recovered capture shows no stale warning. Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
118 lines
5.3 KiB
TypeScript
118 lines
5.3 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
|
import type { Db } from "@parking/db";
|
|
import type { LedgerEvent } from "@parking/shared";
|
|
import { roleHasPermissions } from "../auth.js";
|
|
import { deviceEvents } from "../device-events.js";
|
|
import { enrichEvent } from "../event-enrich.js";
|
|
import type { DeviceMonitor } from "../device-monitor.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://<booth>/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<typeof getOccupancy>; devices: unknown }
|
|
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> }
|
|
| { kind: "printer-status"; event: unknown }
|
|
| { kind: "device-status"; event: unknown };
|
|
|
|
export async function wsRoutes(app: FastifyInstance, db: Db, deviceMonitor: DeviceMonitor): Promise<void> {
|
|
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() });
|
|
|
|
// 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 });
|
|
});
|
|
|
|
socket.on("close", () => {
|
|
offLedger();
|
|
offPrinter();
|
|
offDevice();
|
|
});
|
|
},
|
|
);
|
|
}
|