import type { FastifyReply, FastifyRequest } from "fastify"; import { eq, siteConfig, type Db } from "@parking/db"; import { effectiveModules, isModuleId, isTillId, parseEntitledModules, tillGuards, tillsFor, tillsOf, type ModuleId, type TillGuards, type TillId, } from "@parking/shared"; import { requireAuth, roleHasPermissions } from "./auth.js"; declare module "fastify" { interface FastifyRequest { /** Set by requireTill(): the till this request addresses (already authorized). */ till?: TillId; } } // Venue modules — the server side of "entitled ∩ activated" (registry + rules live in // @parking/shared; design in wiki/decisions/venue-modules.md). // // entitled MODULES_ENTITLED env (vendor, Komodo stack) — unset = everything. // activated site_config.modules_json (site admin, Setup → Site) — null = everything // entitled. // effective what requireModule() enforces and what /api/auth/me + /api/site-config // hand the SPA so it can hide nav. The web only HIDES; this file ENFORCES. // // Both inputs are re-read per request: one env read and one single-row SELECT on the // site_config singleton — cheap, and it means a change takes effect on the next request // with no cache to invalidate (the same reason the presence-bypass flags aren't cached). /** The modules this deployment is entitled to. Unknown ids in the env are ignored * (logged once at boot by registerModules). */ export function entitledModules(): ModuleId[] { return parseEntitledModules(process.env.MODULES_ENTITLED).entitled; } /** Parse the persisted activation list off a site_config row. null = never set. A * corrupt/unknown value is treated as "never set" rather than locking modules off. */ export function activatedModulesOf(row: { modulesJson?: string | null } | undefined): ModuleId[] | null { const raw = row?.modulesJson; if (raw == null) return null; try { const parsed: unknown = JSON.parse(raw); if (!Array.isArray(parsed)) return null; return parsed.filter(isModuleId); } catch { return null; } } /** The effective set for this site right now. */ export function effectiveModulesFor(db: Db): ModuleId[] { const row = db.select({ modulesJson: siteConfig.modulesJson }).from(siteConfig).where(eq(siteConfig.id, 1)).get(); return effectiveModules(entitledModules(), activatedModulesOf(row)); } /** The tills available at this site right now: the booth, plus each effective * money-taking module's own till (registry order). */ export function effectiveTillsFor(db: Db): TillId[] { return tillsOf(effectiveModulesFor(db)); } /** The tills a role may SEE (default) or WORK (`shift` / `cash`) here: the effective * tills whose module guard the role holds (each desk's money is guarded by that desk's * own permissions — venue-modules.md §"Permissions matrix"). */ export function tillsReadableBy(db: Db, roleId: string, kind: keyof TillGuards = "read"): TillId[] { return tillsFor(effectiveModulesFor(db), (p) => roleHasPermissions(roleId, [p]), kind); } /** preHandler factory for the shift/drawer routes: authenticate, parse the `till` * (query on GET, body on POST; absent = booth; 400 `bad_till` when unknown or its * module is off), then require the role to hold THAT TILL's guard for `kind` (403 * `till_forbidden`). The authorized till lands on `req.till`. The permission is thus * resolved from the till, never fixed: the booth checks `shift:read`/`shift:create`/ * `drawer:create`, the wash `carwash:read`/`carwash:cash`. */ export function requireTill(db: Db, kind: keyof TillGuards, from: "query" | "body") { return async (req: FastifyRequest, reply: FastifyReply): Promise => { await requireAuth(req, reply); const raw = from === "query" ? (req.query as { till?: unknown } | undefined)?.till : (req.body as { till?: unknown } | undefined)?.till; const till = parseTill(db, raw); if (!till) { await reply.code(400).send({ error: "unknown till", code: "bad_till" }); return reply; } if (!roleHasPermissions(req.user.roleId, [tillGuards(till)[kind]])) { await reply .code(403) .send({ error: `your role cannot ${kind === "read" ? "see" : "work"} the ${till} till`, code: "till_forbidden", till }); return reply; } req.till = till; }; } /** Parse a till from a query/body value. Absent/blank = the booth. Unknown, or a till * whose module is not effective here, → null (the caller answers 400). */ export function parseTill(db: Db, raw: unknown): TillId | null { if (raw == null || raw === "") return "booth"; if (!isTillId(raw)) return null; return effectiveTillsFor(db).includes(raw) ? raw : null; } /** preHandler: reject the call when `id` is not effective at this site. Compose it * BEFORE requirePermission in a preHandler array so a disabled module answers the * same way for every role — 403 with code "module_disabled" — and never reaches * the permission/CSRF path. */ export function requireModule(db: Db, id: ModuleId) { return async (_req: FastifyRequest, _reply: FastifyReply): Promise => { if (!effectiveModulesFor(db).includes(id)) { throw Object.assign(new Error(`module disabled: ${id}`), { statusCode: 403, code: "module_disabled" }); } }; }