Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: resolved a multi mfa setup failing error
=3b95cf3b63a1
diff --git a/backend/src/server/routes/mfa-step-up-fns.test.ts b/backend/src/server/routes/mfa-step-up-fns.test.tsindex a59bd26f0e..824664f603 100644--- a/backend/src/server/routes/mfa-step-up-fns.test.ts+++ b/backend/src/server/routes/mfa-step-up-fns.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test, vi } from "vitest";import { MfaMethod } from "@app/services/auth/auth-type";-import { ensureStepUpMfa, MfaStepUpResource } from "./mfa-step-up-fns";+import { ensureFactorEnrollmentStepUpMfa, ensureStepUpMfa, MfaStepUpResource } from "./mfa-step-up-fns";const USER_ID = "user-1";const ORG_ID = "org-1";@@ -138,3 +138,49 @@ describe("ensureStepUpMfa binds prior proof to the factors the action would chalexpect(mfaSession.isMfaSessionActive).not.toHaveBeenCalled();});});++describe("ensureFactorEnrollmentStepUpMfa", () => {+ const enrollmentArgs = { userId: USER_ID, tokenVersionId: TOKEN_VERSION };++ const withEnrollmentMethods = (enrollmentMethods: TResolved | null, patch: ServerPatch = {}) => {+ const built = makeServer(patch);+ Object.assign(built.user, {+ getFactorEnrollmentStepUpMfaMethods: vi.fn().mockResolvedValue(enrollmentMethods)+ });+ return built;+ };++ test("lets the first factor through without a challenge", async () => {+ const { server, mfaSession } = withEnrollmentMethods(null);++ await expect(ensureFactorEnrollmentStepUpMfa(server, enrollmentArgs)).resolves.toBeUndefined();+ expect(mfaSession.createMfaSession).not.toHaveBeenCalled();+ });++ test("challenges an existing factor without needing an org", async () => {+ const { server, mfaSession, user } = withEnrollmentMethods({+ challenge: MfaMethod.WEBAUTHN,+ accepted: [MfaMethod.WEBAUTHN, MfaMethod.TOTP]+ });++ await expect(ensureFactorEnrollmentStepUpMfa(server, enrollmentArgs)).rejects.toMatchObject({+ name: "SESSION_MFA_REQUIRED",+ details: { mfaMethod: MfaMethod.WEBAUTHN }+ });+ expect(user.getStepUpMfaMethod).not.toHaveBeenCalled();+ expect(mfaSession.hasRecentMfaAuth).toHaveBeenCalledWith(USER_ID, TOKEN_VERSION, [+ MfaMethod.WEBAUTHN,+ MfaMethod.TOTP+ ]);+ });++ test("a recent proof of any enrolled factor satisfies it", async () => {+ const { server, mfaSession } = withEnrollmentMethods(+ { challenge: MfaMethod.WEBAUTHN, accepted: [MfaMethod.WEBAUTHN, MfaMethod.TOTP] },+ { recentAuthMethod: MfaMethod.TOTP }+ );++ await expect(ensureFactorEnrollmentStepUpMfa(server, enrollmentArgs)).resolves.toBeUndefined();+ expect(mfaSession.createMfaSession).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.tsindex 19b9976d4d..ce96564ab7 100644--- a/backend/src/server/routes/mfa-step-up-fns.ts+++ b/backend/src/server/routes/mfa-step-up-fns.ts@@ -44,15 +44,17 @@ export const ensureStepUpMfa = async (mfaSessionId,message,mfaMethod: mfaMethodOverride,+ acceptedMfaMethods: acceptedMfaMethodsOverride,excludeMfaMethod}: {userId: string;- orgId: string;+ orgId?: string;tokenVersionId: string;resourceId: TMfaStepUpResource;mfaSessionId?: string;message: string;mfaMethod?: MfaMethod;+ acceptedMfaMethods?: MfaMethod[];excludeMfaMethod?: MfaMethod;}) => {@@ -63,7 +65,7 @@ export const ensureStepUpMfa = async (// Resolve the method first: a removal action may fall back to a substitute factor,// and a proof of that substitute must not unlock the other management actions.const { challenge: mfaMethod, accepted: acceptedMfaMethods } = mfaMethodOverride- ? { challenge: mfaMethodOverride, accepted: [mfaMethodOverride] }+ ? { challenge: mfaMethodOverride, accepted: acceptedMfaMethodsOverride ?? [mfaMethodOverride] }: await server.services.user.getStepUpMfaMethod(userId, orgId, excludeMfaMethod);if (@@ -107,3 +109,24 @@ export const ensureStepUpMfa = async (details: { mfaSessionId: newMfaSessionId, mfaMethod }});};++// Gates every route that starts or persists a new factor. Reachable from the org-less+// session login hands out before MFA, so it must never trust that session on its own.+// Verifying the challenge opens the management grace window, which is what lets the+// retried request through, so callers never pass the session id back.+export const ensureFactorEnrollmentStepUpMfa = async (+ server: FastifyZodProvider,+ { userId, tokenVersionId }: { userId: string; tokenVersionId: string }+) => {+ const mfaMethods = await server.services.user.getFactorEnrollmentStepUpMfaMethods(userId);+ if (!mfaMethods) return;++ await ensureStepUpMfa(server, {+ userId,+ tokenVersionId,+ resourceId: MfaStepUpResource.MfaManagement,+ message: "Verify with your existing two-factor method before adding a new one",+ mfaMethod: mfaMethods.challenge,+ acceptedMfaMethods: mfaMethods.accepted+ });+};diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.tsindex ee841aee1d..cc833f8a47 100644--- a/backend/src/server/routes/v1/user-router.ts+++ b/backend/src/server/routes/v1/user-router.ts@@ -9,7 +9,12 @@ import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimimport { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";-import { ensureStepUpMfa, getStepUpSessionId, MfaStepUpResource } from "../mfa-step-up-fns";+import {+ ensureFactorEnrollmentStepUpMfa,+ ensureStepUpMfa,+ getStepUpSessionId,+ MfaStepUpResource+} from "../mfa-step-up-fns";const SantizedUserSchema = UsersSchema.omit({hashedPassword: true@@ -269,6 +274,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {requireOrg: false}),handler: async (req) => {+ await ensureFactorEnrollmentStepUpMfa(server, {+ userId: req.permission.id,+ tokenVersionId: getStepUpSessionId(req)+ });return server.services.totp.registerUserTotp({userId: req.permission.id});@@ -296,6 +305,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {requireOrg: false}),handler: async (req) => {+ await ensureFactorEnrollmentStepUpMfa(server, {+ userId: req.permission.id,+ tokenVersionId: getStepUpSessionId(req)+ });return server.services.totp.verifyUserTotpConfig({userId: req.permission.id,totp: req.body.totp@@ -422,6 +435,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {requireOrg: false}),handler: async (req) => {+ await ensureFactorEnrollmentStepUpMfa(server, {+ userId: req.permission.id,+ tokenVersionId: getStepUpSessionId(req)+ });return server.services.webAuthn.generateRegistrationOptions({userId: req.permission.id});@@ -464,6 +481,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {requireOrg: false}),handler: async (req) => {+ await ensureFactorEnrollmentStepUpMfa(server, {+ userId: req.permission.id,+ tokenVersionId: getStepUpSessionId(req)+ });return server.services.webAuthn.verifyRegistrationResponse({userId: req.permission.id,registrationResponse: req.body.registrationResponse as RegistrationResponseJSON,diff --git a/backend/src/server/routes/v2/mfa-session-router.ts b/backend/src/server/routes/v2/mfa-session-router.tsindex 39e78ceabd..7683801d98 100644--- a/backend/src/server/routes/v2/mfa-session-router.ts+++ b/backend/src/server/routes/v2/mfa-session-router.ts@@ -6,6 +6,8 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";+// Org-less sessions are allowed because enrolling a factor at login is challenged before+// an org is selected. A session is already bound to its user and login session.export const registerMfaSessionRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -30,7 +32,7 @@ export const registerMfaSessionRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.JWT]),+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {if (req.auth.authMode !== AuthMode.JWT) {throw new UnauthorizedError({ message: "MFA session verification requires a user session" });@@ -67,7 +69,7 @@ export const registerMfaSessionRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.JWT]),+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {if (req.auth.authMode !== AuthMode.JWT) {throw new UnauthorizedError({ message: "MFA session status requires a user session" });diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.tsindex 74b92a45de..a94d61b997 100644--- a/backend/src/server/routes/v2/user-router.ts+++ b/backend/src/server/routes/v2/user-router.ts@@ -8,7 +8,12 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMethod, AuthMode, MfaMethod } from "@app/services/auth/auth-type";import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";-import { ensureStepUpMfa, getStepUpSessionId, MfaStepUpResource } from "../mfa-step-up-fns";+import {+ ensureFactorEnrollmentStepUpMfa,+ ensureStepUpMfa,+ getStepUpSessionId,+ MfaStepUpResource+} from "../mfa-step-up-fns";import { SanitizedUserSchema } from "../sanitizedSchemas";export const registerUserRouter = async (server: FastifyZodProvider) => {@@ -77,7 +82,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {// Enroll a factor: proves possession of the factor in-request and persists it.// Reachable pre-MFA (requireOrg:false) so the enforced-MFA onboarding flow can set- // up a factor at login. It NEVER mints recovery codes: those are issued only after+ // up a factor at login; an account that already has one must prove it first.+ // It NEVER mints recovery codes: those are issued only after// the org-required MFA is actually completed (on the first successful verifyMfaToken,// or via POST /me/mfa/activate from a full authenticated session). This keeps a// password-only, pre-MFA session from bootstrapping recovery codes.@@ -122,6 +128,11 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {},preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),handler: async (req) => {+ await ensureFactorEnrollmentStepUpMfa(server, {+ userId: req.permission.id,+ tokenVersionId: getStepUpSessionId(req)+ });+if (req.body.method === MfaMethod.TOTP) {await server.services.totp.verifyUserTotpConfig({userId: req.permission.id,diff --git a/backend/src/services/user/user-service.test.ts b/backend/src/services/user/user-service.test.tsindex 53226af3d7..b6a1767f51 100644--- a/backend/src/services/user/user-service.test.ts+++ b/backend/src/services/user/user-service.test.ts@@ -358,3 +358,60 @@ describe("getStepUpMfaMethod", () => {});});});++describe("getFactorEnrollmentStepUpMfaMethods", () => {+ test("lets an account with no factor enroll its first one unchallenged", async () => {+ const service = buildMfaService({+ memberOrgIds: [ENFORCED_ORG_ID],+ orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }]+ });++ await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toBeNull();+ });++ test("challenges an existing passkey before another one is added", async () => {+ const service = buildMfaService({+ userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.WEBAUTHN },+ passkeyCount: 1+ });++ await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({+ challenge: MfaMethod.WEBAUTHN,+ accepted: [MfaMethod.WEBAUTHN]+ });+ });++ test("challenges the preferred factor and accepts any enrolled one", async () => {+ const service = buildMfaService({+ userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },+ hasTotp: true,+ passkeyCount: 2+ });++ await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({+ challenge: MfaMethod.TOTP,+ accepted: [MfaMethod.WEBAUTHN, MfaMethod.TOTP]+ });+ });++ test("counts email as a factor when login already requires it", async () => {+ const service = buildMfaService({+ memberOrgIds: [ENFORCED_ORG_ID],+ orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.EMAIL }]+ });++ await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({+ challenge: MfaMethod.EMAIL,+ accepted: [MfaMethod.EMAIL]+ });+ });++ test("does not count email when SMTP cannot deliver a code", async () => {+ const service = buildMfaService({+ userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.EMAIL },+ smtp: false+ });++ await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toBeNull();+ });+});diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex 93c58d5860..36cc3b0f08 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -666,10 +666,13 @@ export const userServiceFactory = ({// substitute.const getStepUpMfaMethod = async (userId: string,- orgId: string,+ orgId: string | undefined,excludeMethod?: MfaMethod): Promise<{ challenge: MfaMethod; accepted: MfaMethod[] }> => {- const [user, sessionOrg] = await Promise.all([userDAL.findById(userId), orgDAL.findById(orgId)]);+ const [user, sessionOrg] = await Promise.all([+ userDAL.findById(userId),+ orgId ? orgDAL.findById(orgId) : undefined+ ]);const org =sessionOrg?.rootOrgId && sessionOrg.rootOrgId !== sessionOrg.id? await orgDAL.findById(sessionOrg.rootOrgId)@@ -689,6 +692,36 @@ export const userServiceFactory = ({return { challenge: replacement, accepted: [requiredMfaMethod, replacement] };};+ // Adding a factor must be proven with one the account already relies on, or a+ // password-only session could plant its own. Returns null for an account with none,+ // so enforced-MFA onboarding at login can still enroll the first one.+ const getFactorEnrollmentStepUpMfaMethods = async (+ userId: string+ ): Promise<{ challenge: MfaMethod; accepted: MfaMethod[] } | null> => {+ const user = await userDAL.findById(userId);+ if (!user) throw new NotFoundError({ message: "User not found" });++ const [hasPasskey, hasTotp, enforcingOrgs] = await Promise.all([+ isMfaMethodConfigured(user, MfaMethod.WEBAUTHN),+ isMfaMethodConfigured(user, MfaMethod.TOTP),+ findMfaEnforcingOrgs(userId)+ ]);+ const isEmailRequiredAtLogin =+ (user.isMfaEnabled && (user.selectedMfaMethod ?? MfaMethod.EMAIL) === MfaMethod.EMAIL) ||+ enforcingOrgs.some((org) => (org.selectedMfaMethod ?? MfaMethod.EMAIL) === MfaMethod.EMAIL);+ const hasEmail = isEmailRequiredAtLogin && (await isMfaMethodConfigured(user, MfaMethod.EMAIL));++ const accepted = [+ ...(hasPasskey ? [MfaMethod.WEBAUTHN] : []),+ ...(hasTotp ? [MfaMethod.TOTP] : []),+ ...(hasEmail ? [MfaMethod.EMAIL] : [])+ ];+ if (!accepted.length) return null;++ const preferred = accepted.find((method) => method === user.selectedMfaMethod);+ return { challenge: preferred ?? accepted[0], accepted };+ };+const deleteUser = async (userId: string) => {// If the deleting user is the only remaining server admin, block self-deletion.// The super_admin table's `initialized` flag is not reset on user delete, so@@ -894,6 +927,7 @@ export const userServiceFactory = ({deleteUser,getMe,getStepUpMfaMethod,+ getFactorEnrollmentStepUpMfaMethods,isStepUpMfaRequired,resolveMfaMethodAfterRemoval,assertMfaFactorRemovable,diff --git a/frontend/src/components/mfa/MfaSessionChallenge.tsx b/frontend/src/components/mfa/MfaSessionChallenge.tsxnew file mode 100644index 0000000000..3c0277cdac--- /dev/null+++ b/frontend/src/components/mfa/MfaSessionChallenge.tsx@@ -0,0 +1,137 @@+import { ComponentProps, useState } from "react";+import { startAuthentication } from "@simplewebauthn/browser";++import { Button, FieldError, VerificationCodeForm } from "@app/components/v3";+import { isMfaLockoutError } from "@app/helpers/mfaSession";+import { MfaMethod } from "@app/hooks/api/auth/types";+import { useVerifyMfaSession } from "@app/hooks/api/mfaSession";+import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/hooks/api/webauthn";++const MFA_CODE_LENGTH = 6;++export const MFA_CHALLENGE_PROMPTS: Record<MfaMethod, string> = {+ [MfaMethod.EMAIL]: "Enter the verification code sent to your email.",+ [MfaMethod.TOTP]: "Enter the verification code from your authenticator app.",+ [MfaMethod.WEBAUTHN]: "Use your registered passkey to continue."+};++type Props = {+ mfaSessionId: string;+ mfaMethod: MfaMethod;+ onVerified: () => void | Promise<void>;+ onLockout?: (message: string) => void;+ variant?: ComponentProps<typeof Button>["variant"];+};++export const MfaSessionChallenge = ({+ mfaSessionId,+ mfaMethod,+ onVerified,+ onLockout,+ variant = "project"+}: Props) => {+ const [mfaCode, setMfaCode] = useState("");+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [codeInputKey, setCodeInputKey] = useState(0);++ const verifyMfaSession = useVerifyMfaSession();+ const { mutateAsync: generateWebAuthnAuthenticationOptions } = useGenerateAuthenticationOptions();+ const { mutateAsync: verifyWebAuthnAuthentication } = useVerifyAuthentication();++ const handleLockout = (err: unknown) => {+ if (!onLockout || !isMfaLockoutError(err)) return false;+ onLockout(err.response.data.message);+ return true;+ };++ const handleVerifyCode = async () => {+ if (mfaCode.trim().length !== MFA_CODE_LENGTH) return;++ setIsLoading(true);+ setError(null);++ try {+ await verifyMfaSession.mutateAsync({+ mfaSessionId,+ mfaToken: mfaCode.trim(),+ mfaMethod+ });+ await onVerified();+ } catch (err: any) {+ if (handleLockout(err)) return;++ setError(err?.response?.data?.message || "Invalid MFA code. Please try again.");+ setMfaCode("");+ setCodeInputKey((key) => key + 1);+ } finally {+ setIsLoading(false);+ }+ };++ const handleVerifyPasskey = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const options = await generateWebAuthnAuthenticationOptions();+ const authenticationResponse = await startAuthentication({ optionsJSON: options });+ const result = await verifyWebAuthnAuthentication({ authenticationResponse });++ if (result.sessionToken) {+ await verifyMfaSession.mutateAsync({+ mfaSessionId,+ mfaToken: result.sessionToken,+ mfaMethod: MfaMethod.WEBAUTHN+ });+ await onVerified();+ }+ } catch (err: any) {+ if (handleLockout(err)) return;++ let errorMessage = "Failed to verify passkey";+ if (err.name === "NotAllowedError") {+ errorMessage = "Passkey verification was cancelled or timed out";+ } else if (err?.response?.data?.message) {+ errorMessage = err.response.data.message;+ } else if (err.message) {+ errorMessage = err.message;+ }++ setError(errorMessage);+ } finally {+ setIsLoading(false);+ }+ };++ if (mfaMethod === MfaMethod.WEBAUTHN) {+ return (+ <div className="flex flex-col gap-2">+ <Button+ size="lg"+ onClick={handleVerifyPasskey}+ isFullWidth+ variant={variant}+ isPending={isLoading}+ isDisabled={isLoading}+ >+ Authenticate with passkey+ </Button>+ {error && <FieldError>{error}</FieldError>}+ </div>+ );+ }++ return (+ <VerificationCodeForm+ key={codeInputKey}+ name="mfa-session-code"+ value={mfaCode}+ onChange={setMfaCode}+ onSubmit={() => handleVerifyCode()}+ submitVariant={variant}+ isPending={isLoading}+ error={error}+ />+ );+};diff --git a/frontend/src/components/mfa/setup/EnrollmentStepUp.tsx b/frontend/src/components/mfa/setup/EnrollmentStepUp.tsxnew file mode 100644index 0000000000..acec03d23c--- /dev/null+++ b/frontend/src/components/mfa/setup/EnrollmentStepUp.tsx@@ -0,0 +1,30 @@+import { ComponentProps } from "react";++import { Button } from "@app/components/v3";+import { TMfaStepUpChallenge } from "@app/helpers/mfaSession";++import { MFA_CHALLENGE_PROMPTS, MfaSessionChallenge } from "../MfaSessionChallenge";++type Props = {+ challenge: TMfaStepUpChallenge;+ onVerified: () => void | Promise<void>;+ variant?: ComponentProps<typeof Button>["variant"];+};++// Shown inline rather than in the step-up popup, because login-time enrollment runs+// before an org is selected and the popup's route requires one.+export const EnrollmentStepUp = ({ challenge, onVerified, variant }: Props) => (+ <div className="flex flex-col gap-4">+ <p className="text-sm text-muted">+ Verify with your existing two-factor method before adding a new one.{" "}+ {MFA_CHALLENGE_PROMPTS[challenge.mfaMethod]}+ </p>+ <MfaSessionChallenge+ key={challenge.mfaSessionId}+ mfaSessionId={challenge.mfaSessionId}+ mfaMethod={challenge.mfaMethod}+ onVerified={onVerified}+ variant={variant}+ />+ </div>+);diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsxindex 45eafc4248..b1bb6dff9e 100644--- a/frontend/src/components/mfa/setup/VerifyStep.tsx+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx@@ -12,10 +12,13 @@ import {Skeleton,VerificationCodeForm} from "@app/components/v3";+import { getMfaStepUpChallenge, TMfaStepUpChallenge } from "@app/helpers/mfaSession";import { MfaMethod } from "@app/hooks/api/auth/types";import { useEnrollMfa, useGetUserTotpRegistration } from "@app/hooks/api/users";import { useRegisterPasskey } from "@app/hooks/api/webauthn";+import { EnrollmentStepUp } from "./EnrollmentStepUp";+type Props = {method: MfaMethod;onVerified: () => void | Promise<void>;@@ -30,8 +33,17 @@ const TotpVerify = ({variant: Props["variant"];}) => {const [hasRegistered, setHasRegistered] = useState(false);- const { data: registration, isPending } = useGetUserTotpRegistration({ enabled: !hasRegistered });+ const {+ data: registration,+ isPending,+ error: registrationError,+ refetch: refetchRegistration+ } = useGetUserTotpRegistration({ enabled: !hasRegistered });const { mutateAsync: enrollMfa, isPending: isVerifying } = useEnrollMfa();+ const [enrollStepUpChallenge, setEnrollStepUpChallenge] = useState<TMfaStepUpChallenge | null>(+ null+ );+ const stepUpChallenge = enrollStepUpChallenge ?? getMfaStepUpChallenge(registrationError);const [qrCodeUrl, setQrCodeUrl] = useState("");const [totp, setTotp] = useState("");const [verificationError, setVerificationError] = useState<string>();@@ -51,13 +63,31 @@ const TotpVerify = ({await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });createNotification({ text: "Authenticator app configured", type: "success" });await onVerified();- } catch {+ } catch (error) {+ const challenge = getMfaStepUpChallenge(error);+ if (challenge) {+ setEnrollStepUpChallenge(challenge);+ return;+ }// The mutation's global error handler already surfaces the (more detailed)// failure toast; keep a local signal so the manual Retry action appears.setVerificationError("Invalid code. Please try again.");}};+ if (stepUpChallenge) {+ return (+ <EnrollmentStepUp+ challenge={stepUpChallenge}+ variant={variant}+ onVerified={async () => {+ setEnrollStepUpChallenge(null);+ if (registrationError) await refetchRegistration();+ }}+ />+ );+ }+if (isPending) {return (<div className="space-y-4" aria-label="Loading authenticator setup">@@ -110,7 +140,10 @@ const WebAuthnVerify = ({onVerified: Props["onVerified"];variant: Props["variant"];}) => {- const { registerPasskey, isRegistering } = useRegisterPasskey();+ const [stepUpChallenge, setStepUpChallenge] = useState<TMfaStepUpChallenge | null>(null);+ const { registerPasskey, isRegistering } = useRegisterPasskey({+ onStepUpRequired: setStepUpChallenge+ });const { mutateAsync: enrollMfa } = useEnrollMfa();const [name, setName] = useState("");@@ -127,6 +160,24 @@ const WebAuthnVerify = ({}};+ // Browsers only open the passkey prompt from a user gesture, so after the step-up+ // the user selects Register again instead of it retrying on its own.+ if (stepUpChallenge) {+ return (+ <EnrollmentStepUp+ challenge={stepUpChallenge}+ variant={variant}+ onVerified={() => {+ setStepUpChallenge(null);+ createNotification({+ text: "Verified. Select Register passkey to continue.",+ type: "success"+ });+ }}+ />+ );+ }+return (<div className="flex flex-col gap-4"><p className="text-sm text-muted">diff --git a/frontend/src/components/mfa/setup/index.ts b/frontend/src/components/mfa/setup/index.tsindex 3b43fb0b62..64b457073d 100644--- a/frontend/src/components/mfa/setup/index.ts+++ b/frontend/src/components/mfa/setup/index.ts@@ -1,3 +1,4 @@+export { EnrollmentStepUp } from "./EnrollmentStepUp";export { RecoveryCodesStep } from "./RecoveryCodesStep";export { RecoveryCodesView } from "./RecoveryCodesView";export { MFA_METHOD_ICONS, MFA_METHOD_LABELS } from "./types";diff --git a/frontend/src/helpers/mfaSession.ts b/frontend/src/helpers/mfaSession.tsindex 48314ba170..af4303ef94 100644--- a/frontend/src/helpers/mfaSession.ts+++ b/frontend/src/helpers/mfaSession.ts@@ -17,6 +17,17 @@ export const isMfaSessionError = (return error?.response?.data?.name === "SESSION_MFA_REQUIRED";};+export type TMfaStepUpChallenge = { mfaSessionId: string; mfaMethod: MfaMethod };++export const getMfaStepUpChallenge = (error: unknown): TMfaStepUpChallenge | null => {+ if (!axios.isAxiosError(error) || error.response?.data?.error !== "SESSION_MFA_REQUIRED") {+ return null;+ }+ const details = error.response.data.details as Partial<TMfaStepUpChallenge> | undefined;+ if (!details?.mfaSessionId || !details.mfaMethod) return null;+ return { mfaSessionId: details.mfaSessionId, mfaMethod: details.mfaMethod };+};+export const isMfaLockoutError = (error: any): error is { response: { data: { message: string } } } =>diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex d6eca1183c..da79ccbf06 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -4,6 +4,7 @@ import { AxiosError } from "axios";import { apiRequest } from "@app/config/request";import { SessionStorageKeys } from "@app/const";+import { getMfaStepUpChallenge } from "@app/helpers/mfaSession";import { adminQueryKeys } from "@app/hooks/api/admin/queries";import { getAuthToken, queryClient as qc } from "@app/hooks/api/reactQuery";@@ -495,7 +496,9 @@ export const useGetUserTotpRegistration = (options?: { enabled?: boolean }) => {return data;},- enabled: options?.enabled ?? true+ enabled: options?.enabled ?? true,+ // Retrying a step-up error would mint a second challenge and email a second code.+ retry: (failureCount, error) => !getMfaStepUpChallenge(error) && failureCount < 1});};diff --git a/frontend/src/hooks/api/webauthn/index.tsx b/frontend/src/hooks/api/webauthn/index.tsxindex 1db2260fc3..e58f405646 100644--- a/frontend/src/hooks/api/webauthn/index.tsx+++ b/frontend/src/hooks/api/webauthn/index.tsx@@ -1,6 +1,5 @@export {useGenerateAuthenticationOptions,- useGenerateRegistrationOptions,useUpdateWebAuthnCredential,useVerifyAuthentication,useVerifyRegistrationdiff --git a/frontend/src/hooks/api/webauthn/mutations.tsx b/frontend/src/hooks/api/webauthn/mutations.tsxindex b7581e8aac..7e35790920 100644--- a/frontend/src/hooks/api/webauthn/mutations.tsx+++ b/frontend/src/hooks/api/webauthn/mutations.tsx@@ -5,23 +5,12 @@ import { apiRequest } from "@app/config/request";import { webAuthnKeys } from "./queries";import {TGenerateAuthenticationOptionsResponse,- TGenerateRegistrationOptionsResponse,TUpdateWebAuthnCredentialDTO,TVerifyAuthenticationDTO,TVerifyRegistrationDTO,TVerifyRegistrationResponse} from "./types";-export const useGenerateRegistrationOptions = () =>- useMutation({- mutationFn: async () => {- const { data } = await apiRequest.post<TGenerateRegistrationOptionsResponse>(- "/api/v1/user/me/webauthn/register"- );- return data;- }- });-export const useVerifyRegistration = () => {const queryClient = useQueryClient();diff --git a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsxindex 8f8c8e0f10..55ce674f23 100644--- a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx+++ b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx@@ -2,8 +2,11 @@ import { useState } from "react";import { RegistrationResponseJSON, startRegistration } from "@simplewebauthn/browser";import { createNotification } from "@app/components/notifications";+import { apiRequest } from "@app/config/request";+import { getMfaStepUpChallenge, TMfaStepUpChallenge } from "@app/helpers/mfaSession";-import { useGenerateRegistrationOptions, useVerifyRegistration } from "./mutations";+import { useVerifyRegistration } from "./mutations";+import { TGenerateRegistrationOptionsResponse } from "./types";const DEFAULT_PASSKEY_NAME = "Passkey";@@ -12,11 +15,15 @@ type VerifyAttestation = (name: string) => Promise<void>;+type Options = {+ // An account that already has a factor must prove it before adding a passkey.+ onStepUpRequired: (challenge: TMfaStepUpChallenge) => void;+};+// Shared passkey registration flow (browser support guard -> options -> prompt ->// verify) with consistent success/error notifications. Returns true on success so// callers can chain follow-up work (e.g. advancing a wizard step).-export const useRegisterPasskey = () => {- const { mutateAsync: generateOptions } = useGenerateRegistrationOptions();+export const useRegisterPasskey = ({ onStepUpRequired }: Options) => {const { mutateAsync: verifyRegistration } = useVerifyRegistration();const [isRegistering, setIsRegistering] = useState(false);@@ -28,7 +35,11 @@ export const useRegisterPasskey = () => {setIsRegistering(true);try {- const options = await generateOptions();+ // Called directly rather than through a mutation so the expected step-up 400+ // does not raise the global mutation error toast.+ const { data: options } = await apiRequest.post<TGenerateRegistrationOptionsResponse>(+ "/api/v1/user/me/webauthn/register"+ );const registrationResponse = await startRegistration({ optionsJSON: options });const resolvedName = name?.trim() || DEFAULT_PASSKEY_NAME;if (verify) {@@ -39,6 +50,12 @@ export const useRegisterPasskey = () => {createNotification({ text: "Passkey registered", type: "success" });return true;} catch (error: any) {+ const stepUpChallenge = getMfaStepUpChallenge(error);+ if (stepUpChallenge) {+ onStepUpRequired(stepUpChallenge);+ return false;+ }+let text = "Failed to register passkey";if (error.name === "NotAllowedError")text = "Passkey registration was cancelled or timed out";diff --git a/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx b/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsxindex 01e7a54217..ef570f4569 100644--- a/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx+++ b/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx@@ -1,25 +1,16 @@-import { ReactNode, useEffect, useState } from "react";-import { startAuthentication } from "@simplewebauthn/browser";+import { ReactNode, useEffect } from "react";import { useParams } from "@tanstack/react-router";import { AuthPageLayout } from "@app/components/auth/AuthPageLayout";import { AuthPagePanel } from "@app/components/auth/AuthPagePanel";-import { createNotification } from "@app/components/notifications";-import {- Button,- CardContent,- FieldError,- VerificationCodeForm,- VerificationCodeHeader-} from "@app/components/v3";-import { isMfaLockoutError, stashMfaLockoutError } from "@app/helpers/mfaSession";-import { MfaMethod } from "@app/hooks/api/auth/types";import {- MfaSessionStatus,- useMfaSessionStatus,- useVerifyMfaSession-} from "@app/hooks/api/mfaSession";-import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/hooks/api/webauthn";+ MFA_CHALLENGE_PROMPTS,+ MfaSessionChallenge+} from "@app/components/mfa/MfaSessionChallenge";+import { createNotification } from "@app/components/notifications";+import { CardContent, VerificationCodeHeader } from "@app/components/v3";+import { stashMfaLockoutError } from "@app/helpers/mfaSession";+import { MfaSessionStatus, useMfaSessionStatus } from "@app/hooks/api/mfaSession";const MfaAuthPage = ({ children }: { children: ReactNode }) => (<AuthPageLayout variant="focused" showFooter={false}>@@ -27,144 +18,28 @@ const MfaAuthPage = ({ children }: { children: ReactNode }) => (</AuthPageLayout>);+const notifyAndClose = () => {+ createNotification({+ text: "MFA verification successful! Closing window...",+ type: "success"+ });++ setTimeout(() => {+ window.close();+ }, 1000);+};+export const MfaSessionPage = () => {const { mfaSessionId } = useParams({ strict: false }) as { mfaSessionId: string };- const [mfaCode, setMfaCode] = useState("");- const [isLoading, setIsLoading] = useState(false);- const [error, setError] = useState<string | null>(null);- const [codeInputKey, setCodeInputKey] = useState(0);-const { data: sessionStatus, isError: isStatusError } = useMfaSessionStatus(mfaSessionId);- const verifyMfaSession = useVerifyMfaSession();- const { mutateAsync: generateWebAuthnAuthenticationOptions } = useGenerateAuthenticationOptions();- const { mutateAsync: verifyWebAuthnAuthentication } = useVerifyAuthentication();- // Show notification and auto-close when MFA is completeduseEffect(() => {if (sessionStatus?.status === MfaSessionStatus.ACTIVE) {- createNotification({- text: "MFA verification successful! Closing window...",- type: "success"- });-- // Auto-close window after showing success message- setTimeout(() => {- window.close();- }, 1000);+ notifyAndClose();}}, [sessionStatus?.status]);- // Handle status error (session not found or expired)- useEffect(() => {- if (isStatusError) {- setError("MFA session not found or expired. Please try again.");- }- }, [isStatusError]);-- const getExpectedCodeLength = () => {- if (sessionStatus?.mfaMethod === MfaMethod.EMAIL) return 6;- if (sessionStatus?.mfaMethod === MfaMethod.TOTP) return 6;- return 6;- };-- const isCodeComplete = mfaCode.length === getExpectedCodeLength();-- const handleVerifyMfa = async () => {- if (!mfaCode.trim() || !isCodeComplete || !sessionStatus?.mfaMethod) return;-- setIsLoading(true);- setError(null);-- try {- await verifyMfaSession.mutateAsync({- mfaSessionId,- mfaToken: mfaCode.trim(),- mfaMethod: sessionStatus.mfaMethod- });-- createNotification({- text: "MFA verification successful! Closing window...",- type: "success"- });-- // Auto-close window after showing success message- setTimeout(() => {- window.close();- }, 1000);- } catch (err: any) {- if (isMfaLockoutError(err)) {- stashMfaLockoutError(mfaSessionId, err.response.data.message);- window.close();- return;- }-- setError(err?.response?.data?.message || "Invalid MFA code. Please try again.");- setMfaCode("");- setCodeInputKey((key) => key + 1);- } finally {- setIsLoading(false);- }- };-- const handleWebAuthnVerification = async () => {- if (!sessionStatus?.mfaMethod) return;-- setIsLoading(true);- setError(null);-- try {- // Get authentication options from server- const options = await generateWebAuthnAuthenticationOptions();-- // Prompt user to authenticate with their passkey- const authenticationResponse = await startAuthentication({ optionsJSON: options });-- // Verify with server to get session token- const result = await verifyWebAuthnAuthentication({ authenticationResponse });-- // Use the sessionToken to verify MFA session- if (result.sessionToken) {- await verifyMfaSession.mutateAsync({- mfaSessionId,- mfaToken: result.sessionToken,- mfaMethod: MfaMethod.WEBAUTHN- });-- createNotification({- text: "MFA verification successful! Closing window...",- type: "success"- });-- // Auto-close window after showing success message- setTimeout(() => {- window.close();- }, 1000);- }- } catch (err: any) {- if (isMfaLockoutError(err)) {- stashMfaLockoutError(mfaSessionId, err.response.data.message);- window.close();- return;- }-- console.error("WebAuthn verification failed:", err);-- let errorMessage = "Failed to verify passkey";- if (err.name === "NotAllowedError") {- errorMessage = "Passkey verification was cancelled or timed out";- } else if (err?.response?.data?.message) {- errorMessage = err.response.data.message;- } else if (err.message) {- errorMessage = err.message;- }-- setError(errorMessage);- } finally {- setIsLoading(false);- }- };-if (isStatusError) {return (<MfaAuthPage>@@ -199,44 +74,19 @@ export const MfaSessionPage = () => {<MfaAuthPage><VerificationCodeHeadertitle="Two-factor authentication"- description={- <>- {sessionStatus.mfaMethod === MfaMethod.EMAIL &&- "Enter the verification code sent to your email."}- {sessionStatus.mfaMethod === MfaMethod.TOTP &&- "Enter the verification code from your authenticator app."}- {sessionStatus.mfaMethod === MfaMethod.WEBAUTHN &&- "Use your registered passkey to continue."}- </>- }+ description={MFA_CHALLENGE_PROMPTS[sessionStatus.mfaMethod]}/><CardContent className="flex flex-col gap-5">- {sessionStatus.mfaMethod === MfaMethod.WEBAUTHN ? (- <div className="flex flex-col gap-2">- <Button- size="lg"- onClick={handleWebAuthnVerification}- isFullWidth- variant="project"- isPending={isLoading}- isDisabled={isLoading}- >- Authenticate with passkey- </Button>- {error && <FieldError>{error}</FieldError>}- </div>- ) : (- <VerificationCodeForm- key={codeInputKey}- name="mfa-session-code"- value={mfaCode}- onChange={setMfaCode}- onSubmit={() => handleVerifyMfa()}- isPending={isLoading}- error={error}- />- )}+ <MfaSessionChallenge+ mfaSessionId={mfaSessionId}+ mfaMethod={sessionStatus.mfaMethod}+ onVerified={notifyAndClose}+ onLockout={(message) => {+ stashMfaLockoutError(mfaSessionId, message);+ window.close();+ }}+ /></CardContent></MfaAuthPage>);diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsxindex dd675b64b9..faedf59303 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx@@ -1,6 +1,8 @@import { useState } from "react";import { FingerprintIcon, PlusIcon, TrashIcon, TriangleAlertIcon } from "lucide-react";+import { EnrollmentStepUp } from "@app/components/mfa/setup";+import { createNotification } from "@app/components/notifications";import {Alert,AlertDescription,@@ -24,6 +26,7 @@ import {SheetTitle,Skeleton} from "@app/components/v3";+import { TMfaStepUpChallenge } from "@app/helpers/mfaSession";import { useGetWebAuthnCredentials, useRegisterPasskey } from "@app/hooks/api/webauthn";import { useRemovePasskey } from "./useRemovePasskey";@@ -36,7 +39,10 @@ type Props = {export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {const { data, isPending, isError, refetch } = useGetWebAuthnCredentials();const credentials = data?.credentials ?? [];- const { registerPasskey, isRegistering } = useRegisterPasskey();+ const [stepUpChallenge, setStepUpChallenge] = useState<TMfaStepUpChallenge | null>(null);+ const { registerPasskey, isRegistering } = useRegisterPasskey({+ onStepUpRequired: setStepUpChallenge+ });const { removePasskey, isBusy: isRemoving } = useRemovePasskey();const [name, setName] = useState("");@@ -76,7 +82,13 @@ export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {return (<>- <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <Sheet+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) setStepUpChallenge(null);+ onOpenChange(open);+ }}+ ><SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg"><SheetHeader className="border-b"><SheetTitle>Manage passkeys</SheetTitle>@@ -96,11 +108,32 @@ export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {placeholder="New passkey name (optional)"/></Field>- <Button variant="neutral" isPending={isRegistering} onClick={handleAdd}>+ <Button+ variant="neutral"+ isPending={isRegistering}+ isDisabled={Boolean(stepUpChallenge)}+ onClick={handleAdd}+ ><PlusIcon /> Add</Button></div>+ {stepUpChallenge && (+ <div className="rounded-lg border border-border bg-container p-4">+ <EnrollmentStepUp+ challenge={stepUpChallenge}+ variant="neutral"+ onVerified={() => {+ setStepUpChallenge(null);+ createNotification({+ text: "Verified. Select Add to register your passkey.",+ type: "success"+ });+ }}+ />+ </div>+ )}+{hasSecurityKeyCredential && (<Alert variant="warning"><TriangleAlertIcon />