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
+52
View File
@@ -0,0 +1,52 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FastifyBaseLogger } from "fastify";
import { CameraActivity } from "./camera-activity.js";
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
// Per-camera activity drives the booth tiles' snapshot→live switch: one "active" edge
// per run of pushes, re-armed by each push, one "idle" edge TTL after the last push.
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() } as unknown as FastifyBaseLogger;
let seen: CameraActivityEvent[];
let off: () => void;
beforeEach(() => {
vi.useFakeTimers();
seen = [];
off = deviceEvents.onCameraActivity((e) => seen.push(e));
});
afterEach(() => {
off();
vi.useRealTimers();
});
describe("CameraActivity", () => {
it("emits active once, re-arms on each push, idles after the TTL", () => {
const a = new CameraActivity(logger, 30_000);
a.vehicleDetected("cam1");
vi.advanceTimersByTime(20_000);
a.vehicleDetected("cam1"); // re-arm
expect(seen).toEqual([{ deviceId: "cam1", active: true }]);
expect(a.snapshot()).toEqual(["cam1"]);
vi.advanceTimersByTime(29_000);
expect(seen).toHaveLength(1);
vi.advanceTimersByTime(1_000);
expect(seen).toEqual([
{ deviceId: "cam1", active: true },
{ deviceId: "cam1", active: false },
]);
expect(a.snapshot()).toEqual([]);
});
it("tracks cameras independently", () => {
const a = new CameraActivity(logger, 1_000);
a.vehicleDetected("entry");
vi.advanceTimersByTime(600);
a.vehicleDetected("exit");
vi.advanceTimersByTime(400);
expect(a.snapshot()).toEqual(["exit"]);
a.stop();
vi.advanceTimersByTime(5_000);
expect(seen.filter((e) => !e.active)).toEqual([{ deviceId: "entry", active: false }]);
});
});
+50
View File
@@ -0,0 +1,50 @@
import type { FastifyBaseLogger } from "fastify";
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
import { busyTtlMs } from "./lane-status.js";
// Per-CAMERA "a vehicle is in view" state, for the booth camera tiles: a tile shows the
// camera's latest snapshot and switches to live video while its camera is active. Same
// signal and TTL as LaneStatus (vehicle `active` pushes, no leave event, 30 s after the
// last push) but keyed by camera, not lane: on a shared lane (park-lab: an entry and an
// exit camera on one physical lane) only the camera that saw the car goes live.
// ADVISORY ONLY — it gates nothing. See wiki/decisions/camera-live-view.md.
export type { CameraActivityEvent };
export class CameraActivity {
readonly #logger: FastifyBaseLogger;
readonly #ttlMs: number;
readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
constructor(logger: FastifyBaseLogger, ttlMs = busyTtlMs()) {
this.#logger = logger;
this.#ttlMs = ttlMs;
}
/** Camera ids currently active (for the WS hello). */
snapshot(): string[] {
return [...this.#timers.keys()];
}
/** A vehicle push from `deviceId`: mark it active and (re)arm its clear. */
vehicleDetected(deviceId: string): void {
const existing = this.#timers.get(deviceId);
if (existing) clearTimeout(existing);
const timer = setTimeout(() => {
this.#timers.delete(deviceId);
this.#logger.debug(`camera-activity: ${deviceId} -> idle`);
deviceEvents.emitCameraActivity({ deviceId, active: false });
}, this.#ttlMs);
timer.unref?.();
this.#timers.set(deviceId, timer);
if (!existing) {
this.#logger.debug(`camera-activity: ${deviceId} -> active`);
deviceEvents.emitCameraActivity({ deviceId, active: true });
}
}
stop(): void {
for (const t of this.#timers.values()) clearTimeout(t);
this.#timers.clear();
}
}
+149
View File
@@ -0,0 +1,149 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FastifyBaseLogger } from "fastify";
import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices";
import { CameraLiveHub, type LiveStatus, type LiveViewer } from "./camera-live.js";
// The hub's contract: one upstream per camera however many viewers, latest-frame-only
// delivery (a busy viewer misses frames, never queues them), teardown after the last
// viewer leaves (with a linger), reconnect with backoff while viewers remain, and a
// non-retryable failure (codec) reported as "unavailable".
const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as unknown as FastifyBaseLogger;
class FakeSource implements LiveVideoSource {
frameCbs: Array<(f: Buffer) => void> = [];
endCbs: Array<(e?: Error) => void> = [];
stopped = false;
constructor(private readonly fail?: Error) {}
async start() {
if (this.fail) {
queueMicrotask(() => this.end(this.fail));
throw this.fail;
}
}
stop() {
this.stopped = true;
this.end();
}
onFrame(cb: (f: Buffer) => void) {
this.frameCbs.push(cb);
}
onEnd(cb: (e?: Error) => void) {
this.endCbs.push(cb);
}
frame(b = Buffer.from([0xff, 0xd8])) {
for (const cb of this.frameCbs) cb(b);
}
end(err?: Error) {
for (const cb of this.endCbs.splice(0)) cb(err);
}
}
function viewer(busy = false) {
const frames: Buffer[] = [];
const statuses: LiveStatus[] = [];
const v: LiveViewer & { frames: Buffer[]; statuses: LiveStatus[]; isBusy: boolean } = {
frames,
statuses,
isBusy: busy,
sendFrame: (f) => frames.push(f),
sendStatus: (s) => statuses.push(s),
busy: () => v.isBusy,
};
return v;
}
let sources: FakeSource[];
let nextFail: Error | undefined;
const device: LiveStreamDevice = {
openLiveStream: () => {
const s = new FakeSource(nextFail);
sources.push(s);
return s;
},
};
beforeEach(() => {
vi.useFakeTimers();
sources = [];
nextFail = undefined;
});
afterEach(() => vi.useRealTimers());
describe("CameraLiveHub", () => {
it("shares one upstream between viewers and tears it down after the last leaves", async () => {
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000, maxFps: 1000 });
const a = viewer();
const b = viewer();
const offA = hub.subscribe("cam1", a);
const offB = hub.subscribe("cam1", b);
expect(sources).toHaveLength(1);
sources[0]!.frame();
expect(a.frames).toHaveLength(1);
expect(b.frames).toHaveLength(1);
expect(a.statuses.at(-1)).toEqual({ state: "live" });
offA();
offB();
expect(sources[0]!.stopped).toBe(false); // lingering
vi.advanceTimersByTime(1000);
expect(sources[0]!.stopped).toBe(true);
expect(hub.upstreamCount).toBe(0);
});
it("a viewer returning within the linger reuses the session", () => {
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000 });
const off = hub.subscribe("cam1", viewer());
off();
vi.advanceTimersByTime(500);
hub.subscribe("cam1", viewer());
vi.advanceTimersByTime(5000);
expect(sources).toHaveLength(1);
expect(sources[0]!.stopped).toBe(false);
});
it("skips frames for a busy viewer and caps the frame rate", () => {
const hub = new CameraLiveHub(() => device, logger, { maxFps: 10 });
const slow = viewer(true);
const fast = viewer();
hub.subscribe("cam1", slow);
hub.subscribe("cam1", fast);
for (let i = 0; i < 5; i++) sources[0]!.frame(); // same instant: only the first passes the cap
expect(fast.frames).toHaveLength(1);
expect(slow.frames).toHaveLength(0);
vi.advanceTimersByTime(100);
slow.isBusy = false;
sources[0]!.frame();
expect(fast.frames).toHaveLength(2);
expect(slow.frames).toHaveLength(1);
});
it("reconnects with backoff while viewers remain", async () => {
const hub = new CameraLiveHub(() => device, logger);
const v = viewer();
hub.subscribe("cam1", v);
sources[0]!.end(new Error("RTSP connection closed"));
expect(v.statuses.at(-1)).toEqual({ state: "retrying", reason: "RTSP connection closed" });
vi.advanceTimersByTime(1000);
expect(sources).toHaveLength(2);
});
it("reports a non-retryable failure as unavailable", async () => {
const hub = new CameraLiveHub(() => device, logger, { unavailableRetryMs: 60_000 });
nextFail = Object.assign(new Error("camera stream is H264, not MJPEG"), { retryable: false });
const v = viewer();
hub.subscribe("cam1", v);
await vi.advanceTimersByTimeAsync(0);
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "camera stream is H264, not MJPEG" });
vi.advanceTimersByTime(59_000);
expect(sources).toHaveLength(1);
});
it("a camera without live support is unavailable and opens nothing", () => {
const hub = new CameraLiveHub(() => "live view not supported by this camera driver", logger);
const v = viewer();
hub.subscribe("cam1", v);
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "live view not supported by this camera driver" });
expect(hub.upstreamCount).toBe(0);
});
});
+199
View File
@@ -0,0 +1,199 @@
import type { FastifyBaseLogger } from "fastify";
import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices";
// Live camera video for the booth's camera tiles. ONE upstream session per camera,
// shared by every viewer (booth tab, desktop shell) and torn down a few seconds after
// the last viewer leaves — never one camera session per tab (a camera has few stream
// slots, and the ANPR loop pulls stills from the same unit).
//
// Frames are complete JPEGs (the driver reassembles RTP/JPEG; nothing is decoded here).
// Delivery is LATEST-FRAME-ONLY: a viewer whose socket still holds unsent bytes simply
// misses frames, so a slow client can never grow server memory, and a per-viewer frame
// cap keeps the desktop shell's IPC light. Advisory viewing only: nothing here touches
// the ledger, a gate or a barrier. See wiki/decisions/camera-live-view.md.
export type LiveStatus =
| { state: "connecting" }
| { state: "live" }
| { state: "retrying"; reason: string }
| { state: "unavailable"; reason: string };
export interface LiveViewer {
sendFrame(jpeg: Buffer): void;
sendStatus(status: LiveStatus): void;
/** True while this viewer's transport still has unsent bytes: skip the frame. */
busy(): boolean;
}
/** Resolve a camera id to its live-stream capability, or a reason it has none. */
export type LiveResolver = (deviceId: string) => LiveStreamDevice | string;
export interface CameraLiveOptions {
/** Keep the upstream this long after the last viewer leaves (re-render churn). */
lingerMs?: number;
/** Per-viewer frame cap. The cameras send 12.5–20 fps; 10 is plenty to watch a car. */
maxFps?: number;
/** Backoff ceiling for reconnects while viewers are present. */
maxRetryMs?: number;
/** Retry delay after a non-retryable failure (codec/driver), in case it is fixed. */
unavailableRetryMs?: number;
}
interface Upstream {
readonly deviceId: string;
readonly viewers: Map<LiveViewer, { lastSent: number }>;
source: LiveVideoSource | null;
status: LiveStatus;
attempt: number;
linger: ReturnType<typeof setTimeout> | null;
retry: ReturnType<typeof setTimeout> | null;
}
export function liveMaxFps(): number {
const raw = Number(process.env.CAMERA_LIVE_MAX_FPS ?? 10);
return Number.isFinite(raw) && raw > 0 ? raw : 10;
}
export class CameraLiveHub {
readonly #resolve: LiveResolver;
readonly #logger: FastifyBaseLogger;
readonly #lingerMs: number;
readonly #minFrameGapMs: number;
readonly #maxRetryMs: number;
readonly #unavailableRetryMs: number;
readonly #upstreams = new Map<string, Upstream>();
constructor(resolve: LiveResolver, logger: FastifyBaseLogger, opts: CameraLiveOptions = {}) {
this.#resolve = resolve;
this.#logger = logger;
this.#lingerMs = opts.lingerMs ?? 5000;
this.#minFrameGapMs = 1000 / (opts.maxFps ?? liveMaxFps());
this.#maxRetryMs = opts.maxRetryMs ?? 30_000;
this.#unavailableRetryMs = opts.unavailableRetryMs ?? 60_000;
}
/** Number of open upstream sessions (diagnostic / tests). */
get upstreamCount(): number {
return [...this.#upstreams.values()].filter((u) => u.source !== null).length;
}
subscribe(deviceId: string, viewer: LiveViewer): () => void {
let up = this.#upstreams.get(deviceId);
if (!up) {
up = { deviceId, viewers: new Map(), source: null, status: { state: "connecting" }, attempt: 0, linger: null, retry: null };
this.#upstreams.set(deviceId, up);
}
if (up.linger) {
clearTimeout(up.linger);
up.linger = null;
}
if (!up.source && !up.retry) {
up.status = { state: "connecting" };
this.#start(up); // may settle the status at once (e.g. "unavailable")
}
// Added after the start so the newcomer gets the CURRENT status exactly once.
up.viewers.set(viewer, { lastSent: 0 });
viewer.sendStatus(up.status);
const u = up;
let done = false;
return () => {
if (done) return;
done = true;
u.viewers.delete(viewer);
if (u.viewers.size === 0 && !u.linger) {
u.linger = setTimeout(() => this.#teardown(u), this.#lingerMs);
u.linger.unref?.();
}
};
}
stopAll(): void {
for (const up of [...this.#upstreams.values()]) this.#teardown(up);
}
#start(up: Upstream): void {
const dev = this.#resolve(up.deviceId);
if (typeof dev === "string") {
this.#setStatus(up, { state: "unavailable", reason: dev });
return; // not a live-capable camera: nothing to retry
}
let source: LiveVideoSource;
try {
source = dev.openLiveStream();
} catch (err) {
// A driver that cannot even build a session (bad config): report it; the next
// subscribe tries again.
this.#setStatus(up, { state: "unavailable", reason: (err as Error).message });
return;
}
up.source = source;
let gotFrame = false;
source.onFrame((jpeg) => {
if (up.source !== source) return;
if (!gotFrame) {
gotFrame = true;
up.attempt = 0;
this.#setStatus(up, { state: "live" });
}
const now = Date.now();
for (const [viewer, st] of up.viewers) {
if (now - st.lastSent < this.#minFrameGapMs || viewer.busy()) continue;
st.lastSent = now;
try {
viewer.sendFrame(jpeg);
} catch {
/* a broken viewer is removed by its own close handler */
}
}
});
source.onEnd((err) => this.#onEnded(up, source, err));
source.start().catch(() => undefined); // failures arrive through onEnd
}
#onEnded(up: Upstream, source: LiveVideoSource | null, err?: Error): void {
if (source && up.source !== source) return; // a stale session
up.source = null;
if (up.viewers.size === 0 || !this.#upstreams.has(up.deviceId)) return;
const reason = err?.message ?? "stream ended";
const retryable = (err as { retryable?: boolean } | undefined)?.retryable !== false;
let delay: number;
if (retryable) {
delay = Math.min(this.#maxRetryMs, 1000 * 2 ** up.attempt);
up.attempt++;
this.#setStatus(up, { state: "retrying", reason });
} else {
delay = this.#unavailableRetryMs;
this.#setStatus(up, { state: "unavailable", reason });
}
// Once, not per retry: a camera that is down for hours must not flood the log.
if (up.attempt <= 1) this.#logger.warn(`camera-live ${up.deviceId}: ${reason}`);
up.retry = setTimeout(() => {
up.retry = null;
if (up.viewers.size > 0 && !up.source) this.#start(up);
}, delay);
up.retry.unref?.();
}
#setStatus(up: Upstream, status: LiveStatus): void {
up.status = status;
for (const viewer of up.viewers.keys()) {
try {
viewer.sendStatus(status);
} catch {
/* ignore */
}
}
}
#teardown(up: Upstream): void {
if (up.linger) clearTimeout(up.linger);
if (up.retry) clearTimeout(up.retry);
up.linger = null;
up.retry = null;
const source = up.source;
up.source = null;
this.#upstreams.delete(up.deviceId);
source?.stop();
}
}
+16
View File
@@ -89,6 +89,13 @@ export interface DeviceStatusEvent {
* gate (it never blocks a ticket or opens a barrier). "busy" is set by a vehicle
* `active` event; it auto-clears to "free" after a timeout (this camera class sends
* no leave/`inactive` signal — see wiki/entities/lpr-camera.md). */
/** A camera started/stopped seeing a vehicle (per camera, TTL-cleared). Drives the
* booth camera tiles' snapshot→live switch. Advisory only. See camera-activity.ts. */
export interface CameraActivityEvent {
readonly deviceId: string;
readonly active: boolean;
}
export interface LaneStatusEvent {
readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity)
readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity)
@@ -193,6 +200,15 @@ class DeviceEventBus extends EventEmitter {
return () => this.off("lane-status", cb);
}
/** Emitted when a camera's vehicle activity flips (camera-activity.ts). Advisory. */
emitCameraActivity(event: CameraActivityEvent): void {
this.emit("camera-activity", event);
}
onCameraActivity(cb: (event: CameraActivityEvent) => void): () => void {
this.on("camera-activity", cb);
return () => this.off("camera-activity", cb);
}
/** Emitted whenever a lane's RADAR presence CHANGES (a presence input shorted/cleared
* at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */
emitLanePresence(event: LanePresenceEvent): void {
+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();
});
},
);
+14 -2
View File
@@ -47,6 +47,9 @@ import { entryRoutes } from "./routes/entry.js";
import { siteRoutes } from "./routes/site.js";
import { registerModules } from "./modules/index.js";
import { snapshotRoutes } from "./routes/snapshots.js";
import { cameraRoutes, liveResolverFor } from "./routes/cameras.js";
import { CameraActivity } from "./camera-activity.js";
import { CameraLiveHub } from "./camera-live.js";
import { tariffRoutes } from "./routes/tariffs.js";
import { printerRoutes } from "./routes/printers.js";
import { setupRoutes } from "./routes/setup.js";
@@ -176,6 +179,14 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
const laneStatus = new LaneStatus(db, app.log);
app.addHook("onClose", async () => laneStatus.stop());
// Per-CAMERA vehicle activity (same pushes, keyed by camera) + the live-video hub for
// the booth camera tiles: a tile goes live while its camera sees a vehicle. Advisory
// viewing only. See camera-live.ts, wiki/decisions/camera-live-view.md.
const cameraActivity = new CameraActivity(app.log);
app.addHook("onClose", async () => cameraActivity.stop());
const cameraLive = new CameraLiveHub(liveResolverFor(db), app.log);
app.addHook("onClose", async () => cameraLive.stopAll());
// Per-lane RADAR presence (presence-input edges → barrier-light blink). Mirrors the
// physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI.
const lanePresence = new LanePresence(db, app.log);
@@ -216,10 +227,11 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// Live booth feed: server-pushed ledger + occupancy + printer-status over a
// single authenticated WebSocket (/api/ws). See routes/ws.ts.
await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence);
await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence, cameraActivity);
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
await snapshotRoutes(app, db);
await cameraRoutes(app, db, cameraLive);
// Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen.
// Subscribes to the SAME input bus as the telemetry writer below; the two are
@@ -270,7 +282,7 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// each detected target (vehicle). Source-IP guarded + optional Digest; records the raw
// payload as a `kind:"alarm"` device_event, drives lane busy/free, AND hands a vehicle
// detection to the ANPR bridge above. See routes/hikvision-alarm.ts.
await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge);
await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge, cameraActivity);
// Credential capture ("enroll a card"): lets the operator present an RFID card to a
// CHOSEN reader to populate a subscription credential, without blocking the other