Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

enable mfa after mfa verification

Thiago Araujo da Silvacad7fae6bc6b
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
index 0453f61747..8f9e9284d0 100644
--- a/backend/src/server/routes/mfa-step-up-fns.ts
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -8,8 +8,7 @@ import { MfaMethod } from "@app/services/auth/auth-type";
// disabling MFA).
export const MfaStepUpResource = {
RecoveryCodes: "mfa-recovery-codes",
- DisableMfa: "mfa-disable",
- EnableMfa: "mfa-enable"
+ DisableMfa: "mfa-disable"
} as const;
export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
@@ -34,14 +33,12 @@ export const ensureStepUpMfa = async (
userId,
resourceId,
mfaSessionId,
- message,
- mfaMethod: mfaMethodOverride
+ message
}: {
userId: string;
resourceId: TMfaStepUpResource;
mfaSessionId?: string;
message: string;
- mfaMethod?: MfaMethod;
}
) => {
if (
@@ -56,7 +53,7 @@ export const ensureStepUpMfa = async (
}
const user = await server.services.user.getMe(userId);
- const mfaMethod = mfaMethodOverride ?? (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
+ const mfaMethod = (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId, resourceId, mfaMethod);
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index a1b1aafac5..4d8122e90a 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -65,10 +65,11 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
});
// Enroll a factor: proves possession of the factor in-request and persists it.
- // This does NOT mint recovery codes; those are issued only when MFA is enabled
- // (POST /me/mfa/activate). Because proving the factor here is itself proof of the
- // factor, a verified EnableMfa step-up session is minted and returned so the
- // enrollment wizard can immediately enable MFA without a redundant challenge.
+ // 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
+ // 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.
server.route({
method: "POST",
url: "/me/mfa/enroll",
@@ -106,9 +107,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
})
]),
response: {
- 200: z.object({
- mfaSessionId: z.string()
- })
+ 200: z.object({})
}
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
@@ -131,13 +130,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
});
}
- const mfaSessionId = await server.services.mfaSession.createVerifiedMfaSession(
- req.permission.id,
- MfaStepUpResource.EnableMfa,
- req.body.method
- );
-
- return { mfaSessionId };
+ return {};
}
});
@@ -167,12 +160,17 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
- // Enable MFA. Requires the selected method to be configured (email always is),
- // and issues a fresh recovery-code pool (invalidating any prior codes), returned
- // once so the client can surface them to the user. Because the user chooses the
- // method before enabling, enabling is gated behind a fresh step-up MFA challenge
- // against that method — this proves the user can actually satisfy the factor they
- // just turned on, so they can't lock themselves out.
+ // Enable MFA from a fully authenticated session (personal settings). Issues a
+ // fresh recovery-code pool (invalidating any prior codes), returned once so the
+ // client can surface them.
+ //
+ // Recovery codes bypass any org-required MFA method at login, so they must never
+ // be mintable by a session that has not itself completed that method. This route
+ // requires an org-scoped token (requireOrg:true): a token for an MFA-enforcing org
+ // can only exist after that org's MFA challenge was completed (see
+ // selectOrganization), so reaching this handler already proves the org-required
+ // method. The transient post-password no-org token used during login/onboarding
+ // is rejected here and cannot obtain recovery codes.
server.route({
method: "POST",
url: "/me/mfa/activate",
@@ -182,8 +180,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
schema: {
operationId: "activateUserMfa",
body: z.object({
- selectedMfaMethod: z.nativeEnum(MfaMethod).optional(),
- mfaSessionId: z.string().trim().optional()
+ selectedMfaMethod: z.nativeEnum(MfaMethod).optional()
}),
response: {
200: z.object({
@@ -192,16 +189,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
})
}
},
- preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ preHandler: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
- await ensureStepUpMfa(server, {
- userId: req.permission.id,
- resourceId: MfaStepUpResource.EnableMfa,
- mfaSessionId: req.body.mfaSessionId,
- mfaMethod: req.body.selectedMfaMethod,
- message: "MFA verification is required to enable two-factor authentication"
- });
-
const { user, recoveryCodes } = await server.services.user.activateMfa({
userId: req.permission.id,
selectedMfaMethod: req.body.selectedMfaMethod
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index b7416fe065..75eca8deae 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -1377,15 +1377,13 @@ export const authLoginServiceFactory = ({
if (shouldTriggerMfa) {
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
- const isPendingEmailEnrollment = requiredMfaMethod === MfaMethod.EMAIL && !user.isMfaEnabled;
-
const mfaToken = await issueMfaChallenge({
userId: user.id,
email: user.email,
authMethod: userAuthMethod,
requiredMfaMethod,
organizationId: rootOrg.id,
- sendEmailCode: !isPendingEmailEnrollment
+ sendEmailCode: true
});
return { isMfaEnabled: true, mfa: mfaToken, mfaMethod: requiredMfaMethod } as const;
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index 7900cc104b..d5cfbabb18 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -196,39 +196,12 @@ export const mfaSessionServiceFactory = ({
return mfaSessionId;
};
- // Mints a session that is already ACTIVE, for flows where the factor was just
- // proven in the same request (e.g. enrolling a factor proves possession of it),
- // so the caller can satisfy a step-up gate without a redundant second challenge.
- const createVerifiedMfaSession = async (
- userId: string,
- resourceId: string,
- mfaMethod: MfaMethod
- ): Promise<string> => {
- const mfaSessionId = crypto.randomBytes(32).toString("hex");
- const mfaSession: TMfaSession = {
- sessionId: mfaSessionId,
- userId,
- resourceId,
- status: MfaSessionStatus.ACTIVE,
- mfaMethod
- };
-
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.MfaSession(mfaSessionId),
- KeyStoreTtls.MfaSessionInSeconds,
- JSON.stringify(mfaSession)
- );
-
- return mfaSessionId;
- };
-
const deleteMfaSession = async (mfaSessionId: string) => {
await keyStore.deleteItem(KeyStorePrefixes.MfaSession(mfaSessionId));
};
return {
createMfaSession,
- createVerifiedMfaSession,
verifyMfaSession,
getMfaSessionStatus,
sendMfaCode,
diff --git a/frontend/src/components/auth/Mfa.tsx b/frontend/src/components/auth/Mfa.tsx
index 3e0ec7d8e8..41c4f23b06 100644
--- a/frontend/src/components/auth/Mfa.tsx
+++ b/frontend/src/components/auth/Mfa.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
import ReactCodeInput from "react-code-input";
import { startAuthentication } from "@simplewebauthn/browser";
import { Link, useNavigate } from "@tanstack/react-router";
@@ -10,7 +10,7 @@ import { createNotification } from "@app/components/notifications";
import SecurityClient from "@app/components/utilities/SecurityClient";
import { Button, Tooltip } from "@app/components/v2";
import { isInfisicalCloud } from "@app/helpers/platform";
-import { useLogoutUser, useSendMfaToken } from "@app/hooks/api";
+import { useActivateMfa, useLogoutUser, useSendMfaToken } from "@app/hooks/api";
import {
checkUserTotpMfa,
checkUserWebAuthnMfa,
@@ -22,6 +22,8 @@ import { getMfaTempToken } from "@app/hooks/api/reactQuery";
import { fetchUserDetails } from "@app/hooks/api/users/queries";
import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/hooks/api/webauthn";
+import { RecoveryCodesStep } from "../mfa/setup";
+
// The style for the verification code input
const codeInputProps = {
inputStyle: {
@@ -78,7 +80,10 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
const [triesLeft, setTriesLeft] = useState<number | undefined>(undefined);
const [shouldShowTotpRegistration, setShouldShowTotpRegistration] = useState(false);
const [shouldShowWebAuthnRegistration, setShouldShowWebAuthnRegistration] = useState(false);
- const [shouldShowEmailRegistration, setShouldShowEmailRegistration] = useState(false);
+ const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[] | null>(null);
+ const [hasSavedRecoveryCodes, setHasSavedRecoveryCodes] = useState(false);
+ const wasMfaEnabledRef = useRef(true);
+ const { mutateAsync: activateMfa } = useActivateMfa();
const logout = useLogoutUser();
const { mutateAsync: generateWebAuthnAuthenticationOptions } = useGenerateAuthenticationOptions();
@@ -87,6 +92,14 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
const sendMfaToken = useSendMfaToken();
useEffect(() => {
+ fetchUserDetails()
+ .then((user) => {
+ wasMfaEnabledRef.current = Boolean(user.isMfaEnabled);
+ })
+ .catch(() => {
+ // Keep the safe default (treat as enabled) so existing codes are never rotated.
+ });
+
if (method === MfaMethod.TOTP) {
checkUserTotpMfa().then((isVerified) => {
if (!isVerified) {
@@ -100,16 +113,6 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
setShouldShowWebAuthnRegistration(true);
}
});
- } else if (method === MfaMethod.EMAIL) {
- fetchUserDetails()
- .then((user) => {
- if (!user.isMfaEnabled) {
- setShouldShowEmailRegistration(true);
- }
- })
- .catch(() => {
- // If we can't determine enrollment state, fall back to the normal email challenge.
- });
}
}, [method]);
@@ -129,6 +132,13 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
return "Use authenticator code";
};
+ const completeLogin = async () => {
+ await successCallback();
+ if (closeMfa) {
+ closeMfa();
+ }
+ };
+
const verifyMfa = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -151,10 +161,13 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
SecurityClient.setMfaToken("");
SecurityClient.setToken(result.token);
- await successCallback();
- if (closeMfa) {
- closeMfa();
+ if (!showRecoveryCodeInput && !wasMfaEnabledRef.current) {
+ const { recoveryCodes } = await activateMfa({ selectedMfaMethod: method });
+ setNewRecoveryCodes(recoveryCodes);
+ return;
}
+
+ await completeLogin();
} catch {
if (typeof triesLeft === "number") {
const newTriesLeft = triesLeft - 1;
@@ -219,10 +232,13 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
SecurityClient.setMfaToken("");
SecurityClient.setToken(mfaResult.token);
- await successCallback();
- if (closeMfa) {
- closeMfa();
+ if (!wasMfaEnabledRef.current) {
+ const { recoveryCodes } = await activateMfa({ selectedMfaMethod: MfaMethod.WEBAUTHN });
+ setNewRecoveryCodes(recoveryCodes);
+ return;
}
+
+ await completeLogin();
}
} catch (error: any) {
console.error("WebAuthn verification failed:", error);
@@ -264,7 +280,37 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
}
};
- if (shouldShowTotpRegistration || shouldShowWebAuthnRegistration || shouldShowEmailRegistration) {
+ if (newRecoveryCodes) {
+ return (
+ <div className="mx-auto flex w-full max-w-md flex-col gap-4 pt-4 pb-4 md:mb-16 md:px-8">
+ <div className="text-center">
+ <h2 className="text-xl font-medium text-bunker-100">Save your recovery codes</h2>
+ <p className="mt-2 text-sm text-bunker-300">
+ Store these somewhere safe. Each code can be used once if you lose access to your second
+ factor. This is the only time they are shown.
+ </p>
+ </div>
+ <RecoveryCodesStep
+ recoveryCodes={newRecoveryCodes}
+ onSaved={() => setHasSavedRecoveryCodes(true)}
+ />
+ <Button
+ colorSchema="primary"
+ isFullWidth
+ isDisabled={!hasSavedRecoveryCodes}
+ isLoading={isLoading}
+ onClick={async () => {
+ setIsLoading(true);
+ await completeLogin();
+ }}
+ >
+ Continue
+ </Button>
+ </div>
+ );
+ }
+
+ if (shouldShowTotpRegistration || shouldShowWebAuthnRegistration) {
return (
<div className="mx-auto w-max pt-4 pb-4 md:mb-16 md:px-8">
<MfaEnrollment
@@ -272,7 +318,6 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
onComplete={async () => {
setShouldShowTotpRegistration(false);
setShouldShowWebAuthnRegistration(false);
- setShouldShowEmailRegistration(false);
await successCallback();
}}
/>
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index 46cd3b573e..04b2f2ed51 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -1,32 +1,24 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef } from "react";
-import { createNotification } from "@app/components/notifications";
import SecurityClient from "@app/components/utilities/SecurityClient";
-import { Button } from "@app/components/v3";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { getMfaTempToken } from "@app/hooks/api/reactQuery";
-import { useActivateMfa } from "@app/hooks/api/users";
-import { MFA_METHOD_LABELS, RecoveryCodesStep, VerifyStep } from "./setup";
+import { MFA_METHOD_LABELS, VerifyStep } from "./setup";
type Props = {
method: MfaMethod;
onComplete: () => void | Promise<void>;
};
-// Guided enrollment used when an org enforces MFA but the user has not yet set
-// up the required method (e.g. right after signup). Mirrors the settings wizard:
-// enroll the method (which proves the factor and mints recovery codes) -> enable
-// MFA -> save codes.
+// Guided factor setup shown at login when an org enforces MFA but the user has not
+// yet configured the required method (e.g. right after signup). It only enrolls the
+// factor (proves and persists it). It deliberately does NOT enable MFA or mint
+// recovery codes: those happen when the user completes the org MFA challenge next
+// (verifyMfaToken), so a pre-MFA session can never bootstrap recovery codes.
export const MfaEnrollment = ({ method, onComplete }: Props) => {
- const { mutateAsync: activateMfa } = useActivateMfa();
- const [phase, setPhase] = useState<"verify" | "recovery">("verify");
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
- const [hasSaved, setHasSaved] = useState(false);
const hasPrepared = useRef(false);
- const hasRecoveryCodes = recoveryCodes.length > 0;
-
useEffect(() => {
if (hasPrepared.current) return;
hasPrepared.current = true;
@@ -34,24 +26,7 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
SecurityClient.setMfaToken("");
}, []);
- const handleVerified = async (mfaSessionId?: string) => {
- try {
- const { recoveryCodes: codes } = await activateMfa({
- selectedMfaMethod: method,
- mfaSessionId
- });
- setRecoveryCodes(codes);
- setPhase("recovery");
- } catch (error: any) {
- createNotification({
- text: error?.response?.data?.message || "Failed to enable two-factor authentication",
- type: "error"
- });
- }
- };
-
- const handleContinue = async () => {
- // Restore the temp token so downstream MFA verification can proceed.
+ const handleVerified = async () => {
SecurityClient.setMfaToken(getMfaTempToken());
await onComplete();
};
@@ -65,21 +40,7 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
</p>
</div>
- {phase === "verify" && <VerifyStep method={method} onVerified={handleVerified} />}
-
- {phase === "recovery" && (
- <div className="flex flex-col gap-4">
- <RecoveryCodesStep recoveryCodes={recoveryCodes} onSaved={() => setHasSaved(true)} />
- <Button
- variant="org"
- isFullWidth
- isDisabled={hasRecoveryCodes && !hasSaved}
- onClick={handleContinue}
- >
- Continue
- </Button>
- </div>
- )}
+ <VerifyStep method={method} onVerified={handleVerified} />
</div>
);
};
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index 7bc6600b13..d9e83bec8e 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -15,7 +15,7 @@ import { useRegisterPasskey } from "@app/hooks/api/webauthn";
type Props = {
method: MfaMethod;
- onVerified: (mfaSessionId?: string) => void | Promise<void>;
+ onVerified: () => void | Promise<void>;
};
const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
@@ -36,9 +36,9 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- const { mfaSessionId } = await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
+ await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
createNotification({ text: "Authenticator app configured", type: "success" });
- await onVerified(mfaSessionId);
+ await onVerified();
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -104,9 +104,9 @@ const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- const { mfaSessionId } = await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
+ await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
createNotification({ text: "Email authentication configured", type: "success" });
- await onVerified(mfaSessionId);
+ await onVerified();
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -150,16 +150,15 @@ const WebAuthnVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) =>
const [name, setName] = useState("");
const handleRegister = async () => {
- let mfaSessionId: string | undefined;
const ok = await registerPasskey(name, async (registrationResponse, resolvedName) => {
- ({ mfaSessionId } = await enrollMfa({
+ await enrollMfa({
method: MfaMethod.WEBAUTHN,
registrationResponse,
name: resolvedName
- }));
+ });
});
if (ok) {
- await onVerified(mfaSessionId);
+ await onVerified();
}
};
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index f6af79ee0f..ba740224d7 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -424,11 +424,7 @@ export const useEnrollMfa = () => {
name?: string;
}
) => {
- const { data } = await apiRequest.post<{ mfaSessionId: string }>(
- "/api/v2/users/me/mfa/enroll",
- dto
- );
- return { mfaSessionId: data.mfaSessionId };
+ await apiRequest.post("/api/v2/users/me/mfa/enroll", dto);
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
@@ -454,18 +450,11 @@ export const useSendMfaEnrollmentEmailCode = () =>
export const useActivateMfa = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- selectedMfaMethod,
- mfaSessionId
- }: {
- selectedMfaMethod?: MfaMethod;
- mfaSessionId?: string;
- }) => {
+ mutationFn: async ({ selectedMfaMethod }: { selectedMfaMethod?: MfaMethod }) => {
const { data } = await apiRequest.post<{ user: unknown; recoveryCodes: string[] }>(
"/api/v2/users/me/mfa/activate",
{
- selectedMfaMethod,
- mfaSessionId
+ selectedMfaMethod
}
);
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index fbdeb87115..214fea32c2 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
@@ -26,7 +26,7 @@ import {
SheetHeader,
SheetTitle
} from "@app/components/v3";
-import { useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";
+import { useActivateMfa, useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { useGetUserTotpConfiguration } from "@app/hooks/api/users";
import { AuthMethod } from "@app/hooks/api/users/types";
@@ -35,14 +35,13 @@ import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
import { MfaMethodsCard } from "./MfaMethodsCard";
import { RecoveryOptionsCard } from "./RecoveryOptionsCard";
import { useDisableMfa } from "./useDisableMfa";
-import { useEnableMfa } from "./useEnableMfa";
const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";
export const MFASection = () => {
const { data: user, isPending } = useGetUser();
const { mutateAsync: setMfaMethod } = useSetMfaMethod();
- const { isBusy: isEnabling, enableMfa } = useEnableMfa();
+ const { mutateAsync: activateMfa, isPending: isEnabling } = useActivateMfa();
const { isBusy: isDisabling, disableMfa } = useDisableMfa();
const { data: totpConfiguration } = useGetUserTotpConfiguration();
const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
@@ -84,7 +83,17 @@ export const MFASection = () => {
// MFA is currently enabled.
const hasRecoveryCodes = user.isMfaEnabled;
- const handleEnable = () => enableMfa(selectedMethod, setNewRecoveryCodes);
+ const handleEnable = async () => {
+ try {
+ const { recoveryCodes } = await activateMfa({ selectedMfaMethod: selectedMethod });
+ setNewRecoveryCodes(recoveryCodes);
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to enable two-factor authentication",
+ type: "error"
+ });
+ }
+ };
const handlePreferredMethodChange = async (method: MfaMethod) => {
try {
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts
deleted file mode 100644
index 3b3bf17701..0000000000
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useCallback } from "react";
-import { useQueryClient } from "@tanstack/react-query";
-
-import { createNotification } from "@app/components/notifications";
-import { apiRequest } from "@app/config/request";
-import { MfaMethod } from "@app/hooks/api/auth/types";
-import { userKeys } from "@app/hooks/api/users/query-keys";
-
-import { useMfaStepUp } from "./useMfaStepUp";
-
-/**
- * Enabling MFA turns on a second factor the user selected beforehand, so it is
- * gated behind a fresh step-up MFA challenge against that method. This proves the
- * user can actually satisfy the factor they are about to enforce (so they can't
- * lock themselves out) and mirrors the disable flow. It calls apiRequest directly
- * (rather than a mutation) so the expected SESSION_MFA_REQUIRED 400 doesn't surface
- * a global mutation error toast. The fresh recovery codes are handed back to the
- * caller so they can be shown once.
- */
-export const useEnableMfa = () => {
- const queryClient = useQueryClient();
- const { isBusy, runWithMfa } = useMfaStepUp();
-
- const enableMfa = useCallback(
- (selectedMfaMethod: MfaMethod, onEnabled?: (recoveryCodes: string[]) => void) =>
- runWithMfa(
- async (mfaSessionId) => {
- const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(
- "/api/v2/users/me/mfa/activate",
- { selectedMfaMethod, ...(mfaSessionId ? { mfaSessionId } : {}) }
- );
- return data.recoveryCodes;
- },
- {
- onSuccess: (recoveryCodes) => {
- queryClient.invalidateQueries({ queryKey: userKeys.getUser });
- queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });
- createNotification({
- text: "Two-factor authentication enabled",
- type: "success"
- });
- onEnabled?.(recoveryCodes);
- },
- errorText: "Failed to enable two-factor authentication"
- }
- ),
- [runWithMfa, queryClient]
- );
-
- return { isBusy, enableMfa };
-};