feat(permissions): per-desk till guards, jobs in the role composer, permission-scoped live feed; role reassignment applies without re-login
Permissions matrix rethink (wiki/decisions/venue-modules.md §"Permissions matrix", open-questions #16) — the grid stays the enforcement layer: - Move 1: each desk's money is guarded by that desk's own permissions. Manifest tillGuards {read, shift, cash}: booth = shift:read / shift:create / drawer:create (unchanged), carwash = carwash:read / carwash:cash (new). Shift + drawer routes resolve the guard FROM THE TILL (requireTill); a wash role holds no shift:* and cannot touch the booth by construction. Replaces the session:read borrowing (tillPermission). /api/shift/tills lists the role's readable tills with canWork; history/movements without a till filter return the union of readable tills. - Move 2: jobs — manifest permission bundles (booth-operator, booth-supervisor, merchant, wash-operator) as one-click chips in Setup → Roles, with "mixes desks" and "partial job" lints (warnings, never blocks). - Move 3: the live WebSocket admits any watch permission (event/session/device read or a module's feedPermission) and filters every push per role; report:read is the reports screen only. Auth: the token's roleId is only a hint — refreshRole() after every jwtVerify resolves the user's CURRENT role (cached, bumped on role/user writes), so reassigning a user's role applies on the next request and a deleted user's session ends with 401. Tests: till guards + look-only role, feed rules, every job's permissions exist, role reassignment without re-login. 353/353. Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { Db } from "@parking/db";
|
||||
import type { LedgerEvent } from "@parking/shared";
|
||||
import { requireAuth, roleHasPermissions } from "../auth.js";
|
||||
import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared";
|
||||
import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js";
|
||||
import { effectiveModulesFor } from "../modules.js";
|
||||
import {
|
||||
deviceEvents,
|
||||
type LaneStatusEvent,
|
||||
@@ -45,9 +46,14 @@ import { getOccupancy } from "../occupancy.js";
|
||||
// headers on a WebSocket, so this path is unreachable from a browser and adds
|
||||
// no CSWSH surface; the Origin allowlist still applies to both paths.
|
||||
|
||||
/** 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;
|
||||
// WHO may watch, and WHAT they see (venue-modules.md §"Permissions matrix", move 3):
|
||||
// a role connects if it holds ANY watch permission — the core feed/occupancy/device
|
||||
// ones or an effective module's own (carwash:read) — and every pushed message is then
|
||||
// FILTERED per role: a ledger event needs feedPermissionFor(type) (the owning module's,
|
||||
// else event:read); occupancy + the plate backfill need session:read; device / printer /
|
||||
// lane / radar need device:read. `report:read` is the REPORTS screen, not the socket: the
|
||||
// wash desk gets a live queue without the booth's ledger, the booth a feed without reports.
|
||||
type Viewer = { has: (p: Permission) => boolean };
|
||||
|
||||
/** Handshake header carrying a desktop WS ticket (see file header). */
|
||||
const WS_TICKET_HEADER = "x-ws-ticket";
|
||||
@@ -108,18 +114,25 @@ function isAllowedOrigin(origin: string | undefined, host: string | undefined):
|
||||
type OutMsg =
|
||||
| {
|
||||
kind: "hello";
|
||||
occupancy: ReturnType<typeof getOccupancy>;
|
||||
occupancy: ReturnType<typeof getOccupancy> | null;
|
||||
devices: unknown;
|
||||
lanes: LaneStatusEvent;
|
||||
radar: LanePresenceEvent;
|
||||
lanes: LaneStatusEvent | null;
|
||||
radar: LanePresenceEvent | null;
|
||||
}
|
||||
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> }
|
||||
| { 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: "plate-recognized"; plate: PlateRecognizedEvent };
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
/** The role the WS preHandler authenticated (ticket or cookie path) — for the handler's filter. */
|
||||
wsRoleId?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export async function wsRoutes(
|
||||
app: FastifyInstance,
|
||||
db: Db,
|
||||
@@ -161,14 +174,18 @@ export async function wsRoutes(
|
||||
if (!req.user) {
|
||||
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||
}
|
||||
roleId = req.user.roleId;
|
||||
}
|
||||
if (!roleHasPermissions(roleId, [WATCH_PERMISSION])) {
|
||||
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||
roleId = currentRoleId(req.user.sub) ?? "";
|
||||
}
|
||||
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
|
||||
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
||||
req.wsRoleId = roleId;
|
||||
},
|
||||
},
|
||||
(socket) => {
|
||||
(socket, req) => {
|
||||
const roleId = req.wsRoleId ?? req.user?.roleId ?? "";
|
||||
const viewer: Viewer = { has: (p) => roleHasPermissions(roleId, [p]) };
|
||||
const seesOccupancy = viewer.has("session:read");
|
||||
const seesDevices = viewer.has("device:read");
|
||||
const send = (msg: OutMsg) => {
|
||||
// readyState 1 = OPEN; never throw out of an event-bus callback.
|
||||
if (socket.readyState === 1) {
|
||||
@@ -182,40 +199,43 @@ export async function wsRoutes(
|
||||
|
||||
// Initial snapshot so the client renders immediately, before any event:
|
||||
// occupancy AND the current device-status set (for the footer).
|
||||
// Each part of the snapshot only for a role that may see it (null otherwise).
|
||||
send({
|
||||
kind: "hello",
|
||||
occupancy: getOccupancy(db),
|
||||
devices: deviceMonitor.snapshot(),
|
||||
lanes: laneStatus.snapshot(),
|
||||
radar: lanePresence.snapshot(),
|
||||
occupancy: seesOccupancy ? getOccupancy(db) : null,
|
||||
devices: seesDevices ? deviceMonitor.snapshot() : null,
|
||||
lanes: seesDevices ? laneStatus.snapshot() : null,
|
||||
radar: seesDevices ? lanePresence.snapshot() : null,
|
||||
});
|
||||
|
||||
// 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) => {
|
||||
// Per-role filter: the event type's feed permission (module's own, else event:read).
|
||||
if (!viewer.has(feedPermissionFor((event as { type: LedgerEvent["type"] }).type))) return;
|
||||
// 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) });
|
||||
send({ kind: "ledger", event: enriched, occupancy: seesOccupancy ? getOccupancy(db) : null });
|
||||
});
|
||||
const offPrinter = deviceEvents.onPrinterStatus((event) => {
|
||||
send({ kind: "printer-status", event });
|
||||
if (seesDevices) 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 });
|
||||
if (seesDevices) 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 });
|
||||
if (seesDevices) 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 });
|
||||
if (seesDevices) 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 });
|
||||
if (seesOccupancy) send({ kind: "plate-recognized", plate });
|
||||
});
|
||||
|
||||
socket.on("close", () => {
|
||||
|
||||
Reference in New Issue
Block a user