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.
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)
- Passkey logins ARE challenged (they land at AAL1).
- Enrollment UI lives in account settings — later moved to a dedicated
x+/account+/security.tsxalongside passkeys. - Active re-checking chosen for stale sessions:
AuthSession.mfaVerifiedflag + per-request Redis-cached factor lookup inrequireAuthSession, bouncing to/mfa. - Admin reset: any company admin with
update: "users"(People module modal route). - All editions, no feature flag.
Implementation deltas from the original plan
- Academy and starter also consume
requireAuthSession, so they got/mfaroutes too (no callback gate there — the active re-check bounces them on first use). - Challenge action logic centralized as
completeMfaChallengeinsession.server.tsinstead of four copies;makeAuthSessionexported with anmfaVerifiedoption. - Enrollment UI was later MOVED out of
profile.tsxinto a dedicatedx+/account+/security.tsxthat also owns passkeys (open question 2 revisited). - Phase 6 (org enforcement) WAS built, not deferred:
companySettings.requireMfa(20260816103045), a Settings → Company toggle, aCONTROLLED_ENVIRONMENToverride 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 theapi+/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_mfaRPC (20260816114512, gated on enforcement in20260816131807) backs a Two-Factor column on employee accounts. It could not be a column on theemployeesview — that view is SECURITY_INVOKER andauth.mfa_factorsis 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
/mfachallenge routes are85% duplicated (843 lines across erp/mes/ academy/starter). Extracting a shared challenge form + action helper is the main outstanding refactor. x+/account+/security.tsxis ~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
aalJWT 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): addGOTRUE_MFA_TOTP_ENROLL_ENABLED: "true",GOTRUE_MFA_TOTP_VERIFY_ENABLED: "true",GOTRUE_MFA_MAX_ENROLLED_FACTORS: 10. Verify:crbn up(user runs), thencurl $SUPABASE_URL/auth/v1/settings | jq .mfa_enabled. - 1.2 Hosted parity —
packages/database/supabase/config.toml: add[auth.mfa]max_enrolled_factors = 10and[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.serversubpath inpackages/auth/package.json, mirroring./passkey.server):getUserAuthClient(accessToken, refreshToken)— fresh anon client +auth.setSession(...); private helper.hasVerifiedTotpFactor(userId)→ boolean, andgetVerifiedTotpFactors(userId)— service roleauth.admin.mfa.listFactors({ userId }), filterfactor_type === 'totp' && status === 'verified'.enrollTotpFactor(tokens, friendlyName)→{ factorId, qrCode, secret, uri }.verifyTotpChallenge(tokens, factorId, code)→Result<SupabaseAuthSession>viamfa.challengeAndVerify; used by BOTH enrollment verify and login challenge.unenrollTotpFactor(tokens, factorId, code)— step-upchallengeAndVerifythenmfa.unenroll.adminDeleteTotpFactors(userId)— service roleauth.admin.mfa.deleteFactorper factor.- Unenrolled-factor cleanup:
enrollTotpFactorfirst deletes any stalestatus === '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-beAuthSession+redirectTo. Reject pending sessions older than 10 min (storecreatedAt, compare ingetPendingMfaSession). - 2.3 Export
makeAuthSession(currently private inauth.server.ts:129) or add a thinmakeSessionFromSupabase(session, companyId, companyGroupId)wrapper so/mfaroute 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) — afterrefreshAccessTokensucceeds: ifhasVerifiedTotpFactor(userId)→setPendingMfaSession+ redirect/mfa(carryredirectTo); 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— aftersignInWithPasskey: 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 onverify.tsx:- Loader:
getPendingMfaSessionor redirect to/login. - Action: IP+userId rate limit (
@carbon/kvRatelimit.slidingWindow, sameRATE_LIMITpattern as login), validatecode(zod.length(6)), look up verified factors, callverifyTotpChallenge(pendingTokens, factorId, code)→ on success build final session →setAuthSession+setCompanyId, clear pending key, redirect toredirectTo(defaultpath.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).
- Loader:
- 4.2 MES
apps/mes/app/routes/_public+/mfa.tsx— same shape, MES styling/paths. - 4.3 Path helpers — add
mfatoapps/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, mirroringpasskey.register.*):requirePermissions(request, {}), tokens fromrequireAuthSession, call the Phase-2 service.mfa.verifyalso 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.tsxnext to the Passkeys Card (L297-360 precedent): "Two-factor authentication" — list verified factors (friendly name, created date), Add button →Modalwith QR SVG (dangerouslySetInnerHTMLis NOT needed — enroll returns an SVG string; render viaimgwithdata:image/svg+xml;utf8,URI) + copyable secret +<InputOTP>confirm step; Remove → confirm dialog requiring a current code. Loader adds the factor list (user-scopedmfa.listFactorsvia seeded client). - 5.3 Admin recovery — People module (
apps/erp/app/routes/x+/users+/employeesarea): "Reset two-factor authentication" action gated byrole: "employee"+update: "users", callingadminDeleteTotpFactors. 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/authfor pending-session helpers (TTL, key isolation fromSESSION_KEY). - Manual e2e (with user's permission,
/auth+/testskills): 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)
- 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.
- Enrollment UI location — card in existing
profile.tsx(recommended, minimal) vs a newaccount/securitypage (move Passkeys there too — bigger diff). - 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
aalflag + re-check factor status inrequireAuthSession, at the cost of a Redis/admin-API call.) - 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.
- 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
getUserAuthClienthelper is the mitigation. - Cookie size: pending key adds a second payload to the
carboncookie 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.