Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

11.8 KB
Raw Blame

TOTP MFA (Authenticator App) — Implementation Plan

Status: IMPLEMENTED 2026-08-15 (committed on nist-800-110-audit; the unchecked task boxes below are stale — the code shipped. See "Resolved decisions" and "Implementation deltas"). Reference: https://supabase.com/docs/guides/auth/auth-mfa/totp

Resolved decisions (2026-08-15)

  1. Passkey logins ARE challenged (they land at AAL1).
  2. Enrollment UI lives in account settings — later moved to a dedicated x+/account+/security.tsx alongside passkeys.
  3. Active re-checking chosen for stale sessions: AuthSession.mfaVerified flag + per-request Redis-cached factor lookup in requireAuthSession, bouncing to /mfa.
  4. Admin reset: any company admin with update: "users" (People module modal route).
  5. All editions, no feature flag.

Implementation deltas from the original plan

  • Academy and starter also consume requireAuthSession, so they got /mfa routes too (no callback gate there — the active re-check bounces them on first use).
  • Challenge action logic centralized as completeMfaChallenge in session.server.ts instead of four copies; makeAuthSession exported with an mfaVerified option.
  • Enrollment UI was later MOVED out of profile.tsx into a dedicated x+/account+/security.tsx that also owns passkeys (open question 2 revisited).
  • Phase 6 (org enforcement) WAS built, not deferred: companySettings.requireMfa (20260816103045), a Settings → Company toggle, a CONTROLLED_ENVIRONMENT override that cannot be switched off, and a blocking screen in the ERP/MES shells modeled on the ITAR gate rather than a redirect (a redirect must allowlist the api+/mfa.* routes used to escape it). Enforcement is scoped to the ACTIVE company.
  • A "Skip for now" deferral was built (per-company cookie) and then REMOVED at the user's request; Sign out is now the only exit from the gate.
  • Admin visibility: users_with_verified_mfa RPC (20260816114512, gated on enforcement in 20260816131807) backs a Two-Factor column on employee accounts. It could not be a column on the employees view — that view is SECURITY_INVOKER and auth.mfa_factors is in the auth schema.
  • Shared UI extracted to ~/components/TotpEnrollment (useTotpEnrollment, OtpInput, INVALID_CODE_MESSAGE) so the settings card and the enforcement gate cannot drift.
  • Unit tests: packages/auth/src/services/mfa-session.test.ts (10 tests) covers the pending-session TTL/clearing, completeMfaChallenge paths, and the re-check bounce.

Known remaining work

  • The four /mfa challenge routes are 85% duplicated (843 lines across erp/mes/ academy/starter). Extracting a shared challenge form + action helper is the main outstanding refactor.
  • x+/account+/security.tsx is ~650 lines; its passkey and MFA halves are independent and could be separate components.
  • No browser verification has been done for any of the MFA UI.
  • RLS enforcement on the aal JWT claim (recommended by the Supabase docs) is NOT implemented — service-role and API-key paths have no AAL, so a blanket restrictive policy would break them. Needs its own design pass.

Tasks

Phase 1 — Infrastructure

  • 1.1 Local GoTrue MFA env — packages/dev/docker/docker-compose.dev.yml (auth service, after L94): add GOTRUE_MFA_TOTP_ENROLL_ENABLED: "true", GOTRUE_MFA_TOTP_VERIFY_ENABLED: "true", GOTRUE_MFA_MAX_ENROLLED_FACTORS: 10. Verify: crbn up (user runs), then curl $SUPABASE_URL/auth/v1/settings | jq .mfa_enabled.
  • 1.2 Hosted parity — packages/database/supabase/config.toml: add [auth.mfa] max_enrolled_factors = 10 and [auth.mfa.totp] enroll_enabled = true, verify_enabled = true. (Cloud project: also flip on in dashboard — user action, note in PR.)

Phase 2 — @carbon/auth MFA service

  • 2.1 packages/auth/src/services/mfa.server.ts (new; export as ./mfa.server subpath in packages/auth/package.json, mirroring ./passkey.server):
    • getUserAuthClient(accessToken, refreshToken) — fresh anon client + auth.setSession(...); private helper.
    • hasVerifiedTotpFactor(userId) → boolean, and getVerifiedTotpFactors(userId) — service role auth.admin.mfa.listFactors({ userId }), filter factor_type === 'totp' && status === 'verified'.
    • enrollTotpFactor(tokens, friendlyName) → { factorId, qrCode, secret, uri }.
    • verifyTotpChallenge(tokens, factorId, code) → Result<SupabaseAuthSession> via mfa.challengeAndVerify; used by BOTH enrollment verify and login challenge.
    • unenrollTotpFactor(tokens, factorId, code) — step-up challengeAndVerify then mfa.unenroll.
    • adminDeleteTotpFactors(userId) — service role auth.admin.mfa.deleteFactor per factor.
    • Unenrolled-factor cleanup: enrollTotpFactor first deletes any stale status === 'unverified' factors for the user (abandoned enrollments block re-enroll with the same friendly name).
  • 2.2 Pending-MFA session — packages/auth/src/services/session.server.ts: setPendingMfaSession(request, authSession), getPendingMfaSession(request), clearPendingMfaSession(request) using key "mfa" in the existing session storage. Pending payload = the would-be AuthSession + redirectTo. Reject pending sessions older than 10 min (store createdAt, compare in getPendingMfaSession).
  • 2.3 Export makeAuthSession (currently private in auth.server.ts:129) or add a thin makeSessionFromSupabase(session, companyId, companyGroupId) wrapper so /mfa route actions can build the final session from the verify response. Verify: pnpm --filter @carbon/auth typecheck && pnpm --filter @carbon/auth test.

Phase 3 — Login gate (ERP + MES)

Insert the gate at every setAuthSession call site that follows a fresh sign-in:

  • 3.1 ERP _public+/callback.tsx (action L95-107) — after refreshAccessToken succeeds: if hasVerifiedTotpFactor(userId) → setPendingMfaSession + redirect /mfa (carry redirectTo); else unchanged. Covers magic link + Google/Azure OAuth.
  • 3.2 ERP _public+/login.tsx — dev-bypass branch (L159-165): skip the gate (local dev only).
  • 3.3 ERP api+/passkey.authenticate.verify.ts — after signInWithPasskey: same gate. (Pending Open Question 1 — default: yes, challenge passkey logins too.)
  • 3.4 MES _public+/callback.tsx (action L41-99) — same gate, redirect to MES /mfa.
  • 3.5 ERP _public+/verify.tsx — no gate (new account, no factor possible). Add a comment saying so. Verify: pnpm exec turbo run typecheck --filter=erp --filter=mes.

Phase 4 — /mfa challenge route

  • 4.1 ERP apps/erp/app/routes/_public+/mfa.tsx (new) — modeled on verify.tsx:
    • Loader: getPendingMfaSession or redirect to /login.
    • Action: IP+userId rate limit (@carbon/kv Ratelimit.slidingWindow, same RATE_LIMIT pattern as login), validate code (zod .length(6)), look up verified factors, call verifyTotpChallenge(pendingTokens, factorId, code) → on success build final session → setAuthSession + setCompanyId, clear pending key, redirect to redirectTo (default path.to.authenticatedRoot). On failure: flash error, stay.
    • UI: ValidatedForm + <InputOTP name="code" />, "Open your authenticator app" copy, logout link ("Use a different account").
    • Multiple verified factors: try the first; iterate factors only if Supabase rejects (keep v1 simple — most users have one).
  • 4.2 MES apps/mes/app/routes/_public+/mfa.tsx — same shape, MES styling/paths.
  • 4.3 Path helpers — add mfa to apps/erp/app/utils/path.ts (and MES equivalent). Verify: typecheck both apps; manual login test in Phase 7.

Phase 5 — Enrollment UI (account settings)

  • 5.1 API routes apps/erp/app/routes/api+/mfa.enroll.ts + mfa.verify.ts + mfa.unenroll.ts (new, mirroring passkey.register.*): requirePermissions(request, {}), tokens from requireAuthSession, call the Phase-2 service. mfa.verify also re-issues the cookie from the AAL2 verify response (setAuthSession) in its response headers.
  • 5.2 Enrollment Card in apps/erp/app/routes/x+/account+/profile.tsx next to the Passkeys Card (L297-360 precedent): "Two-factor authentication" — list verified factors (friendly name, created date), Add button → Modal with QR SVG (dangerouslySetInnerHTML is NOT needed — enroll returns an SVG string; render via img with data:image/svg+xml;utf8, URI) + copyable secret + <InputOTP> confirm step; Remove → confirm dialog requiring a current code. Loader adds the factor list (user-scoped mfa.listFactors via seeded client).
  • 5.3 Admin recovery — People module (apps/erp/app/routes/x+/users+/employees area): "Reset two-factor authentication" action gated by role: "employee" + update: "users", calling adminDeleteTotpFactors. Pending Open Question 4. Verify: pnpm exec turbo run typecheck --filter=erp; pnpm run lint.

Phase 6 (optional, separate PR) — Company "require MFA" policy

Migration adding companySettings.requireMfa boolean not null default false; settings toggle; login gate extension: enrolled → challenge (as above); not enrolled + required → redirect to a forced-enrollment screen before entering the app. Needs pnpm run generate:types. Defer until v1 lands.

Phase 7 — Verification

  • Unit tests in packages/auth for pending-session helpers (TTL, key isolation from SESSION_KEY).
  • Manual e2e (with user's permission, /auth + /test skills): enroll with a TOTP generator (e.g. oathtool --totp -b <secret>), logout, login → challenge screen → wrong code rejected + rate limit, right code lands in app; unenroll; login again → no challenge.
  • pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/auth, pnpm run lint.

Docs/rules sync (same PR)

Update .claude/rules/authentication-system.md (new MFA section) and packages/auth/AGENTS.md (new ./mfa.server subpath).


Open Questions (answer before /execute)

  1. Passkey logins also challenged? Recommend yes for v1 consistency (Carbon passkey sign-in is a custom flow that lands at AAL1; exempting it means TOTP is bypassable by registering a passkey). Could exempt later as "phishing-resistant" with a real design.
  2. Enrollment UI location — card in existing profile.tsx (recommended, minimal) vs a new account/security page (move Passkeys there too — bigger diff).
  3. Stale sessions: sessions issued before a user enrolls stay valid (AAL1) up to the 7-day cookie life on other devices. Acceptable for v1? (Fix = store an aal flag + re-check factor status in requireAuthSession, at the cost of a Redis/admin-API call.)
  4. Admin recovery scope: factors are per auth user, global across companies. A user in two companies could have MFA reset by an admin of either. Options: allow (recommended v1, matches how user deactivation works) vs restrict to system admins.
  5. Editions/flag: available to all editions, or gate behind AUTH_PROVIDERS-style env / Cloud plan? Recommend: all editions, no flag.

Risks

  • auth-js internal-session gotcha (design section) — the single most likely implementation bug; the Phase-2 getUserAuthClient helper is the mitigation.
  • Cookie size: pending key adds a second payload to the carbon cookie during the challenge window only; payload ≈ existing session, well under 4KB total but verify in dev.
  • GoTrue clock skew: codes valid ±1 interval (30s); no action needed, but flaky local e2e can come from Docker clock drift.
  • enable_refresh_token_rotation + reuse interval 10s already configured — challengeAndVerify rotates tokens; the pending session's tokens are single-purpose and discarded after verify.