Authentication & Role-Based Access Control (RBAC)
1. Executive Summary & Identity Architecture
Debelu's identity management architecture decouples Identity Verification (delegated to Supabase Auth) from Domain Authorization & Governance (enforced via backend middleware and PostgreSQL Row-Level Security).
Every request across web, native mobile, and operational surfaces is authenticated via cryptographically verified JSON Web Tokens (JWTs) and enriched with granular RBAC permissions and Authenticator Assurance Levels (AAL).
graph TD
subgraph Client Authentication
BUYER[Buyer Client] -->|Email / Password / Magic Link| SUPA_AUTH[Supabase Auth Service]
VENDOR[Vendor Client] -->|Credentials + Session| SUPA_AUTH
STAFF[Staff Member] -->|Credentials + TOTP MFA (AAL2)| SUPA_AUTH
end
subgraph Token Issuance & Enrichment
SUPA_AUTH -->|Signs JWT with SUPABASE_JWT_SECRET| JWT[Bearer JWT<br/>sub, exp, aal: aal1|aal2]
end
subgraph Backend Gateways on Fly.io
JWT --> AUTH_MW[auth.ts Middleware]
AUTH_MW --> PROFILE[Load public.profiles]
AUTH_MW --> ROLE_DEG[Role Resolution & Degradation Engine]
AUTH_MW --> AAL_CHECK{Enforce AAL2 for Sensitive Ops}
end
subgraph Authorization Envelopes
ROLE_DEG --> REQ_BUYER[Role: user]
ROLE_DEG --> REQ_VENDOR[Role: vendor]
ROLE_DEG --> REQ_STAFF[Role: moderator / admin + StaffPermissions]
end2. Token Lifecycle & Assurance Levels (AAL1 vs AAL2)
In compliance with modern financial security standards (NIST SP 800-63B), Debelu distinguishes between standard single-factor authentication and high-assurance multi-factor sessions:
2.1 Authenticator Assurance Level 1 (aal1)
- Granted via email/password authentication or magic link verification.
- Valid for standard customer operations: catalog browsing, searching, cart updates, order checkout, and buyer-vendor messaging.
- Prohibited Surfaces: Cannot access staff administration routes, cannot initiate privacy exports (DSAR), and cannot review platform configuration proposals.
2.2 Authenticator Assurance Level 2 (aal2)
- Requires successful completion of a secondary authentication factor:
- Time-based One-Time Password (TOTP via Google Authenticator, 1Password, Authy).
- WebAuthn / Passkeys / FIDO2 security keys.
- Mandatory Enforcing Endpoints:
/api/privacy/exports(Personal data dossier download)./api/platform-configuration-proposals(Maker-Checker platform settings)./api/payout-transfer-reconciliations(Financial ledger restitution)./api/admin/roles(Staff permission elevation).
3. Account Status & The Effective Role Degradation Engine
Grounded in [debelu-backend/src/middleware/auth.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/debelu-backend/src/middleware/auth.ts), Debelu prevents privilege escalation and orphan admin permissions through Dynamic Role Degradation:
const access = await resolveStaffAccess(profile);
const effectiveRole = ['admin', 'moderator'].includes(profile.role) && (!access.staff || !access.globalAccess)
? 'user'
: profile.role === 'admin' && !access.owner
? 'moderator'
: profile.role;3.1 Degradation Invariants
- Dangling Role Mitigation: If an administrative role is revoked in
public.admin_roleswhile a user'sprofiles.rolecolumn still contains'admin', the user is instantly degraded to'user'on their next API request without requiring a database profile rewrite. - Owner Isolation: Only the verified platform owner retains root administrative status; secondary administrators operate under scoped
'moderator'role policies. - Restricted Account Exclusion: Users with
status IN ('suspended', 'banned', 'deactivated')are blocked by default with403 Forbidden("This account is restricted"), with exemptions granted exclusively to account appeal endpoints viarequireAuthAllowRestricted.
4. Middleware Pipeline & Route Guards
Backend route files in debelu-backend/src/routes declare authorization gates declaratively using composable Express middlewares:
graph LR
REQ[Inbound Request] --> AUTH[requireAuth]
AUTH --> CHECK_ROLE{Role Check}
CHECK_ROLE -->|requireVendor| VENDOR_ROUTE[Vendor Catalog & Orders]
CHECK_ROLE -->|requireStaff| PERM[requirePermission: canApprovePayouts]
PERM --> AAL[requireAal2]
AAL --> SENSITIVE_ROUTE[Payout Batch Dispatch]Middleware Specifications
requireAuth: Extracts Bearer token, validates JWT integrity against Supabase Auth, confirms active non-suspended status, and enrichesreq.user.requireAuthAllowRestricted: Allows suspended or deletion-requested accounts to view restriction reasons or cancel pending account erasure.requireVendor: Assertsreq.user.role === 'vendor'.requireStaff: Asserts user belongs to an active staff role with non-empty permissions.requirePermission(permission: StaffPermission): Asserts exact granular capability (e.g.canApprovePayouts,canManageOrders,canManageUsers).requireAal2: Assertsreq.user._aal === 'aal2', throwing403 Forbiddenif the session lacks second-factor validation.
5. Row-Level Security (RLS) Policy Architecture
While API routes enforce perimeter authorization, PostgreSQL Row-Level Security (RLS) acts as the definitive data isolation barrier at the storage engine level.
-- RLS Policy: Buyers can only inspect their own orders
CREATE POLICY buyer_order_isolation ON public.orders
FOR SELECT
TO authenticated
USING (user_id = auth.uid());
-- RLS Policy: Vendors can only view orders containing their inventory
CREATE POLICY vendor_order_isolation ON public.orders
FOR SELECT
TO authenticated
USING (vendor_id = auth.uid());
-- RLS Policy: Service role bypass for backend background workers
-- service_role role possesses BYPASSRLS privilegeSecurity Definer Stored Procedures
For operations requiring complex multi-table mutations (such as escrow fund release, payout batching, and privacy erasure), Debelu uses PostgreSQL Security Definer Functions:
- Functions run with elevated privileges of their creator.
- Explicit validation of
auth.uid()or inputactor_idwithin the function body. - Revocation of direct table
INSERT,UPDATE,DELETEgrants from standard roles, preventing SQL injection from bypassing business logic.