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,159 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import bcrypt from "bcrypt";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, roles, users, type Db } from "@parking/db";
|
||||
import { ADMIN_ROLE_ID } from "@parking/shared";
|
||||
import { requirePermission } from "../auth.js";
|
||||
|
||||
// User management (admin). Users are created/edited at runtime here — the
|
||||
// install-time seed-admin.mjs only bootstraps the FIRST admin. Each user has one
|
||||
// role (RBAC); the role resolves to a permission set at request time. Passwords
|
||||
// are bcrypt-hashed (cost 12) and never returned. See @parking/shared PERMISSIONS.
|
||||
//
|
||||
// NO-LOCKOUT INVARIANT: the app refuses to delete, or move off the `admin` role,
|
||||
// the LAST user still holding `admin`. Administration can therefore never be
|
||||
// locked out of the appliance. See wiki/entities/local-jwt-auth.md.
|
||||
|
||||
interface CreateBody {
|
||||
username: string;
|
||||
password: string;
|
||||
roleId: string;
|
||||
}
|
||||
interface UpdateBody {
|
||||
username?: string;
|
||||
roleId?: string;
|
||||
}
|
||||
interface PasswordBody {
|
||||
password: string;
|
||||
}
|
||||
|
||||
const MIN_PASSWORD = 8;
|
||||
|
||||
export async function userRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
const readGuard = requirePermission("user:read");
|
||||
const createGuard = requirePermission("user:create");
|
||||
const updateGuard = requirePermission("user:update");
|
||||
const deleteGuard = requirePermission("user:delete");
|
||||
|
||||
/** Count users currently holding the protected admin role. */
|
||||
function adminCount(): number {
|
||||
return db.select().from(users).where(eq(users.roleId, ADMIN_ROLE_ID)).all().length;
|
||||
}
|
||||
|
||||
/** True if removing/relocating `userId` from admin would leave zero admins. */
|
||||
function isLastAdmin(userId: string): boolean {
|
||||
const u = db.select().from(users).where(eq(users.id, userId)).get();
|
||||
return u?.roleId === ADMIN_ROLE_ID && adminCount() <= 1;
|
||||
}
|
||||
|
||||
/** A user row safe to return — never the password hash. */
|
||||
function publicUser(u: { id: string; username: string; roleId: string; language: string; createdAt: string }) {
|
||||
return { id: u.id, username: u.username, roleId: u.roleId, language: u.language, createdAt: u.createdAt };
|
||||
}
|
||||
|
||||
// List all users (no password hashes) + their role names for display.
|
||||
app.get("/api/users", { preHandler: readGuard }, async () => {
|
||||
const rows = db.select().from(users).all();
|
||||
const roleRows = db.select().from(roles).all();
|
||||
const roleName = new Map(roleRows.map((r) => [r.id, r.name]));
|
||||
return {
|
||||
users: rows.map((u) => ({ ...publicUser(u), roleName: roleName.get(u.roleId) ?? u.roleId })),
|
||||
};
|
||||
});
|
||||
|
||||
// Create a user. Username unique; password >= 8 chars; roleId must exist.
|
||||
app.post<{ Body: CreateBody }>("/api/users", { preHandler: createGuard }, async (req, reply) => {
|
||||
const username = (req.body?.username ?? "").trim();
|
||||
const password = req.body?.password ?? "";
|
||||
const roleId = (req.body?.roleId ?? "").trim();
|
||||
if (!username || !roleId) {
|
||||
return reply.code(400).send({ error: "username and roleId required" });
|
||||
}
|
||||
if (password.length < MIN_PASSWORD) {
|
||||
return reply.code(400).send({ error: `password must be at least ${MIN_PASSWORD} characters` });
|
||||
}
|
||||
if (!db.select().from(roles).where(eq(roles.id, roleId)).get()) {
|
||||
return reply.code(400).send({ error: "unknown roleId" });
|
||||
}
|
||||
if (db.select().from(users).where(eq(users.username, username)).get()) {
|
||||
return reply.code(409).send({ error: "username already exists" });
|
||||
}
|
||||
const id = randomUUID();
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
db.insert(users).values({ id, username, passwordHash, roleId }).run();
|
||||
const created = db.select().from(users).where(eq(users.id, id)).get()!;
|
||||
return reply.code(201).send(publicUser(created));
|
||||
});
|
||||
|
||||
// Update a user's username and/or role. Guarded against orphaning admin.
|
||||
app.put<{ Params: { id: string }; Body: UpdateBody }>(
|
||||
"/api/users/:id",
|
||||
{ preHandler: updateGuard },
|
||||
async (req, reply) => {
|
||||
const id = req.params.id;
|
||||
const existing = db.select().from(users).where(eq(users.id, id)).get();
|
||||
if (!existing) return reply.code(404).send({ error: "user not found" });
|
||||
|
||||
const next: { username?: string; roleId?: string } = {};
|
||||
if (req.body?.username != null) {
|
||||
const username = req.body.username.trim();
|
||||
if (!username) return reply.code(400).send({ error: "username cannot be empty" });
|
||||
const clash = db.select().from(users).where(eq(users.username, username)).get();
|
||||
if (clash && clash.id !== id) return reply.code(409).send({ error: "username already exists" });
|
||||
next.username = username;
|
||||
}
|
||||
if (req.body?.roleId != null) {
|
||||
const roleId = req.body.roleId.trim();
|
||||
if (!db.select().from(roles).where(eq(roles.id, roleId)).get()) {
|
||||
return reply.code(400).send({ error: "unknown roleId" });
|
||||
}
|
||||
// No-lockout: don't move the last admin off the admin role.
|
||||
if (roleId !== ADMIN_ROLE_ID && isLastAdmin(id)) {
|
||||
return reply.code(409).send({ error: "cannot change the role of the last admin" });
|
||||
}
|
||||
next.roleId = roleId;
|
||||
}
|
||||
if (Object.keys(next).length === 0) {
|
||||
return reply.code(400).send({ error: "nothing to update" });
|
||||
}
|
||||
db.update(users).set(next).where(eq(users.id, id)).run();
|
||||
return publicUser(db.select().from(users).where(eq(users.id, id)).get()!);
|
||||
},
|
||||
);
|
||||
|
||||
// Reset a user's password (admin sets a new one; >= 8 chars).
|
||||
app.put<{ Params: { id: string }; Body: PasswordBody }>(
|
||||
"/api/users/:id/password",
|
||||
{ preHandler: updateGuard },
|
||||
async (req, reply) => {
|
||||
const id = req.params.id;
|
||||
if (!db.select().from(users).where(eq(users.id, id)).get()) {
|
||||
return reply.code(404).send({ error: "user not found" });
|
||||
}
|
||||
const password = req.body?.password ?? "";
|
||||
if (password.length < MIN_PASSWORD) {
|
||||
return reply.code(400).send({ error: `password must be at least ${MIN_PASSWORD} characters` });
|
||||
}
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
db.update(users).set({ passwordHash }).where(eq(users.id, id)).run();
|
||||
return { ok: true };
|
||||
},
|
||||
);
|
||||
|
||||
// Delete a user. Refused if it's the last admin (no-lockout).
|
||||
app.delete<{ Params: { id: string } }>(
|
||||
"/api/users/:id",
|
||||
{ preHandler: deleteGuard },
|
||||
async (req, reply) => {
|
||||
const id = req.params.id;
|
||||
if (!db.select().from(users).where(eq(users.id, id)).get()) {
|
||||
return reply.code(404).send({ error: "user not found" });
|
||||
}
|
||||
if (isLastAdmin(id)) {
|
||||
return reply.code(409).send({ error: "cannot delete the last admin" });
|
||||
}
|
||||
db.delete(users).where(eq(users.id, id)).run();
|
||||
return { ok: true };
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user