feat(cameras): booth camera tiles — latest snapshot at rest, live video while a vehicle is in view

Footer camera chips open/close a tile per camera (bottom right, ~15% wide, stacking
leftwards); the open set is a per-user preference (users.open_cameras). A tile shows the
camera's newest entry/exit snapshot and switches to live video while that camera pushes
vehicle events (per-camera activity, same 30 s TTL as lane status).

- devices: RTSP MJPEG client + RFC 2435 RTP/JPEG reassembly; Hikvision openLiveStream()
  on the sub-stream (x02, must be MJPEG — H.264 is refused with that reason)
- server: CameraLiveHub (one shared upstream per camera, latest-frame delivery, fps cap,
  linger, backoff), CameraActivity, /api/cameras/:id/latest-snapshot, WS
  /api/cameras/:id/live (shared handshake auth with /api/ws + device:read),
  PUT /api/auth/open-cameras, migration 0033 (open_cameras + snapshot device/time index)
- web: CameraDock, footer toggles, binary frames in the platform socket (Tauri too)
- .gitattributes: *.jpg / *.bin binary (byte-exact test fixtures)

Verified on park-lab cameras end to end and in headless Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:48:50 +01:00
parent b6f7ea65a4
commit 39fb5fb7c2
36 changed files with 2067 additions and 45 deletions
+40 -20
View File
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
import type { FastifyInstance } from "fastify";
import type { FastifyInstance, FastifyRequest } 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";
@@ -9,7 +9,9 @@ import {
type LaneStatusEvent,
type LanePresenceEvent,
type PlateRecognizedEvent,
type CameraActivityEvent,
} from "../device-events.js";
import type { CameraActivity } from "../camera-activity.js";
import { enrichEvent } from "../event-enrich.js";
import type { DeviceMonitor } from "../device-monitor.js";
import type { LaneStatus } from "../lane-status.js";
@@ -111,6 +113,32 @@ function isAllowedOrigin(origin: string | undefined, host: string | undefined):
return allow.includes(origin);
}
/**
* Authenticate a WebSocket handshake and return the caller's role id: Origin allowlist
* FIRST (anti-CSWSH), then a desktop ticket (x-ws-ticket) or the JWT cookie. Shared by
* every socket route (/api/ws, /api/cameras/:id/live) so they cannot drift apart.
* Permission checks stay with each route.
*/
export async function authenticateWsHandshake(req: FastifyRequest): Promise<string> {
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;
if (ticket !== undefined) {
const t = consumeWsTicket(ticket);
if (!t) {
throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 });
}
return t.roleId;
}
await req.jwtVerify(); // reads the HttpOnly cookie (browser path)
if (!req.user) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
return currentRoleId(req.user.sub) ?? "";
}
type OutMsg =
| {
kind: "hello";
@@ -118,12 +146,15 @@ type OutMsg =
devices: unknown;
lanes: LaneStatusEvent | null;
radar: LanePresenceEvent | null;
/** Camera ids currently seeing a vehicle (camera tiles go live). */
cameras: string[] | null;
}
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> | null }
| { kind: "printer-status"; event: unknown }
| { kind: "device-status"; event: unknown }
| { kind: "lane-status"; lanes: LaneStatusEvent }
| { kind: "lane-presence"; radar: LanePresenceEvent }
| { kind: "camera-activity"; camera: CameraActivityEvent }
| { kind: "plate-recognized"; plate: PlateRecognizedEvent };
declare module "fastify" {
@@ -139,6 +170,7 @@ export async function wsRoutes(
deviceMonitor: DeviceMonitor,
laneStatus: LaneStatus,
lanePresence: LanePresence,
cameraActivity: CameraActivity,
): Promise<void> {
// 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
@@ -157,25 +189,7 @@ export async function wsRoutes(
// 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 roleId = await authenticateWsHandshake(req);
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
req.wsRoleId = roleId;
@@ -206,6 +220,7 @@ export async function wsRoutes(
devices: seesDevices ? deviceMonitor.snapshot() : null,
lanes: seesDevices ? laneStatus.snapshot() : null,
radar: seesDevices ? lanePresence.snapshot() : null,
cameras: seesDevices ? cameraActivity.snapshot() : null,
});
// Subscribe to the live buses. Each handler recomputes occupancy from the
@@ -233,6 +248,10 @@ export async function wsRoutes(
const offPresence = deviceEvents.onLanePresence((radar) => {
if (seesDevices) send({ kind: "lane-presence", radar });
});
// A camera started/stopped seeing a vehicle → its booth tile switches live/snapshot.
const offCamera = deviceEvents.onCameraActivity((camera) => {
if (seesDevices) send({ kind: "camera-activity", camera });
});
// 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 });
@@ -245,6 +264,7 @@ export async function wsRoutes(
offLane();
offPresence();
offPlate();
offCamera();
});
},
);