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
+47
View File
@@ -37,6 +37,24 @@ interface FontScaleBody {
fontScale: number;
}
// Booth camera tiles the user left open (camera device ids, in opening order). Bounded:
// a booth has a handful of cameras; the cap stops a client from storing junk.
const OPEN_CAMERAS_MAX = 8;
const DEVICE_ID_MAX = 64;
interface OpenCamerasBody {
openCameras: string[];
}
/** users.open_cameras (JSON text) → string[]; anything malformed reads as none open. */
function parseOpenCameras(raw: string | null | undefined): string[] {
try {
const v: unknown = JSON.parse(raw ?? "[]");
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, OPEN_CAMERAS_MAX) : [];
} catch {
return [];
}
}
// Self-service profile: a signed-in user edits their OWN display name + email. This is
// NOT the admin user-management path (routes/users.ts) — it only ever touches the caller
// (req.user.sub), needs no `user:*` permission, and can't change username, role, or any
@@ -90,6 +108,7 @@ function sessionView(
language: string;
theme: string;
fontScale: number;
openCameras?: string | null;
fullName?: string | null;
email?: string | null;
},
@@ -106,6 +125,7 @@ function sessionView(
language: user.language,
theme: user.theme,
fontScale: user.fontScale,
openCameras: parseOpenCameras(user.openCameras),
fullName: user.fullName ?? null,
email: user.email ?? null,
// Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes
@@ -219,6 +239,33 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
},
);
// Which booth camera tiles I left open (any signed-in user; only touches the caller).
// Persisted like `theme`, restored on the next login from any booth. Ids are not
// checked against `devices`: a removed camera's tile is simply not rendered.
app.put<{ Body: OpenCamerasBody }>(
"/api/auth/open-cameras",
{ preHandler: requireAuth },
async (req, reply) => {
const raw = req.body?.openCameras;
if (
!Array.isArray(raw) ||
raw.length > OPEN_CAMERAS_MAX ||
!raw.every((x) => typeof x === "string" && x.length > 0 && x.length <= DEVICE_ID_MAX)
) {
return reply
.code(400)
.send({ error: `openCameras must be up to ${OPEN_CAMERAS_MAX} device ids` });
}
const openCameras = [...new Set(raw as string[])];
await db
.update(users)
.set({ openCameras: JSON.stringify(openCameras) })
.where(eq(users.id, req.user.sub))
.run();
return { openCameras };
},
);
// Edit MY own display name / email (any signed-in user; no permission needed — it only
// touches the caller). Cannot change username or role — those stay admin-only (users.ts).
app.put<{ Body: ProfileBody }>(
+137
View File
@@ -0,0 +1,137 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { devices, snapshots, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { login, seedUser } from "../test-helpers.js";
// Booth camera tiles: latest-snapshot lookup (session:read), the live socket's auth gate
// (same handshake as /api/ws, then device:read), and the per-user open-tiles preference.
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
// A Dahua camera: no live-view capability, so the socket answers without any network.
db.insert(devices)
.values({ id: "cam-dahua", category: "camera", driverId: "dahua", config: { host: "192.0.2.1" } })
.run();
db.insert(devices).values({ id: "relay-1", category: "access", driverId: "stub-access", config: {} }).run();
});
afterEach(async () => {
await app.close();
close();
});
function shot(id: string, deviceId: string, capturedAt: string) {
db.insert(snapshots)
.values({ id, direction: "entry", deviceId, identity: "x", contentType: "image/jpeg", bytes: Buffer.from([1]), capturedAt })
.run();
}
describe("GET /api/cameras/:id/latest-snapshot", () => {
it("returns the camera's newest snapshot", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
shot("s1", "cam-dahua", "2026-11-17T10:00:00.000Z");
shot("s2", "cam-dahua", "2026-11-17T11:00:00.000Z");
shot("s3", "other", "2026-11-17T12:00:00.000Z");
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: auth.cookie } });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ id: "s2", direction: "entry" });
});
it("404s when the camera has none, 403s without session:read", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const admin = await login(app, "admin", "pw");
const none = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: admin.cookie } });
expect(none.statusCode).toBe(404);
await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] });
const dev = await login(app, "dev", "pw");
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: dev.cookie } });
expect(res.statusCode).toBe(403);
});
});
describe("WS /api/cameras/:id/live", () => {
const origin = "http://booth.local:8080";
it("rejects a cross-origin handshake", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
await expect(
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin: "http://evil.example", host: "booth.local:8080" } }),
).rejects.toThrow(/403/);
});
it("rejects a role without device:read", async () => {
await seedUser(db, { username: "cash", password: "pw", roleId: "cashier2", permissions: ["session:read"] });
const auth = await login(app, "cash", "pw");
await expect(
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
).rejects.toThrow(/403/);
});
it("404s a device that is not a camera", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
await expect(
app.injectWS("/api/cameras/relay-1/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
).rejects.toThrow(/404/);
});
it("tells the viewer when the camera has no live view", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
let resolveMsg!: (m: string) => void;
const first = new Promise<string>((r) => (resolveMsg = r));
const ws = await app.injectWS(
"/api/cameras/cam-dahua/live",
{ headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } },
{ onInit: (sock) => sock.once("message", (d) => resolveMsg(String(d))) },
);
const msg = await first;
expect(JSON.parse(msg)).toEqual({
kind: "status",
state: "unavailable",
reason: "live view not supported by this camera driver",
});
ws.terminate();
});
});
describe("PUT /api/auth/open-cameras", () => {
it("persists the open tiles and returns them on /me", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
const put = await app.inject({
method: "PUT",
url: "/api/auth/open-cameras",
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
payload: { openCameras: ["cam-b", "cam-a", "cam-b"] },
});
expect(put.statusCode).toBe(200);
expect(put.json()).toEqual({ openCameras: ["cam-b", "cam-a"] });
const me = await app.inject({ url: "/api/auth/me", headers: { cookie: auth.cookie } });
expect(me.json().openCameras).toEqual(["cam-b", "cam-a"]);
});
it("rejects a malformed list", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
const res = await app.inject({
method: "PUT",
url: "/api/auth/open-cameras",
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
payload: { openCameras: Array.from({ length: 9 }, (_, i) => `c${i}`) },
});
expect(res.statusCode).toBe(400);
});
});
+83
View File
@@ -0,0 +1,83 @@
import type { FastifyInstance } from "fastify";
import { desc, devices, eq, snapshots, type Db } from "@parking/db";
import { isLiveStreamDevice } from "@parking/devices";
import { requirePermission, roleHasPermissions } from "../auth.js";
import { buildCamera } from "../snapshot.js";
import type { CameraLiveHub, LiveResolver, LiveStatus } from "../camera-live.js";
import { authenticateWsHandshake } from "./ws.js";
// The booth's camera tiles (wiki/decisions/camera-live-view.md):
// - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest
// entry/exit evidence still this camera captured (metadata; bytes stay at
// /api/snapshots/:id). Evidence → `session:read`, like every snapshot read.
// - WS /api/cameras/:deviceId/live — live video while the camera sees a vehicle.
// Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie),
// then `device:read` (the footer's permission). Server → client: text JSON
// `{kind:"status", ...LiveStatus}` and binary messages, each one complete JPEG.
// Advisory viewing only: no route here writes anything.
/** Bytes a viewer's socket may hold unsent before frames are skipped for it. */
const MAX_BUFFERED_BYTES = 256 * 1024;
/** Resolve a camera id to its live capability, or the reason it has none. */
export function liveResolverFor(db: Db): LiveResolver {
return (deviceId) => {
const row = db.select().from(devices).where(eq(devices.id, deviceId)).get();
if (!row || row.category !== "camera") return "unknown camera";
if (!row.enabled) return "camera disabled";
const camera = buildCamera(row);
if (!camera) return "camera driver unavailable";
if (!isLiveStreamDevice(camera)) return "live view not supported by this camera driver";
return camera;
};
}
export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLiveHub): Promise<void> {
app.get<{ Params: { deviceId: string } }>(
"/api/cameras/:deviceId/latest-snapshot",
{ preHandler: requirePermission("session:read") },
async (req, reply) => {
// Uses snapshots_device_time_idx (migration 0033): one index seek, not a scan.
const row = db
.select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt })
.from(snapshots)
.where(eq(snapshots.deviceId, req.params.deviceId))
.orderBy(desc(snapshots.capturedAt))
.limit(1)
.get();
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
return row;
},
);
app.get<{ Params: { deviceId: string } }>(
"/api/cameras/:deviceId/live",
{
websocket: true,
preHandler: async (req) => {
const roleId = await authenticateWsHandshake(req);
if (!roleHasPermissions(roleId, ["device:read"])) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
const row = db.select({ category: devices.category }).from(devices).where(eq(devices.id, req.params.deviceId)).get();
if (!row || row.category !== "camera") {
throw Object.assign(new Error("unknown camera"), { statusCode: 404 });
}
},
},
(socket, req) => {
const open = () => socket.readyState === 1;
const unsubscribe = hub.subscribe(req.params.deviceId, {
sendFrame: (jpeg) => {
if (open()) socket.send(jpeg, { binary: true });
},
sendStatus: (status: LiveStatus) => {
if (open()) socket.send(JSON.stringify({ kind: "status", ...status }));
},
busy: () => !open() || socket.bufferedAmount > MAX_BUFFERED_BYTES,
});
socket.on("close", unsubscribe);
socket.on("error", unsubscribe);
},
);
}
+11 -1
View File
@@ -6,6 +6,7 @@ import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { hikvisionAlarmRoutes } from "./hikvision-alarm.js";
import type { AnprBridge } from "../anpr-entry.js";
import type { CameraActivity } from "../camera-activity.js";
import { seedUser, login } from "../test-helpers.js";
// Hikvision Alarm Server push ingress. Verifies the discovery endpoint: a vehicle-
@@ -235,6 +236,7 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
let rawDb: Db;
let rawClose: () => void;
let onVehicleDetected: ReturnType<typeof vi.fn>;
let cameraSaw: ReturnType<typeof vi.fn>;
beforeEach(async () => {
const t = createTestDb();
@@ -243,7 +245,9 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
onVehicleDetected = vi.fn(async () => {});
const bridge = { onVehicleDetected } as unknown as AnprBridge;
rawApp = Fastify();
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge);
cameraSaw = vi.fn();
const activity = { vehicleDetected: cameraSaw } as unknown as CameraActivity;
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge, activity);
await rawApp.ready();
rawDb.insert(devices).values({
id: CAM_ID,
@@ -275,10 +279,16 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
expect(onVehicleDetected).toHaveBeenCalledWith(CAM_ID);
});
it("marks THIS camera active for the booth camera tile", async () => {
await post(VEHICLE_XML);
expect(cameraSaw).toHaveBeenCalledWith(CAM_ID);
});
it("does NOT call the bridge for a human target", async () => {
const human = VEHICLE_XML.replace("vehicle", "human");
await post(human);
expect(onVehicleDetected).not.toHaveBeenCalled();
expect(cameraSaw).not.toHaveBeenCalled();
});
it("does NOT call the bridge on an `inactive` (leave) vehicle event", async () => {
@@ -6,6 +6,7 @@ import { requirePermission } from "../auth.js";
import { verifyDigest } from "../digest-auth.js";
import type { LaneStatus } from "../lane-status.js";
import type { AnprBridge } from "../anpr-entry.js";
import type { CameraActivity } from "../camera-activity.js";
// Hikvision "Alarm Server" event PUSH ingress. The newer-firmware cameras (Event →
// Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm
@@ -101,6 +102,7 @@ export async function hikvisionAlarmRoutes(
db: Db,
laneStatus?: LaneStatus,
anprBridge?: AnprBridge,
cameraActivity?: CameraActivity,
): Promise<void> {
// Accept ANY content-type as a raw Buffer (the camera may POST application/xml,
// multipart/form-data with a JPEG, or text). Fastify's default JSON parser would 415
@@ -213,6 +215,10 @@ export async function hikvisionAlarmRoutes(
if (laneStatus && isVehicleActive) {
laneStatus.vehicleDetected(deviceId);
}
// The same signal per camera: the booth's tile for THIS camera switches to live video.
if (cameraActivity && isVehicleActive) {
cameraActivity.vehicleDetected(deviceId);
}
// ANPR BRIDGE: on a vehicle detection, if this camera opts into ANPR (config.anpr),
// pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read
+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();
});
},
);