feat(auth): dynamic RBAC — composable roles + resource×CRUD permissions

Replace the hardcoded role enum (admin/operator/cashier/readonly, checked
literally as requireRole("admin",...) across ~15 routes) with dynamic RBAC:
roles are DATA, route guards check a PERMISSION.

@parking/shared defines a code-defined grid: RESOURCES (user/role/tariff/
subscription/site/device/shift/payment/session/event/report) × Action
(create/read/update/delete + domain verbs void/cash) -> PERMISSIONS
(resource:action, e.g. tariff:update, payment:create, event:void).

DB: new roles + role_permissions tables; users.role enum -> role_id FK;
migration 0007_rbac (create tables, seed the builtin admin role + all 26
perms, seed operator/cashier/readonly composable roles matching old
behaviour, rebuild users to swap the column copying all rows).

auth.ts: JWT payload role -> roleId; permissionsFor(roleId) with an
in-memory cache + bumpPermsCache(); requirePermission(...perms) preHandler;
requireAuth for /me & /language; initAuth(db) wires the resolver once. Every
route guard mapped to a permission; device ingress (devices/qr-reader) stays
auth-free by design. New routes/users.ts (user:* CRUD, bcrypt 12, last-admin
guard) + routes/roles.ts (role:* CRUD, builtin-protected, perms validated
against the grid, cache bump on write). auth/me + /login return
{roleId, roleName, permissions, language}. seed-admin -> roleId:'admin'.

Frontend: SessionUser carries permissions + can() helper; router nav/route
guards gate by permission (requirePerm replaces adminOnly); SiteSettings
edit gated by site:update; new UsersManager + RolesManager (permission
checkbox grid; admin role locked); i18n nav.users/roles + blocks (sq+en).

Decisions: one role per user; protected built-in admin (no-lockout: the last
admin can't be deleted/downgraded); JWT carries roleId, perms resolved
per-request so role edits apply immediately (no re-login).

Verified: full build green; 20-assertion inject test passes (cashier 403s on
tariff publish + user list, admin passes, granting a perm applies on the next
request, last-admin + builtin-role protections return 409); migration 0007
applied to a copy of the live DB (incl WAL/shm) — existing admin maps to
role_id='admin', all rows preserved. Append-only event chain untouched
(event:void gates appending a void, not a delete).

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-19 01:19:28 +02:00
parent d71ba82999
commit d0841c8601
29 changed files with 1301 additions and 104 deletions
+81 -8
View File
@@ -1,16 +1,22 @@
import { randomBytes } from "node:crypto";
import type { FastifyReply, FastifyRequest } from "fastify";
import type { Role } from "@parking/shared";
import { eq, rolePermissions, type Db } from "@parking/db";
import { ADMIN_ROLE_ID, PERMISSIONS, type Permission } from "@parking/shared";
// Local JWT auth helpers — fully local, no external identity provider
// (offline-first). The JWT is carried in an HttpOnly cookie (JS can't read it);
// a separate readable CSRF cookie + matching header defends mutations
// (double-submit). See wiki/entities/local-jwt-auth.md.
//
// Authorization is DYNAMIC RBAC: the token carries the user's `roleId`, and each
// guarded route resolves that role's PERMISSION SET (cached in memory) and checks
// the permission it requires. Editing a role takes effect on the next request —
// no re-login, no token bloat, no stale perms. See @parking/shared PERMISSIONS.
declare module "@fastify/jwt" {
interface FastifyJWT {
payload: { sub: string; username: string; role: Role; csrf: string };
user: { sub: string; username: string; role: Role; csrf: string };
payload: { sub: string; username: string; roleId: string; csrf: string };
user: { sub: string; username: string; roleId: string; csrf: string };
}
}
@@ -96,17 +102,84 @@ function assertCsrf(req: FastifyRequest): void {
}
}
// --- Permission resolution + cache -------------------------------------------
// A role's permission set is read from `role_permissions` and cached in memory.
// SQLite is single-writer/single-process here, so a module-level Map is a correct
// cache: every role / role-permission mutation calls bumpPermsCache() to clear it,
// and the next request re-reads. The built-in `admin` role always resolves to the
// FULL permission set in code (never trusts the DB rows for it), so administration
// can't be accidentally narrowed.
const ADMIN_PERMS: ReadonlySet<Permission> = new Set(PERMISSIONS);
const permsCache = new Map<string, ReadonlySet<Permission>>();
// The DB handle the permission resolver reads from. Set ONCE at startup via
// initAuth() so route guards don't each have to thread `db` (several route
// modules only receive a monitor/service, not the db). Single-process server.
let authDb: Db | null = null;
/** Wire the permission resolver to the app's DB. Call once in buildServer(). */
export function initAuth(db: Db): void {
authDb = db;
permsCache.clear();
}
/** Clear the permission cache. Call after ANY write to roles / role_permissions
* (or a user's roleId) so the change takes effect on the next request. */
export function bumpPermsCache(): void {
permsCache.clear();
}
/** The permission set for a role id, cached. `admin` is always the full set. */
export function permissionsFor(roleId: string): ReadonlySet<Permission> {
if (roleId === ADMIN_ROLE_ID) return ADMIN_PERMS;
const hit = permsCache.get(roleId);
if (hit) return hit;
if (!authDb) throw new Error("auth not initialised (call initAuth)");
const rows = authDb
.select({ permission: rolePermissions.permission })
.from(rolePermissions)
.where(eq(rolePermissions.roleId, roleId))
.all();
const set = new Set(rows.map((r) => r.permission as Permission));
permsCache.set(roleId, set);
return set;
}
/** True if the role grants every listed permission. */
export function roleHasPermissions(
roleId: string,
required: readonly Permission[],
): boolean {
const granted = permissionsFor(roleId);
return required.every((p) => granted.has(p));
}
/**
* preHandler role guard. Verifies the JWT (from the HttpOnly cookie), enforces
* CSRF on mutations, then checks the role. Authorization is a simple per-route
* role check — no Casbin/RBAC engine needed at this scale.
* preHandler permission guard. Verifies the JWT (from the HttpOnly cookie),
* enforces CSRF on mutations, then requires the user's role to grant ALL of the
* listed permissions. Authorization is a per-route permission check against the
* dynamic, admin-composed role grid — no Casbin/RBAC engine needed at this scale.
*/
export function requireRole(...allowed: Role[]) {
export function requirePermission(...required: Permission[]) {
return async (req: FastifyRequest, _reply: FastifyReply) => {
await req.jwtVerify(); // reads the token cookie (configured in server.ts)
assertCsrf(req);
if (!req.user || !allowed.includes(req.user.role)) {
if (!req.user || !roleHasPermissions(req.user.roleId, required)) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
};
}
/**
* preHandler that requires a valid signed-in session but NO specific permission —
* for "about me" routes (/me, change own language) every authenticated user may
* call regardless of role. Still enforces CSRF on mutations.
*/
export async function requireAuth(
req: FastifyRequest,
_reply: FastifyReply,
): Promise<void> {
await req.jwtVerify();
assertCsrf(req);
}