feat(modules): venue-module registry — entitled ∩ activated, requireModule, Setup panel

Groundwork for the Car Wash pilot (wiki/decisions/venue-modules.md, build-order
steps 1 + 3). No Car Wash code yet; validation is the first module behind the
seam, unchanged in behaviour.

- @parking/shared: MODULE_IDS, ModuleManifest, MODULES (parking required;
  validation dependsOn parking), parseEntitledModules / resolveModuleActivation
  / effectiveModules as pure functions.
- DB: site_config.modules_json (migration 0026, hand-written + journal;
  additive, nullable = everything entitled).
- Server: modules.ts (entitledModules from MODULES_ENTITLED env, activated
  from site_config, effective set, requireModule preHandler → 403
  module_disabled); modules/index.ts registers folder-based modules by
  iterating the registry (modules/validation); site-config GET exposes
  modules/modulesEntitled/modulesActivated, PUT takes the full desired set,
  enforces entitlement + dependency rules (400 with reason) and signs one
  config_change per module that actually flips; /api/auth/me carries the
  effective set; validation routes guarded requireModule → requirePermission.
- Web: lib/modules.ts + modules/{index,validation}; router.tsx spreads
  WEB_MODULES into nav + route tree (validate route no longer named there);
  Setup → Site "Modules" panel (required shown disabled, dependencies as
  hints, server refusal shown verbatim); validation sections + programs fetch
  gated on the module; App invalidates the router whenever the session
  changes (route-context consumers only re-read on navigation — the nav was
  stale after a flip, and after every other setUser too).
- Lavazh validation station retired (STATIONS = ["bar"]; rows untouched).
- Deploy: MODULES_ENTITLED=parking,validation explicit in both booth stacks;
  documented in .env.example.
- Tests: modules.test.ts (7); suite 329/329; web build clean; Playwright
  round-trip on /setup/site verified live.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
This commit is contained in:
2026-09-05 11:04:39 +02:00
parent db9c3e0e31
commit 23d6379be8
27 changed files with 848 additions and 57 deletions
+166
View File
@@ -0,0 +1,166 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { type Db } from "@parking/db";
import type { FastifyInstance } from "fastify";
import { buildServer } from "./server.js";
import { seedUser, login } from "./test-helpers.js";
// Venue modules — entitled ∩ activated, enforced server-side (wiki/decisions/
// venue-modules.md). Boots the real app over an in-memory DB and drives it with
// app.inject, like routes.test.ts.
let db: Db;
let close: () => void;
let app: FastifyInstance;
const savedEnv = process.env.MODULES_ENTITLED;
async function boot(): Promise<void> {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
}
beforeEach(async () => {
delete process.env.MODULES_ENTITLED;
await boot();
});
afterEach(async () => {
await app.close();
close();
if (savedEnv === undefined) delete process.env.MODULES_ENTITLED;
else process.env.MODULES_ENTITLED = savedEnv;
});
async function admin() {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
return login(app, username, password);
}
describe("defaults (no env, nothing activated)", () => {
it("every registered module is entitled, activated and effective; /me carries the set", async () => {
const { cookie } = await admin();
const cfg = await app.inject({ method: "GET", url: "/api/site-config", headers: { cookie } });
expect(cfg.statusCode).toBe(200);
const body = cfg.json();
expect(body.modulesEntitled).toEqual(["parking", "validation"]);
expect(body.modulesActivated).toEqual(["parking", "validation"]);
expect(body.modules).toEqual(["parking", "validation"]);
const me = await app.inject({ method: "GET", url: "/api/auth/me", headers: { cookie } });
expect(me.json().modules).toEqual(["parking", "validation"]);
// A module route answers normally while the module is on.
const programs = await app.inject({ method: "GET", url: "/api/validation/programs", headers: { cookie } });
expect(programs.statusCode).toBe(200);
});
});
describe("activation (site admin)", () => {
it("deactivating validation 403s its routes with module_disabled, signs a config_change, and is reversible", async () => {
const { cookie, csrf } = await admin();
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: ["parking"] },
});
expect(put.statusCode).toBe(200);
expect(put.json().modules).toEqual(["parking"]);
expect(put.json().modulesActivated).toEqual(["parking"]);
const off = await app.inject({ method: "GET", url: "/api/validation/programs", headers: { cookie } });
expect(off.statusCode).toBe(403);
expect(off.json().code).toBe("module_disabled");
const me = await app.inject({ method: "GET", url: "/api/auth/me", headers: { cookie } });
expect(me.json().modules).toEqual(["parking"]);
// The flip is on the signed ledger, attributed.
const events = await app.inject({ method: "GET", url: "/api/events?limit=50", headers: { cookie } });
expect(events.statusCode).toBe(200);
const list = (events.json().events ?? events.json()) as Array<{ type: string; payload: Record<string, unknown> }>;
const flip = list.find((e) => e.type === "config_change" && e.payload?.setting === "modules.validation");
expect(flip).toBeTruthy();
expect(flip!.payload).toMatchObject({ value: false, prev: true, operator: "boss" });
// Nothing was deleted: re-enable and the route is back.
const back = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: ["parking", "validation"] },
});
expect(back.json().modules).toEqual(["parking", "validation"]);
const on = await app.inject({ method: "GET", url: "/api/validation/programs", headers: { cookie } });
expect(on.statusCode).toBe(200);
});
it("required modules cannot be deactivated (parking is always included)", async () => {
const { cookie, csrf } = await admin();
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: [] },
});
expect(put.statusCode).toBe(200);
expect(put.json().modules).toEqual(["parking"]);
});
it("rejects unknown ids with 400", async () => {
const { cookie, csrf } = await admin();
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: ["parking", "carwash"] },
});
expect(put.statusCode).toBe(400);
});
it("a no-op resave signs nothing", async () => {
const { cookie, csrf } = await admin();
const before = await app.inject({ method: "GET", url: "/api/events?limit=50", headers: { cookie } });
const countBefore = ((before.json().events ?? before.json()) as unknown[]).length;
await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: ["parking", "validation"] },
});
const after = await app.inject({ method: "GET", url: "/api/events?limit=50", headers: { cookie } });
expect(((after.json().events ?? after.json()) as unknown[]).length).toBe(countBefore);
});
});
describe("entitlement (vendor env)", () => {
it("MODULES_ENTITLED=parking: validation is neither offered nor activatable, and its routes 403", async () => {
await app.close();
close();
process.env.MODULES_ENTITLED = "parking";
await boot();
const { cookie, csrf } = await admin();
const cfg = await app.inject({ method: "GET", url: "/api/site-config", headers: { cookie } });
expect(cfg.json().modulesEntitled).toEqual(["parking"]);
expect(cfg.json().modules).toEqual(["parking"]);
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { modules: ["parking", "validation"] },
});
expect(put.statusCode).toBe(400);
expect(put.json().error).toMatch(/not entitled/);
const off = await app.inject({ method: "GET", url: "/api/validation/programs", headers: { cookie } });
expect(off.statusCode).toBe(403);
});
it("required modules are entitled even when the env omits them; unknown ids are ignored", async () => {
await app.close();
close();
process.env.MODULES_ENTITLED = "validation,bogus";
await boot();
const { cookie } = await admin();
const cfg = await app.inject({ method: "GET", url: "/api/site-config", headers: { cookie } });
expect(cfg.json().modulesEntitled).toEqual(["parking", "validation"]);
});
});
+59
View File
@@ -0,0 +1,59 @@
import type { FastifyReply, FastifyRequest } from "fastify";
import { eq, siteConfig, type Db } from "@parking/db";
import {
effectiveModules,
isModuleId,
parseEntitledModules,
type ModuleId,
} from "@parking/shared";
// 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));
}
/** 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<void> => {
if (!effectiveModulesFor(db).includes(id)) {
throw Object.assign(new Error(`module disabled: ${id}`), { statusCode: 403, code: "module_disabled" });
}
};
}
+51
View File
@@ -0,0 +1,51 @@
import type { FastifyInstance } from "fastify";
import type { Db } from "@parking/db";
import { MODULES, parseEntitledModules, type ModuleId } from "@parking/shared";
import type { EventLog } from "../event-log.js";
import { effectiveModulesFor } from "../modules.js";
import { validationModule } from "./validation/index.js";
// The server-side module registry. A module's routes live in its own folder
// (apps/server/src/modules/<id>/index.ts) and are registered by iterating
// @parking/shared's MODULES — so adding a module is one manifest entry + one folder +
// one line in SERVER_MODULES below, with nothing else in the core touched
// (wiki/decisions/venue-modules.md, "A module = a manifest + three folders").
//
// `parking` is registered in the manifest but has NO folder yet: its routes are still
// the flat list in server.ts. That is deliberate — the seam is drawn, the code moves
// across it subsystem by subsystem as each is touched, not in one big move.
export interface ServerModuleDeps {
db: Db;
eventLog: EventLog;
}
export interface ServerModule {
id: ModuleId;
register(app: FastifyInstance, deps: ServerModuleDeps): Promise<void>;
}
const SERVER_MODULES: Partial<Record<ModuleId, ServerModule>> = {
validation: validationModule,
};
/** Register every folder-based module in registry order, then log what this site
* is entitled to / has effective, so a "why is X missing" question is answerable
* from the container log alone. */
export async function registerModules(app: FastifyInstance, deps: ServerModuleDeps): Promise<void> {
for (const manifest of MODULES) {
const impl = SERVER_MODULES[manifest.id];
if (impl) {
if (impl.id !== manifest.id) throw new Error(`module registry mismatch: ${impl.id} registered under ${manifest.id}`);
await impl.register(app, deps);
}
}
const { entitled, unknown } = parseEntitledModules(process.env.MODULES_ENTITLED);
if (unknown.length > 0) {
app.log.warn({ unknown }, "MODULES_ENTITLED names unknown module ids — ignored");
}
app.log.info(
{ entitled, effective: effectiveModulesFor(deps.db) },
"venue modules (entitled = MODULES_ENTITLED env; effective = entitled ∩ site activation)",
);
}
@@ -0,0 +1,13 @@
import { validationRoutes } from "../../routes/validations.js";
import type { ServerModule } from "../index.js";
// Merchant-scan ticket validation as a venue module. Kept for the Bar until a Bar
// module absorbs it (wiki/decisions/venue-modules.md, decision 1). The routes
// themselves still live in routes/validations.ts (unchanged location, now guarded by
// requireModule("validation")); this folder is the registry hook.
export const validationModule: ServerModule = {
id: "validation",
async register(app, { db, eventLog }) {
await validationRoutes(app, db, eventLog);
},
};
+4
View File
@@ -1,6 +1,7 @@
import bcrypt from "bcrypt";
import type { FastifyInstance } from "fastify";
import { eq, roles, users, type Db } from "@parking/db";
import { effectiveModulesFor } from "../modules.js";
import {
clearAuthCookies,
newCsrfToken,
@@ -107,6 +108,9 @@ function sessionView(
fontScale: user.fontScale,
fullName: user.fullName ?? null,
email: user.email ?? null,
// Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes
// on first paint. The server still enforces via requireModule — this is display.
modules: effectiveModulesFor(db),
...(csrf ? { csrfToken: csrf } : {}),
};
}
+58
View File
@@ -1,7 +1,9 @@
import type { FastifyInstance } from "fastify";
import { eq, siteConfig, type Db } from "@parking/db";
import { MODULES, effectiveModules, isModuleId, resolveModuleActivation, type ModuleId } from "@parking/shared";
import { requirePermission } from "../auth.js";
import type { EventLog } from "../event-log.js";
import { activatedModulesOf, entitledModules } from "../modules.js";
import { getOccupancy } from "../occupancy.js";
// Site config (capacity) + live occupancy. Occupancy is a fold over the signed
@@ -36,6 +38,10 @@ interface SiteConfigBody extends Partial<Record<TextField, string | null>> {
/** Master switch for the ANPR subscriber-entry bridge (auto-open on a subscriber's
* plate read). OFF → subscribers fall back to card/QR; advisory ANPR still records. */
anprEntryEnabled?: boolean;
/** Venue modules to ACTIVATE (full desired set). Validated against the entitlement
* and the registry's dependency rules; required modules are always included. Each
* module that actually flips signs a config_change. See wiki/decisions/venue-modules.md. */
modules?: unknown;
}
/** Shape returned by GET/PUT: capacity + the booth flag + the subscription default
@@ -48,6 +54,13 @@ type SiteConfig = {
anprEntryEnabled: boolean;
bypassPresenceRadar: boolean;
bypassPresenceCamera: boolean;
/** Effective venue modules = entitled ∩ activated (what the server enforces). */
modules: ModuleId[];
/** What this deployment is entitled to (MODULES_ENTITLED env) — the Setup → Site
* panel offers exactly these to toggle. */
modulesEntitled: ModuleId[];
/** What the site admin has activated (null in storage = everything entitled). */
modulesActivated: ModuleId[];
} & Record<TextField, string | null>;
function toSiteConfig(row: typeof siteConfig.$inferSelect | undefined): SiteConfig {
@@ -59,11 +72,22 @@ function toSiteConfig(row: typeof siteConfig.$inferSelect | undefined): SiteConf
anprEntryEnabled: row?.anprEntryEnabled ?? true,
bypassPresenceRadar: row?.bypassPresenceRadar ?? false,
bypassPresenceCamera: row?.bypassPresenceCamera ?? false,
...moduleView(row),
} as SiteConfig;
for (const f of TEXT_FIELDS) out[f] = row?.[f] ?? null;
return out;
}
function moduleView(row: typeof siteConfig.$inferSelect | undefined) {
const entitled = entitledModules();
const activated = activatedModulesOf(row) ?? entitled;
return {
modules: effectiveModules(entitled, activated),
modulesEntitled: entitled,
modulesActivated: activated,
};
}
/** Trim a text field; empty string becomes null so blank input clears it. */
function normText(v: unknown): string | null {
if (v == null) return null;
@@ -136,6 +160,40 @@ export async function siteRoutes(app: FastifyInstance, db: Db, eventLog?: EventL
}
const existing = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
// Venue-module activation. The body carries the full DESIRED set; the shared rules
// (required always on, must be entitled, dependencies effective) decide, and every
// module whose effective state actually flips is signed as a config_change — the
// same attribution pattern as the presence-bypass endpoint below. Disabling never
// deletes anything: tables/history/grants stay, routes 403, UI hides.
if ("modules" in body) {
const requested = body.modules;
if (!Array.isArray(requested) || !requested.every(isModuleId)) {
return reply.code(400).send({
error: `modules must be an array of module ids (${MODULES.map((m) => m.id).join(", ")})`,
});
}
const entitled = entitledModules();
const result = resolveModuleActivation(entitled, requested);
if (!result.ok) return reply.code(400).send({ error: result.error });
const prevEffective = new Set(effectiveModules(entitled, activatedModulesOf(existing) ?? entitled));
const nextEffective = new Set(effectiveModules(entitled, result.modules));
const operator = req.user?.username ?? "unknown";
for (const m of MODULES) {
const was = prevEffective.has(m.id);
const now = nextEffective.has(m.id);
if (was !== now) {
await eventLog?.append({
type: "config_change",
source: "manual",
identity: `module:${m.id}`,
payload: { setting: `modules.${m.id}`, value: now, prev: was, operator },
});
}
}
patch.modulesJson = JSON.stringify(result.modules);
}
const updatedAt = new Date().toISOString();
if (existing) {
db.update(siteConfig).set({ ...patch, updatedAt }).where(eq(siteConfig.id, 1)).run();
+7 -3
View File
@@ -12,6 +12,7 @@ import {
} from "@parking/db";
import { VALIDATION_MODES, type ValidationMode } from "@parking/shared";
import { requirePermission } from "../auth.js";
import { requireModule } from "../modules.js";
import type { EventLog } from "../event-log.js";
import { liveValidations, sessionValidations } from "../validations.js";
@@ -75,9 +76,12 @@ function validateProgram(b: ProgramBody): string | null {
}
export async function validationRoutes(app: FastifyInstance, db: Db, eventLog: EventLog): Promise<void> {
const siteRead = requirePermission("site:read");
const siteWrite = requirePermission("site:update");
const applyGuard = requirePermission("validation:create");
// Every route is behind the venue-module gate FIRST (403 module_disabled when the
// site has validation off — see ../modules.ts), then the usual permission guard.
const moduleOn = requireModule(db, "validation");
const siteRead = [moduleOn, requirePermission("site:read")];
const siteWrite = [moduleOn, requirePermission("site:update")];
const applyGuard = [moduleOn, requirePermission("validation:create")];
const liveProgram = (id: string) =>
db
+7 -5
View File
@@ -45,7 +45,7 @@ import { shiftRoutes } from "./routes/shift.js";
import { drawerRoutes } from "./routes/drawer.js";
import { entryRoutes } from "./routes/entry.js";
import { siteRoutes } from "./routes/site.js";
import { validationRoutes } from "./routes/validations.js";
import { registerModules } from "./modules/index.js";
import { snapshotRoutes } from "./routes/snapshots.js";
import { tariffRoutes } from "./routes/tariffs.js";
import { printerRoutes } from "./routes/printers.js";
@@ -296,10 +296,12 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// at capacity) is in the entry flow. See wiki/concepts/capacity-occupancy.md.
await siteRoutes(app, db, eventLog);
// Merchant validations (bar / lavazh): setup panel config + the merchant user's
// scan-and-apply. The booth settlement folds the applied validations into its
// quote (pay-station.ts). See wiki/concepts/validation-discounts.md.
await validationRoutes(app, db, eventLog);
// Venue modules (wiki/decisions/venue-modules.md): folder-based modules register
// here by iterating the shared registry — today that is `validation` (merchant
// validations for the Bar; the booth settlement folds applied validations into its
// quote, pay-station.ts). `parking` is in the registry too but its routes are still
// the flat list above; they move behind the seam subsystem by subsystem.
await registerModules(app, { db, eventLog });
// Application logs: ingest frontend errors (POST /api/logs, any signed-in user) +
// read the store (GET /api/logs, log:read). See wiki/concepts/app-logs.md.