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
+42 -6
View File
@@ -1,5 +1,5 @@
import { sql } from "drizzle-orm";
import { blob, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { blob, integer, sqliteTable, text, unique } from "drizzle-orm/sqlite-core";
// Schema notes:
// - TWO event streams, deliberately separate (see wiki/decisions/event-streams-split.md):
@@ -12,16 +12,50 @@ import { blob, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
// - Business master data (tariffs/subscriptions/blocklist) IS mutable, but its USE is fixed in a
// signed ledger event, so the audit trail stays append-only. Tariffs are versioned:
// editing publishes a new immutable tariff_version. See wiki/concepts/tariff.md.
// - `users` holds bcrypt hashes + a role; auth is fully local (offline-first).
// See wiki/entities/local-jwt-auth.md.
// - Authorization is DYNAMIC RBAC, fully local (offline-first): `roles` are data
// (admin-composable), `role_permissions` is the role→permission grid, and each
// `users` row points at one role via `role_id`. Permissions are checked per
// route (see @parking/shared PERMISSIONS). A built-in, locked `admin` role
// (id='admin') always holds every permission. See wiki/entities/local-jwt-auth.md.
/** A composable role: a named bundle of permissions. `builtin` rows (the `admin`
* role) are protected — not editable or deletable, and always granted all
* permissions. Everything else is admin-composed at runtime. */
export const roles = sqliteTable("roles", {
id: text("id").primaryKey(),
name: text("name").notNull().unique(),
// 1 = protected built-in (the `admin` role). 0 = admin-composed.
builtin: integer("builtin").notNull().default(0),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
/** The role→permission grid. One row per granted `resource:action` permission.
* The `admin` role is granted all permissions implicitly in code, so its rows
* here are belt-and-suspenders. See @parking/shared PERMISSIONS. */
export const rolePermissions = sqliteTable(
"role_permissions",
{
roleId: text("role_id")
.notNull()
.references(() => roles.id),
permission: text("permission").notNull(),
},
(t) => ({
// A permission is granted to a role at most once.
uniq: unique().on(t.roleId, t.permission),
}),
);
export const users = sqliteTable("users", {
id: text("id").primaryKey(),
username: text("username").notNull().unique(),
passwordHash: text("password_hash").notNull(),
role: text("role", {
enum: ["admin", "operator", "cashier", "readonly"],
}).notNull(),
// One role per user (RBAC). Resolves to a permission set at request time.
roleId: text("role_id")
.notNull()
.references(() => roles.id),
// Preferred UI language for this user (operator-facing). Loaded on login and
// restored from any booth. Albanian is the default. Printed tickets are NOT
// governed by this — they're always Albanian (customer-facing). See i18n.md.
@@ -310,6 +344,8 @@ export const sessions = sqliteTable("sessions", {
});
export type UserRow = typeof users.$inferSelect;
export type RoleRow = typeof roles.$inferSelect;
export type RolePermissionRow = typeof rolePermissions.$inferSelect;
export type LedgerEventRow = typeof ledgerEvents.$inferSelect;
export type DeviceEventRow = typeof deviceEvents.$inferSelect;
export type SnapshotRow = typeof snapshots.$inferSelect;