Files
parking_solution/wiki/entities/local-jwt-auth.md
T
julian 55d6242c7d
CI / check (push) Successful in 46s
Build & push images / images (push) Successful in 2m58s
Build desktop / desktop (push) Successful in 4m53s
feat(permissions): per-desk till guards, jobs in the role composer, permission-scoped live feed; role reassignment applies without re-login
Permissions matrix rethink (wiki/decisions/venue-modules.md §"Permissions matrix",
open-questions #16) — the grid stays the enforcement layer:

- Move 1: each desk's money is guarded by that desk's own permissions. Manifest
  tillGuards {read, shift, cash}: booth = shift:read / shift:create / drawer:create
  (unchanged), carwash = carwash:read / carwash:cash (new). Shift + drawer routes
  resolve the guard FROM THE TILL (requireTill); a wash role holds no shift:* and cannot
  touch the booth by construction. Replaces the session:read borrowing (tillPermission).
  /api/shift/tills lists the role's readable tills with canWork; history/movements
  without a till filter return the union of readable tills.
- Move 2: jobs — manifest permission bundles (booth-operator, booth-supervisor,
  merchant, wash-operator) as one-click chips in Setup → Roles, with "mixes desks" and
  "partial job" lints (warnings, never blocks).
- Move 3: the live WebSocket admits any watch permission (event/session/device read or
  a module's feedPermission) and filters every push per role; report:read is the
  reports screen only.

Auth: the token's roleId is only a hint — refreshRole() after every jwtVerify resolves
the user's CURRENT role (cached, bumped on role/user writes), so reassigning a user's
role applies on the next request and a deleted user's session ends with 401.

Tests: till guards + look-only role, feed rules, every job's permissions exist, role
reassignment without re-login. 353/353.

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-05 14:45:48 +02:00

7.1 KiB

type, tags, sources, updated
type tags sources updated
entity
parking
stack
auth
offline-first
parking-system-architecture
2026-06-15

Local JWT Auth

Authentication and authorization, kept fully local — a direct consequence of offline-first (an air-gapped park cannot reach an external identity provider; see logto-zitadel-oidc for the rejected alternative). (See parking-system-architecture §2.)

  • @fastify/jwt signs tokens with a local secret (symmetric HMAC). The server refuses to start without a strong JWT_SECRET (≥32 chars, no placeholder) — there is deliberately no insecure default.
  • Session lifetime: valid until explicit logout — no time expiry (decision 2026-06-15, built). Booth reality breaks any fixed clock: relief arrives late, fails to show, or one operator is forced to work two shifts in a row — a token that expired mid-duty would strand an active operator. So the login persists until logout; a shift is a separate, explicit boundary, not tied to token lifetime. (Superseded the earlier "8h expiry, bound to a shift" assumption.) The JWT carries no exp; the cookie has a long fixed maxAge (30 days) so a browser restart doesn't log out an active operator, and logout clears it.
  • A users table in sqlite holds bcrypt password hashes plus a role_id FK. The first admin is seeded via pnpm --filter @parking/server seed-admin (no bootstrap endpoint); every other user is created in-app (admin → Users screen).
  • Authorization = dynamic RBAC (built 2026-06-18, replacing the old hardcoded admin/operator/cashier/readonly enum — those are now ordinary seed roles). Roles are data: roles + role_permissions tables, composed by an admin from a code-defined permission grid (@parking/shared PERMISSIONS = resource:action, e.g. tariff:update, payment:create, event:void). A preHandler requirePermission(...) per route checks a PERMISSION, not a role name. The JWT carries roleId (not the permission list); the guard resolves the role's permission set per-request from an in-memory cache (bumpPermsCache() on any role write), so editing a role applies immediately — no re-login, no token bloat. No Casbin/engine needed at this scale. The token's roleId is only a hint (2026-09-05): after every jwtVerify the guard replaces it with the user's CURRENT role from the DB (refreshRole(); cached per user, cleared by the same bumpPermsCache(), which user update/delete now call), so REASSIGNING a user's role — or deleting the user (→ 401 on their next request) — applies immediately too. Found when a user moved to a new wash role kept the old role's rights until logout.
  • Protected built-in admin role (id='admin', builtin=1): non-editable, non-deletable, and always resolves to the FULL permission set in code. The app refuses to delete or downgrade the last user holding admin — administration can never be locked out of the appliance.
  • event:void is a permission, NOT a ledger delete: the append-only signed chain is untouched; the permission only gates who may APPEND a void event (there is no void API route yet — forward seam).
  • The grid is extensible — adding a feature adds its resource:action rows. Recent additions: log:read (gates the diagnostic-log viewer, GET /api/logs; see app-logs); report:read (the admin Reports dashboard; see reporting-analytics); and recyclebin:read/update/delete (view / restore / purge soft-deleted master data; see soft-delete). Admin holds them all; each is grantable to a scoped role.
  • Soft-deleted users can't authenticate. The login route rejects a user whose deleted_at is set (with the same generic "invalid credentials" so a deleted account isn't enumerable). The no-lockout "last admin" check counts only LIVE admins, so soft-deleting can't strand administration. See soft-delete.
  • No privilege escalation through the RBAC system itself. role:create/role:update and user:create/user:update are themselves grantable, so a non-admin could otherwise self-escalate. Guards (routes/roles.ts, routes/users.ts): a caller may only put permissions on a role that they already hold, and may only assign/modify users whose role is a SUBSET of the caller's own (so no minting a privileged role, handing out the admin role, or resetting/deleting a more- privileged account). An admin holds the full set, so it is unrestricted — the intended behaviour.

The SPA never sees the JWT. Login (POST /api/auth/login) verifies bcrypt and sets two cookies:

  • parking_token — the JWT, HttpOnly + SameSite=Strict, and Secure by default (fail-safe — a forgotten env can only make cookies more restrictive, never drop the flag). Secure is dropped ONLY for a deliberate opt-out: COOKIE_SECURE=0 (the plain-HTTP LAN appliance — see disk-os-hardening deploy checklist) or NODE_ENV=development. (Was keyed off NODE_ENV=production, which silently leaked cookies on an appliance that forgot to set it — corrected 2026-06-21.) JS can't read it; @fastify/jwt reads it from the cookie, not the Authorization header.
  • parking_csrf — a random token, readable by JS. The JWT also carries a matching csrf claim. On every mutation the SPA echoes the cookie in the X-CSRF-Token header; the guard requires header == cookie == the signed claim (double-submit CSRF). Safe reads are exempt.

Routes: login, logout (clears cookies), me (bootstraps SPA session on load). The dev

Self-service profile (added 2026-06-24). Alongside the admin user-manager (routes/users.ts, gated on user:*), any signed-in user has two self-only routes (no permission needed — they act solely on req.user.sub):

  • PUT /api/auth/profile — edit own fullName / email ("" clears → null). Returns the refreshed session (so the SPA header updates). Cannot touch username or role — those stay admin-only, so this is not a privilege-escalation surface.
  • PUT /api/auth/password — change own password, but must prove the current one first (bcrypt.compare) → defends a walked-up, already-logged-in booth from a silent re-key. New password ≥ 8 chars. Distinct from the admin reset (PUT /api/users/:id/password), which needs no current password but DOES need user:update + the no-escalation guard. Both are still CSRF-guarded (mutations). The SPA surfaces them at /profile (apps/web/src/Profile.tsx), reachable from the header username chip. Covered by apps/server/src/routes/profile.test.ts.

The dev react-vite-spa proxy and the prod nginx reverse proxy keep the SPA and API same-origin, so the cookies work without CORS. (This replaced an earlier dev-only SETUP_AUTH_BYPASS shim, now removed.)

Open decision: moving from the symmetric secret to an asymmetric key (RS256/EdDSA) so verifying hosts hold only a public key — open-questions #7. Relevant before any multi-host/multi-lane deployment.

Part of the technology-stack. License: MIT.