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:
@@ -0,0 +1,103 @@
|
||||
-- Dynamic RBAC: roles become DATA. Replaces the hardcoded users.role enum with a
|
||||
-- role_id FK into a composable `roles` table + a `role_permissions` grid.
|
||||
-- See wiki/entities/local-jwt-auth.md and @parking/shared PERMISSIONS.
|
||||
|
||||
-- 1. Roles + the role→permission grid.
|
||||
CREATE TABLE `roles` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`builtin` integer DEFAULT 0 NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `roles_name_unique` ON `roles` (`name`);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `role_permissions` (
|
||||
`role_id` text NOT NULL,
|
||||
`permission` text NOT NULL,
|
||||
FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `role_permissions_role_id_permission_unique` ON `role_permissions` (`role_id`,`permission`);
|
||||
--> statement-breakpoint
|
||||
|
||||
-- 2. Seed the protected built-in `admin` role. Its permission set is enforced in
|
||||
-- code (always ALL), but we materialise the rows too so the grid is complete.
|
||||
INSERT INTO `roles` (`id`, `name`, `builtin`) VALUES ('admin', 'Admin', 1);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `role_permissions` (`role_id`, `permission`) VALUES
|
||||
('admin','user:create'),('admin','user:read'),('admin','user:update'),('admin','user:delete'),
|
||||
('admin','role:create'),('admin','role:read'),('admin','role:update'),('admin','role:delete'),
|
||||
('admin','tariff:read'),('admin','tariff:update'),
|
||||
('admin','subscription:read'),('admin','subscription:create'),('admin','subscription:update'),('admin','subscription:delete'),
|
||||
('admin','site:read'),('admin','site:update'),
|
||||
('admin','device:read'),
|
||||
('admin','shift:read'),('admin','shift:create'),('admin','shift:cash'),
|
||||
('admin','payment:read'),('admin','payment:create'),
|
||||
('admin','session:read'),
|
||||
('admin','event:read'),('admin','event:void'),
|
||||
('admin','report:read');
|
||||
--> statement-breakpoint
|
||||
|
||||
-- 3. Seed composable roles matching the OLD enum's intended behaviour, so any
|
||||
-- existing operator/cashier/readonly user keeps working. These are ordinary
|
||||
-- (non-builtin) rows an admin may later edit or delete.
|
||||
INSERT INTO `roles` (`id`, `name`, `builtin`) VALUES ('operator', 'Operator', 0);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `role_permissions` (`role_id`, `permission`) VALUES
|
||||
('operator','payment:read'),('operator','payment:create'),
|
||||
('operator','session:read'),
|
||||
('operator','shift:read'),('operator','shift:create'),
|
||||
('operator','subscription:read'),
|
||||
('operator','tariff:read'),
|
||||
('operator','site:read'),
|
||||
('operator','device:read'),
|
||||
('operator','event:read'),
|
||||
('operator','report:read');
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `roles` (`id`, `name`, `builtin`) VALUES ('cashier', 'Cashier', 0);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `role_permissions` (`role_id`, `permission`) VALUES
|
||||
('cashier','payment:read'),('cashier','payment:create'),
|
||||
('cashier','session:read'),
|
||||
('cashier','shift:read'),('cashier','shift:create'),
|
||||
('cashier','subscription:read'),
|
||||
('cashier','tariff:read'),
|
||||
('cashier','site:read'),
|
||||
('cashier','device:read'),
|
||||
('cashier','event:read'),
|
||||
('cashier','report:read');
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `roles` (`id`, `name`, `builtin`) VALUES ('readonly', 'Read-only', 0);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `role_permissions` (`role_id`, `permission`) VALUES
|
||||
('readonly','session:read'),
|
||||
('readonly','subscription:read'),
|
||||
('readonly','tariff:read'),
|
||||
('readonly','site:read'),
|
||||
('readonly','device:read'),
|
||||
('readonly','event:read'),
|
||||
('readonly','report:read');
|
||||
--> statement-breakpoint
|
||||
|
||||
-- 4. Rebuild `users` to swap the `role` enum column for a `role_id` FK. SQLite
|
||||
-- can't DROP a column cleanly, so: create the new shape, copy rows mapping the
|
||||
-- old role string -> role id (identical strings), drop, rename.
|
||||
CREATE TABLE `users_new` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`role_id` text NOT NULL,
|
||||
`language` text DEFAULT 'sq' NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL,
|
||||
FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO `users_new` (`id`, `username`, `password_hash`, `role_id`, `language`, `created_at`)
|
||||
SELECT `id`, `username`, `password_hash`, `role`, `language`, `created_at` FROM `users`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `users`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `users_new` RENAME TO `users`;
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_username_unique` ON `users` (`username`);
|
||||
@@ -50,6 +50,13 @@
|
||||
"when": 1781884900000,
|
||||
"tag": "0006_site_default_category",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "6",
|
||||
"when": 1781885000000,
|
||||
"tag": "0007_rbac",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -5,7 +5,61 @@
|
||||
// and exit events are never edited or deleted — a "void" is itself an appended
|
||||
// event. See wiki/concepts/append-only-event-chain.md.
|
||||
|
||||
export type Role = "admin" | "operator" | "cashier" | "readonly";
|
||||
// --- Authorization: dynamic RBAC (resource × CRUD permissions) ---------------
|
||||
// Roles are DATA (admin-composable rows in the DB), not a hardcoded enum. A role
|
||||
// is a named bundle of PERMISSIONS; a permission is a `resource:action` pair drawn
|
||||
// from the code-defined grid below. Route guards check a permission, never a role
|
||||
// name. A built-in, locked `admin` role (id ADMIN_ROLE_ID) always holds every
|
||||
// permission, so administration can never be locked out. See
|
||||
// wiki/entities/local-jwt-auth.md and the RBAC plan.
|
||||
|
||||
/** The resources permissions are scoped to (code-defined; roles/assignments are data). */
|
||||
export const RESOURCES = [
|
||||
"user", // manage operators/cashiers + reset password
|
||||
"role", // compose roles + assign permissions
|
||||
"tariff", // read / publish a new version
|
||||
"subscription", // the subscription registry
|
||||
"site", // site_config + device setup/assign
|
||||
"device", // device status / printers / snapshots / catalog
|
||||
"shift", // open/close own shift; move the drawer float
|
||||
"payment", // take payment, quote, voucher/receipt, exit, reopen
|
||||
"session", // active sessions, lookup
|
||||
"event", // the signed ledger feed + void
|
||||
"report", // events feed, occupancy, future reports
|
||||
] as const;
|
||||
export type Resource = (typeof RESOURCES)[number];
|
||||
|
||||
/** CRUD plus two domain verbs where CRUD doesn't fit: `void` (append a void event,
|
||||
* NOT a delete) and `cash` (move the drawer float — an admin-grade shift action). */
|
||||
export type Action = "create" | "read" | "update" | "delete" | "void" | "cash";
|
||||
|
||||
/** A single permission, e.g. "tariff:update". The route guard checks one of these. */
|
||||
export type Permission = `${Resource}:${Action}`;
|
||||
|
||||
/** The complete, code-defined permission grid. Only these strings are checkable by
|
||||
* a guard — an admin composes roles by selecting from this set. Preserves today's
|
||||
* exact authz semantics (e.g. void split from read; shift cash split from open). */
|
||||
export const PERMISSIONS: readonly Permission[] = [
|
||||
"user:create", "user:read", "user:update", "user:delete",
|
||||
"role:create", "role:read", "role:update", "role:delete",
|
||||
"tariff:read", "tariff:update",
|
||||
"subscription:read", "subscription:create", "subscription:update", "subscription:delete",
|
||||
"site:read", "site:update",
|
||||
"device:read",
|
||||
"shift:read", "shift:create", "shift:cash",
|
||||
"payment:read", "payment:create",
|
||||
"session:read",
|
||||
"event:read", "event:void",
|
||||
"report:read",
|
||||
] as const;
|
||||
|
||||
/** The protected built-in role: non-deletable, non-editable, always = ALL
|
||||
* permissions. At least one user must always hold it (no-lockout invariant). */
|
||||
export const ADMIN_ROLE_ID = "admin";
|
||||
|
||||
/** Transitional alias. Roles are now DB rows keyed by a string id; `Role` is kept
|
||||
* as `string` so any not-yet-migrated reference still compiles. */
|
||||
export type Role = string;
|
||||
|
||||
export type Direction = "entry" | "exit";
|
||||
|
||||
@@ -637,13 +691,6 @@ function compareCard(
|
||||
return 0;
|
||||
}
|
||||
|
||||
export const ROLES: readonly Role[] = [
|
||||
"admin",
|
||||
"operator",
|
||||
"cashier",
|
||||
"readonly",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Signs the canonical bytes of an event for the append-only chain. This is the
|
||||
* abstraction over the [[atecc608]] secure element: the real, non-extractable
|
||||
|
||||
Reference in New Issue
Block a user