Skip to content

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

change UI

Thiago Araujo da Silvad7f346ba1e93
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a0d08f4111..594d1a483a 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -125,6 +125,7 @@ export const KeyStorePrefixes = {
EmailSignupOtpHash: (hash: string) => `email-signup-otp:${hash}:hash` as const,
EmailSignupOtpLock: (hash: string) => `email-signup-otp:${hash}:lock` as const,
EmailSignupResendCooldown: (hash: string) => `email-signup-otp:${hash}:cd` as const,
+ MfaEmailSetupResendCooldown: (userId: string) => `mfa-email-setup:${userId}:cd` as const,
InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,
AdminConfig: "infisical-admin-cfg",
@@ -164,6 +165,7 @@ export const KeyStoreTtls = {
RefreshTokenGraceInSeconds: 10,
EmailSignupOtpInSeconds: 300, // 5 minutes
EmailSignupResendCooldownInSeconds: 60, // 1 minute
+ MfaEmailSetupResendCooldownInSeconds: 60, // 1 minute
InsightsCacheInSeconds: 300, // 5 minutes
InsightsDuplicationCacheInSeconds: 3600, // 1 hour
AdminConfigInSeconds: 60,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e983077e16..bca91e2bfd 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1174,6 +1174,9 @@ export const registerRoutes = async (
smtpService,
userAliasDAL,
membershipUserDAL,
+ totpConfigDAL,
+ webAuthnCredentialDAL,
+ keyStore,
mfaRecoveryCodeService
});
@@ -1181,16 +1184,14 @@ export const registerRoutes = async (
totpConfigDAL,
userDAL,
kmsService,
- keyStore,
- mfaRecoveryCodeService
+ keyStore
});
const webAuthnService = webAuthnServiceFactory({
webAuthnCredentialDAL,
userDAL,
tokenService,
- keyStore,
- mfaRecoveryCodeService
+ keyStore
});
const loginService = authLoginServiceFactory({
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 918084eea4..b87383e77e 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -206,8 +206,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
operationId: "getUserTotpConfig",
response: {
200: z.object({
- isVerified: z.boolean(),
- recoveryCodes: z.string().array()
+ isVerified: z.boolean()
})
}
},
@@ -246,8 +245,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
operationId: "registerUserTotp",
response: {
200: z.object({
- otpUrl: z.string(),
- recoveryCodes: z.string().array()
+ otpUrl: z.string()
})
}
},
@@ -274,7 +272,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- recoveryCodes: z.string().array()
+ success: z.boolean()
})
}
},
@@ -289,7 +287,6 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
- // Account-level MFA recovery codes (shared across TOTP and WebAuthn/passkey)
server.route({
method: "GET",
url: "/me/mfa/recovery-codes",
@@ -336,6 +333,56 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/me/mfa/email/send",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "sendEmailMfaSetupCode",
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ await server.services.user.sendEmailMfaSetupCode({
+ userId: req.permission.id
+ });
+ return { message: "Successfully sent email verification code" };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/me/mfa/email/verify",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "verifyEmailMfaSetupCode",
+ body: z.object({
+ code: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ success: z.boolean()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ await server.services.user.verifyEmailMfaSetupCode({
+ userId: req.permission.id,
+ code: req.body.code
+ });
+ return { success: true };
+ }
+ });
+
// WebAuthn/Passkey Routes
server.route({
method: "GET",
@@ -419,8 +466,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
credentialId: z.string(),
- name: z.string().nullable().optional(),
- recoveryCodes: z.string().array()
+ name: z.string().nullable().optional()
})
}
},
diff --git a/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts b/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts
index ac0ae67730..084f0808e2 100644
--- a/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts
+++ b/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts
@@ -6,7 +6,6 @@ import { TMfaRecoveryCodeDALFactory } from "./mfa-recovery-code-dal";
import { generateRecoveryCode } from "./mfa-recovery-code-fns";
import {
TDeleteRecoveryCodesDTO,
- TEnsureRecoveryCodesDTO,
TGetRecoveryCodesDTO,
TRotateRecoveryCodesDTO,
TVerifyAndConsumeRecoveryCodeDTO
@@ -36,27 +35,6 @@ export const mfaRecoveryCodeServiceFactory = ({
return { recoveryCodes, encryptedRecoveryCodes };
};
- /**
- * Ensures the user has an account-level recovery code pool. Idempotent: if a
- * pool already exists (e.g. from a prior TOTP setup) the existing codes are
- * returned unchanged; otherwise a fresh pool of codes is generated.
- * Called from both TOTP and passkey registration.
- */
- const ensureRecoveryCodes = async ({ userId }: TEnsureRecoveryCodesDTO) => {
- const decryptWithRoot = kmsService.decryptWithRootKey();
-
- return mfaRecoveryCodeDAL.transaction(async (tx) => {
- const existing = await mfaRecoveryCodeDAL.findOne({ userId }, tx);
- if (existing) {
- return decryptWithRoot(existing.encryptedRecoveryCodes).toString().split(",");
- }
-
- const { recoveryCodes, encryptedRecoveryCodes } = generateEncryptedRecoveryCodes();
- await mfaRecoveryCodeDAL.create({ userId, encryptedRecoveryCodes }, tx);
- return recoveryCodes;
- });
- };
-
const getRecoveryCodes = async ({ userId }: TGetRecoveryCodesDTO) => {
const recoveryCodeConfig = await mfaRecoveryCodeDAL.findOne({ userId });
@@ -67,9 +45,6 @@ export const mfaRecoveryCodeServiceFactory = ({
}
const decryptWithRoot = kmsService.decryptWithRootKey();
- // Once every code is consumed the stored value is the empty string, which
- // split(",") turns into [""]. Filter out empties so an exhausted pool
- // reads as [] rather than a single blank code.
const recoveryCodes = decryptWithRoot(recoveryCodeConfig.encryptedRecoveryCodes)
.toString()
.split(",")
@@ -145,7 +120,6 @@ export const mfaRecoveryCodeServiceFactory = ({
};
return {
- ensureRecoveryCodes,
getRecoveryCodes,
verifyAndConsumeRecoveryCode,
rotateRecoveryCodes,
diff --git a/backend/src/services/mfa-recovery-code/mfa-recovery-code-types.ts b/backend/src/services/mfa-recovery-code/mfa-recovery-code-types.ts
index 854a759a6a..3403ea99fc 100644
--- a/backend/src/services/mfa-recovery-code/mfa-recovery-code-types.ts
+++ b/backend/src/services/mfa-recovery-code/mfa-recovery-code-types.ts
@@ -1,7 +1,3 @@
-export type TEnsureRecoveryCodesDTO = {
- userId: string;
-};
-
export type TGetRecoveryCodesDTO = {
userId: string;
};
diff --git a/backend/src/services/totp/totp-service.ts b/backend/src/services/totp/totp-service.ts
index 581a26a883..b8e9b98dc0 100644
--- a/backend/src/services/totp/totp-service.ts
+++ b/backend/src/services/totp/totp-service.ts
@@ -4,7 +4,6 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TKmsServiceFactory } from "../kms/kms-service";
-import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";
import { TUserDALFactory } from "../user/user-dal";
import { TTotpConfigDALFactory } from "./totp-config-dal";
import {
@@ -20,20 +19,13 @@ type TTotpServiceFactoryDep = {
totpConfigDAL: TTotpConfigDALFactory;
kmsService: TKmsServiceFactory;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
- mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "ensureRecoveryCodes" | "getRecoveryCodes">;
};
authenticator.options = { window: 1 };
export type TTotpServiceFactory = ReturnType<typeof totpServiceFactory>;
-export const totpServiceFactory = ({
- totpConfigDAL,
- kmsService,
- userDAL,
- keyStore,
- mfaRecoveryCodeService
-}: TTotpServiceFactoryDep) => {
+export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStore }: TTotpServiceFactoryDep) => {
const getUserTotpConfig = async ({ userId }: TGetUserTotpConfigDTO) => {
const totpConfig = await totpConfigDAL.findOne({
userId
@@ -51,11 +43,8 @@ export const totpServiceFactory = ({
});
}
- const recoveryCodes = await mfaRecoveryCodeService.getRecoveryCodes({ userId });
-
return {
- isVerified: totpConfig.isVerified,
- recoveryCodes
+ isVerified: totpConfig.isVerified
};
};
@@ -97,9 +86,6 @@ export const totpServiceFactory = ({
return newTotpConfig;
});
- // Recovery codes are account-level and shared across MFA methods.
- const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });
-
const user = await userDAL.findById(userId);
const decryptWithRoot = kmsService.decryptWithRootKey();
@@ -107,8 +93,7 @@ export const totpServiceFactory = ({
const otpUrl = authenticator.keyuri(user.username, "Infisical", secret);
return {
- otpUrl,
- recoveryCodes
+ otpUrl
};
};
@@ -146,9 +131,8 @@ export const totpServiceFactory = ({
isVerified: true
});
- const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });
return {
- recoveryCodes
+ success: true
};
};
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 14e4042793..fd308d0b97 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -4,6 +4,7 @@ import { Knex } from "knex";
import { AccessScope, OrganizationActionScope } from "@app/db/schemas";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
@@ -18,7 +19,9 @@ import { ActorType, AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType } from
import { TGroupProjectDALFactory } from "../group-project/group-project-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";
+import { TTotpConfigDALFactory } from "../totp/totp-config-dal";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
+import { TWebAuthnCredentialDALFactory } from "../webauthn/webauthn-credential-dal";
import { TUserDALFactory } from "./user-dal";
import { TListUserGroupsDTO, TUpdateUserEmailDTO, TUpdateUserMfaDTO, TVerifyCurrentEmailOTPDTO } from "./user-types";
@@ -45,7 +48,10 @@ type TUserServiceFactoryDep = {
smtpService: Pick<TSmtpService, "sendMail">;
permissionService: TPermissionServiceFactory;
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById" | "delete">;
- mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "deleteRecoveryCodes" | "ensureRecoveryCodes">;
+ totpConfigDAL: Pick<TTotpConfigDALFactory, "delete">;
+ webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "delete">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "ttl">;
+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "deleteRecoveryCodes" | "rotateRecoveryCodes">;
};
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
@@ -59,6 +65,9 @@ export const userServiceFactory = ({
smtpService,
permissionService,
userAliasDAL,
+ totpConfigDAL,
+ webAuthnCredentialDAL,
+ keyStore,
mfaRecoveryCodeService
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
@@ -103,6 +112,26 @@ export const userServiceFactory = ({
if (!user || !user.email) throw new BadRequestError({ name: "Failed to toggle MFA" });
+ const wasMfaEnabled = user.isMfaEnabled;
+
+ // MFA cannot be turned off while any organization the user belongs to enforces
+ // it — doing so would lock them out of that org on the next login.
+ if (isMfaEnabled === false) {
+ const userOrgMemberships = await membershipUserDAL.find({
+ actorUserId: userId,
+ scope: AccessScope.Organization
+ });
+ if (userOrgMemberships.length) {
+ const orgIds = userOrgMemberships.map((membership) => membership.scopeOrgId);
+ const organizations = await orgDAL.find({ $in: { id: orgIds } });
+ if (organizations.some((org) => org.enforceMfa)) {
+ throw new ForbiddenRequestError({
+ message: "Two-factor authentication is required by your organization and cannot be disabled"
+ });
+ }
+ }
+ }
+
let mfaMethods;
if (isMfaEnabled === undefined) {
mfaMethods = undefined;
@@ -116,18 +145,68 @@ export const userServiceFactory = ({
selectedMfaMethod
});
- // Recovery codes are account-level and tied to MFA being enabled, not to any
- // specific method. Provision the pool as soon as MFA is turned on, and clear
- // it when MFA is turned off so no usable codes are left behind.
- if (isMfaEnabled === true) {
- await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });
+ if (isMfaEnabled === true && !wasMfaEnabled) {
+ await mfaRecoveryCodeService.rotateRecoveryCodes({ userId });
} else if (isMfaEnabled === false) {
- await mfaRecoveryCodeService.deleteRecoveryCodes({ userId });
+ await Promise.all([
+ mfaRecoveryCodeService.deleteRecoveryCodes({ userId }),
+ totpConfigDAL.delete({ userId }),
+ webAuthnCredentialDAL.delete({ userId })
+ ]);
}
return updatedUser;
};
+ // Sends a one-time code to the account email so the user can prove control of
+ // the inbox while adding email as a second factor from account settings.
+ const sendEmailMfaSetupCode = async ({ userId }: { userId: string }) => {
+ const user = await userDAL.findById(userId);
+ if (!user || !user.email) throw new BadRequestError({ message: "No email address is set on this account" });
+
+ const cooldownKey = KeyStorePrefixes.MfaEmailSetupResendCooldown(userId);
+ const acquired = await keyStore.setItemWithExpiryNX(
+ cooldownKey,
+ KeyStoreTtls.MfaEmailSetupResendCooldownInSeconds,
+ "1"
+ );
+ if (!acquired) {
+ const remaining = await keyStore.ttl(cooldownKey);
+ throw new BadRequestError({
+ message: "Please wait before requesting another code",
+ details: { cooldownSeconds: Math.max(1, remaining) }
+ });
+ }
+
+ const code = await tokenService.createTokenForUser({
+ type: TokenType.TOKEN_EMAIL_MFA,
+ userId
+ });
+
+ await smtpService.sendMail({
+ template: SmtpTemplates.EmailMfa,
+ subjectLine: "Infisical MFA code",
+ recipients: [user.email],
+ substitutions: {
+ code
+ }
+ });
+ };
+
+ // Verifies the email setup code so the caller can confirm the method works
+ // before enabling account MFA (which mints the recovery codes).
+ const verifyEmailMfaSetupCode = async ({ userId, code }: { userId: string; code: string }) => {
+ try {
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_MFA,
+ userId,
+ code
+ });
+ } catch (error) {
+ throw new BadRequestError({ message: "Invalid verification code" });
+ }
+ };
+
const updateUserName = async (userId: string, firstName: string, lastName: string) => {
const updatedUser = await userDAL.updateById(userId, {
firstName,
@@ -555,6 +634,8 @@ export const userServiceFactory = ({
return {
sendEmailVerificationCode,
updateUserMfa,
+ sendEmailMfaSetupCode,
+ verifyEmailMfaSetupCode,
updateUserName,
updateAuthMethods,
requestEmailChangeOTP,
diff --git a/backend/src/services/webauthn/webauthn-service.ts b/backend/src/services/webauthn/webauthn-service.ts
index 713a51175d..8648d17862 100644
--- a/backend/src/services/webauthn/webauthn-service.ts
+++ b/backend/src/services/webauthn/webauthn-service.ts
@@ -14,7 +14,6 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
-import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";
import { TUserDALFactory } from "../user/user-dal";
import { TWebAuthnCredentialDALFactory } from "./webauthn-credential-dal";
import {
@@ -32,7 +31,6 @@ type TWebAuthnServiceFactoryDep = {
webAuthnCredentialDAL: TWebAuthnCredentialDALFactory;
tokenService: TAuthTokenServiceFactory;
keyStore: TKeyStoreFactory;
- mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "ensureRecoveryCodes">;
};
export type TWebAuthnServiceFactory = ReturnType<typeof webAuthnServiceFactory>;
@@ -41,8 +39,7 @@ export const webAuthnServiceFactory = ({
userDAL,
webAuthnCredentialDAL,
tokenService,
- keyStore,
- mfaRecoveryCodeService
+ keyStore
}: TWebAuthnServiceFactoryDep) => {
const storeChallenge = async (userId: string, challenge: string) => {
const challengeKey = KeyStorePrefixes.WebAuthnChallenge(userId);
@@ -181,15 +178,9 @@ export const webAuthnServiceFactory = ({
// Clear the challenge
await clearChallenge(userId);
- // Ensure the user has account-level recovery codes as a passkey fallback.
- // Idempotent: only the first registered passkey (or a pre-existing TOTP
- // setup) generates codes; subsequent passkeys reuse the same pool.
- const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });
-
return {
credentialId: credential.credentialId,
- name: credential.name,
- recoveryCodes
+ name: credential.name
};
};
diff --git a/frontend/src/components/auth/Mfa.tsx b/frontend/src/components/auth/Mfa.tsx
index ea0aa69a22..f27b727b0f 100644
--- a/frontend/src/components/auth/Mfa.tsx
+++ b/frontend/src/components/auth/Mfa.tsx
@@ -1,15 +1,14 @@
import React, { useEffect, useState } from "react";
import ReactCodeInput from "react-code-input";
-import { startAuthentication, startRegistration } from "@simplewebauthn/browser";
+import { startAuthentication } from "@simplewebauthn/browser";
import { Link, useNavigate } from "@tanstack/react-router";
import { t } from "i18next";
import Error from "@app/components/basic/Error";
-import { RecoveryCodesDownload } from "@app/components/mfa/RecoveryCodesDownload";
-import TotpRegistration from "@app/components/mfa/TotpRegistration";
+import { MfaEnrollment } from "@app/components/mfa/MfaEnrollment";
import { createNotification } from "@app/components/notifications";
import SecurityClient from "@app/components/utilities/SecurityClient";
-import { Button, Input, Tooltip } from "@app/components/v2";
+import { Button, Tooltip } from "@app/components/v2";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useLogoutUser, useSendMfaToken } from "@app/hooks/api";
import {
@@ -20,12 +19,7 @@ import {
} from "@app/hooks/api/auth/queries";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { getMfaTempToken } from "@app/hooks/api/reactQuery";
-import {
- useGenerateAuthenticationOptions,
- useGenerateRegistrationOptions,
- useVerifyAuthentication,
- useVerifyRegistration
-} from "@app/hooks/api/webauthn";
+import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/hooks/api/webauthn";
// The style for the verification code input
const codeInputProps = {
@@ -83,17 +77,12 @@ 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 [credentialName, setCredentialName] = useState("");
- const [isRegisteringPasskey, setIsRegisteringPasskey] = useState(false);
- const [registrationRecoveryCodes, setRegistrationRecoveryCodes] = useState<string[]>([]);
const logout = useLogoutUser();
const { mutateAsync: generateWebAuthnAuthenticationOptions } = useGenerateAuthenticationOptions();
const { mutateAsync: verifyWebAuthnAuthentication } = useVerifyAuthentication();
const sendMfaToken = useSendMfaToken();
- const generateRegistrationOptions = useGenerateRegistrationOptions();
- const verifyRegistration = useVerifyRegistration();
useEffect(() => {
if (method === MfaMethod.TOTP) {
@@ -263,142 +252,18 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop
}
};
- const handleRegisterPasskey = async () => {
- try {
- setIsRegisteringPasskey(true);
-
- // Check if WebAuthn is supported
- if (
- !window.PublicKeyCredential ||
- !window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
- ) {
- createNotification({
- text: "WebAuthn is not supported on this browser",
- type: "error"
- });
- return;
- }
-
- // Check if platform authenticator is available
- const available =
- await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
- if (!available) {
- createNotification({
- text: "No passkey-compatible authenticator found on this device",
- type: "error"
- });
- return;
- }
-
- // Temporarily clear MFA token so the regular access token is used for registration endpoints
- const mfaToken = getMfaTempToken();
- SecurityClient.setMfaToken("");
-
- try {
- // Generate registration options from server (using regular user endpoint)
- const options = await generateRegistrationOptions.mutateAsync();
- const registrationResponse = await startRegistration({ optionsJSON: options });
-
- // Verify registration with server (using regular user endpoint)
- const { recoveryCodes } = await verifyRegistration.mutateAsync({
- registrationResponse,
- name: credentialName || "Passkey"
- });
-
- createNotification({
- text: "Successfully registered passkey",
- type: "success"
- });
-
- // Surface account-level recovery codes generated on first passkey so the
- // user can save them before continuing. If none were returned (a pool
- // already existed), proceed immediately.
- if (recoveryCodes && recoveryCodes.length > 0) {
- setRegistrationRecoveryCodes(recoveryCodes);
- } else {
- setShouldShowWebAuthnRegistration(false);
- await successCallback();
- }
- } finally {
- // Restore MFA token
- SecurityClient.setMfaToken(mfaToken);
- }
- } catch (error: any) {
- console.error("Failed to register passkey:", error);
-
- let errorMessage = "Failed to register passkey";
- if (error.name === "NotAllowedError") {
- errorMessage = "Passkey registration was cancelled or timed out";
- } else if (error.name === "InvalidStateError") {
- errorMessage = "This passkey has already been registered";
- } else if (error.message) {
- errorMessage = error.message;
- }
-
- createNotification({
- text: errorMessage,
- type: "error"
- });
- } finally {
- setIsRegisteringPasskey(false);
- }
- };
-
- if (shouldShowTotpRegistration) {
- return (
- <>
- <div className="mb-6 text-center text-lg font-bold text-white">
- Your organization requires mobile authentication to be configured.
- </div>
- <div className="mx-auto w-max pt-4 pb-4 md:mb-16 md:px-8">
- <TotpRegistration
- shouldCenterQr
- onComplete={async () => {
- setShouldShowTotpRegistration(false);
- await successCallback();
- }}
- />
- </div>
- </>
- );
- }
-
- if (shouldShowWebAuthnRegistration) {
+ if (shouldShowTotpRegistration || shouldShowWebAuthnRegistration) {
return (
- <>
- <div className="mb-6 text-center text-lg font-bold text-white">
- Your organization requires passkey authentication to be configured.
- </div>
- <div className="mx-auto w-max pt-4 pb-4 md:mb-16 md:px-8">
- <div className="flex max-w-lg flex-col text-bunker-200">
- <div className="mb-8">
- 1. Click the button below to register your passkey. You&apos;ll be prompted to use
- your device&apos;s biometric authentication (Touch ID, Face ID, Windows Hello, etc.).
- </div>
- <div className="mb-4">2. Optionally, give your passkey a name to identify it later</div>
- <div className="mb-4 flex flex-col gap-2">
- <Input
- onChange={(e) => setCredentialName(e.target.value)}
- value={credentialName}
- placeholder="Passkey name (optional)"
- />
- <Button onClick={handleRegisterPasskey} isLoading={isRegisteringPasskey}>
- Register Passkey
- </Button>
- </div>
- </div>
- </div>
- <RecoveryCodesDownload
- isOpen={registrationRecoveryCodes.length > 0}
- recoveryCodes={registrationRecoveryCodes}
- onClose={() => setRegistrationRecoveryCodes([])}
- onDownloadComplete={async () => {
- setRegistrationRecoveryCodes([]);
+ <div className="mx-auto w-max pt-4 pb-4 md:mb-16 md:px-8">
+ <MfaEnrollment
+ method={method}
+ onComplete={async () => {
+ setShouldShowTotpRegistration(false);
setShouldShowWebAuthnRegistration(false);
await successCallback();
}}
/>
- </>
+ </div>
);
}
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
new file mode 100644
index 0000000000..7c50e2d9d6
--- /dev/null
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -0,0 +1,101 @@
+import { useEffect, useRef, useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import SecurityClient from "@app/components/utilities/SecurityClient";
+import { ContentLoader } from "@app/components/v2";
+import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+import { getMfaTempToken } from "@app/hooks/api/reactQuery";
+import { fetchMfaRecoveryCodes, useUpdateUserMfa } from "@app/hooks/api/users";
+
+import { MFA_METHOD_LABELS, RecoveryCodesView, 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:
+// enable MFA (which mints recovery codes) -> verify the method -> save codes.
+export const MfaEnrollment = ({ method, onComplete }: Props) => {
+ const { mutateAsync: updateUserMfa } = useUpdateUserMfa();
+ const [phase, setPhase] = useState<"preparing" | "verify" | "recovery">("preparing");
+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
+ const [hasDownloaded, setHasDownloaded] = useState(false);
+ const hasPrepared = useRef(false);
+
+ useEffect(() => {
+ if (hasPrepared.current) return;
+ hasPrepared.current = true;
+
+ const prepare = async () => {
+ // The enrollment endpoints authenticate with the regular access token, so
+ // clear the temporary MFA token first.
+ SecurityClient.setMfaToken("");
+ try {
+ // Enabling is the single place recovery codes are minted; idempotent if
+ // MFA is already on.
+ await updateUserMfa({ isMfaEnabled: true });
+ setPhase("verify");
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to start two-factor setup",
+ type: "error"
+ });
+ }
+ };
+
+ prepare();
+ }, [updateUserMfa]);
+
+ const handleVerified = async () => {
+ try {
+ await updateUserMfa({ selectedMfaMethod: method });
+ } catch {
+ // preference update is best-effort
+ }
+ const codes = await fetchMfaRecoveryCodes();
+ setRecoveryCodes(codes);
+ setPhase("recovery");
+ };
+
+ const handleContinue = async () => {
+ // Restore the temp token so downstream MFA verification can proceed.
+ SecurityClient.setMfaToken(getMfaTempToken());
+ await onComplete();
+ };
+
+ return (
+ <div className="mx-auto flex w-full max-w-md flex-col gap-5 pt-4 pb-4">
+ <div className="text-center">
+ <h2 className="text-xl font-medium text-bunker-100">Set up two-factor authentication</h2>
+ <p className="mt-2 text-sm text-bunker-300">
+ Your organization requires {MFA_METHOD_LABELS[method]} to be configured.
+ </p>
+ </div>
+
+ {phase === "preparing" && <ContentLoader />}
+
+ {phase === "verify" && <VerifyStep method={method} onVerified={handleVerified} />}
+
+ {phase === "recovery" && (
+ <div className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <AlertTitle>Save your recovery codes</AlertTitle>
+ <AlertDescription>
+ Store these somewhere safe. Each works once if you lose access to your other methods.
+ </AlertDescription>
+ </Alert>
+ <RecoveryCodesView
+ recoveryCodes={recoveryCodes}
+ onDownloaded={() => setHasDownloaded(true)}
+ />
+ <Button variant="org" isFullWidth isDisabled={!hasDownloaded} onClick={handleContinue}>
+ Continue
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/mfa/RecoveryCodesDownload.tsx b/frontend/src/components/mfa/RecoveryCodesDownload.tsx
deleted file mode 100644
index db779bd942..0000000000
--- a/frontend/src/components/mfa/RecoveryCodesDownload.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { useState } from "react";
-import { faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { Button, Modal, ModalContent } from "../v2";
-
-type Props = {
- isOpen: boolean;
- onClose: () => void;
- recoveryCodes: string[];
- onDownloadComplete: () => void;
-};
-
-export const RecoveryCodesDownload = ({
- isOpen,
- onClose,
- recoveryCodes,
- onDownloadComplete
-}: Props) => {
- const [hasDownloaded, setHasDownloaded] = useState(false);
- const [copied, setCopied] = useState(false);
-
- const downloadRecoveryCodes = () => {
- const content = [...recoveryCodes].join("\n");
-
- const blob = new Blob([content], { type: "text/plain" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `infisical-recovery-codes-${new Date().toISOString().split("T")[0]}.txt`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- setHasDownloaded(true);
- };
-
- const copyToClipboard = async () => {
- const text = recoveryCodes.join("\n");
- try {
- await navigator.clipboard.writeText(text);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch (err) {
- console.error("Failed to copy recovery codes:", err);
- }
- };
-
- const handleClose = () => {
- if (hasDownloaded) {
- onDownloadComplete();
- onClose();
- }
- };
-
- return (
- <Modal isOpen={isOpen} onOpenChange={hasDownloaded ? handleClose : () => {}}>
- <ModalContent title="Recovery Codes" className="max-w-md">
- <div className="space-y-4">
- <div className="rounded-sm border border-yellow bg-yellow/10 p-2 px-3 text-xs text-yellow">
- Save these codes securely. Each can only be used once.
- </div>
-
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">
- {recoveryCodes.map((code, index) => (
- <div key={code} className="flex items-center text-mineshaft-200">
- <span className="w-8 text-right text-mineshaft-400">{index + 1}.</span>
- <span className="pl-2">{code}</span>
- </div>
- ))}
- </div>
- </div>
-
- <div className="flex gap-3">
- <Button
- onClick={downloadRecoveryCodes}
- className="flex flex-1 items-center justify-center gap-2"
- colorSchema="primary"
- variant="solid"
- >
- <FontAwesomeIcon icon={faDownload} className="mr-2 h-4 w-4" />
- Download
- </Button>
-
- <Button
- onClick={copyToClipboard}
- className="flex flex-1 items-center justify-center gap-2"
- colorSchema="secondary"
- variant="outline"
- >
- <FontAwesomeIcon icon={faCopy} className="mr-2 h-4 w-4" />
- {copied ? "Copied!" : "Copy"}
- </Button>
- </div>
-
- {hasDownloaded ? (
- <p className="text-center text-xs text-mineshaft-400">
- Recovery codes downloaded. You can now close this modal.
- </p>
- ) : (
- <p className="text-center text-xs text-mineshaft-400">
- Download the recovery codes to continue.
- </p>
- )}
- </div>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/components/mfa/TotpRegistration.tsx b/frontend/src/components/mfa/TotpRegistration.tsx
deleted file mode 100644
index bcb0d3691c..0000000000
--- a/frontend/src/components/mfa/TotpRegistration.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { useEffect, useState } from "react";
-import QRCode from "qrcode";
-import { twMerge } from "tailwind-merge";
-
-import { useGetUserTotpRegistration } from "@app/hooks/api";
-import { useVerifyUserTotpRegistration } from "@app/hooks/api/users/mutation";
-
-import { createNotification } from "../notifications";
-import { Button, ContentLoader, Input } from "../v2";
-import { RecoveryCodesDownload } from "./RecoveryCodesDownload";
-
-type Props = {
- onComplete?: () => Promise<void>;
- shouldCenterQr?: boolean;
-};
-
-const TotpRegistration = ({ onComplete, shouldCenterQr }: Props) => {
- const { data: registration, isPending } = useGetUserTotpRegistration();
- const { mutateAsync: verifyUserTotp, isPending: isVerifyLoading } =
- useVerifyUserTotpRegistration();
- const [qrCodeUrl, setQrCodeUrl] = useState("");
- const [totp, setTotp] = useState("");
- const [showRecoveryModal, setShowRecoveryModal] = useState(false);
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
-
- const handleTotpVerify = async (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- const result = await verifyUserTotp({
- totp
- });
-
- createNotification({
- text: "Successfully configured mobile authenticator",
- type: "success"
- });
-
- if (result.recoveryCodes && result.recoveryCodes.length > 0) {
- setRecoveryCodes(result.recoveryCodes);
- setShowRecoveryModal(true);
- } else if (onComplete) {
- onComplete();
- }
- };
-
- const handleRecoveryDownloadComplete = async () => {
- setShowRecoveryModal(false);
- if (onComplete) {
- await onComplete();
- }
- };
-
- useEffect(() => {
- const generateQRCode = async () => {
- if (registration?.otpUrl) {
- const url = await QRCode.toDataURL(registration.otpUrl);
- setQrCodeUrl(url);
- }
- };
-
- generateQRCode();
- }, [registration]);
-
- if (isPending) {
- return <ContentLoader />;
- }
-
- return (
- <>
- <div className="flex max-w-lg flex-col text-bunker-200">
- <div className="mb-8">
- 1. Download a two-step verification app (Duo, Google Authenticator, etc.) and scan the QR
- code.
- </div>
- <div className={twMerge("mb-8 flex items-center", shouldCenterQr && "justify-center")}>
- <img src={qrCodeUrl} alt="registration-qr" />
- </div>
- <form onSubmit={handleTotpVerify}>
- <div className="mb-4">2. Enter the resulting verification code</div>
- <div className="mb-4 flex flex-row gap-2">
- <Input
- onChange={(e) => setTotp(e.target.value)}
- value={totp}
- placeholder="Verification code"
- />
- <Button isLoading={isVerifyLoading} type="submit">
- Enable MFA
- </Button>
- </div>
- </form>
- </div>
-
- <RecoveryCodesDownload
- isOpen={showRecoveryModal}
- onClose={() => setShowRecoveryModal(false)}
- recoveryCodes={recoveryCodes}
- onDownloadComplete={handleRecoveryDownloadComplete}
- />
- </>
- );
-};
-
-export default TotpRegistration;
diff --git a/frontend/src/components/mfa/setup/MethodStep.tsx b/frontend/src/components/mfa/setup/MethodStep.tsx
new file mode 100644
index 0000000000..6d4b7fc75d
--- /dev/null
+++ b/frontend/src/components/mfa/setup/MethodStep.tsx
@@ -0,0 +1,47 @@
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+ FieldTitle,
+ RadioGroup,
+ RadioGroupItem
+} from "@app/components/v3";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+
+import { MFA_METHOD_OPTIONS } from "./types";
+
+type Props = {
+ selectedMethod: MfaMethod;
+ onSelect: (method: MfaMethod) => void;
+};
+
+export const MethodStep = ({ selectedMethod, onSelect }: Props) => {
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted">Choose the method you want to use as your second factor.</p>
+ <RadioGroup
+ value={selectedMethod}
+ onValueChange={(value) => onSelect(value as MfaMethod)}
+ className="gap-3"
+ >
+ {MFA_METHOD_OPTIONS.map((option) => {
+ const Icon = option.icon;
+ const id = `mfa-method-${option.value}`;
+ return (
+ <FieldLabel key={option.value} htmlFor={id}>
+ <Field orientation="horizontal">
+ <Icon />
+ <FieldContent>
+ <FieldTitle>{option.label}</FieldTitle>
+ <FieldDescription>{option.description}</FieldDescription>
+ </FieldContent>
+ <RadioGroupItem value={option.value} id={id} />
+ </Field>
+ </FieldLabel>
+ );
+ })}
+ </RadioGroup>
+ </div>
+ );
+};
diff --git a/frontend/src/components/mfa/setup/RecoveryCodesView.tsx b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
new file mode 100644
index 0000000000..1761c461ba
--- /dev/null
+++ b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
@@ -0,0 +1,60 @@
+import { useState } from "react";
+import { CopyIcon, DownloadIcon } from "lucide-react";
+
+import { Button } from "@app/components/v3";
+
+type Props = {
+ recoveryCodes: string[];
+ onDownloaded?: () => void;
+};
+
+export const RecoveryCodesView = ({ recoveryCodes, onDownloaded }: Props) => {
+ const [copied, setCopied] = useState(false);
+
+ const handleDownload = () => {
+ const content = recoveryCodes.join("\n");
+ const blob = new Blob([content], { type: "text/plain" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `infisical-recovery-codes-${new Date().toISOString().split("T")[0]}.txt`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ onDownloaded?.();
+ };
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(recoveryCodes.join("\n"));
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch {
+ // ignore clipboard failures
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4">
+ <div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">
+ {recoveryCodes.map((code, index) => (
+ <div key={code} className="flex items-center text-mineshaft-200">
+ <span className="w-6 text-right text-mineshaft-400">{index + 1}.</span>
+ <span className="pl-2">{code}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <Button variant="org" isFullWidth onClick={handleDownload}>
+ <DownloadIcon /> Download
+ </Button>
+ <Button variant="outline" isFullWidth onClick={handleCopy}>
+ <CopyIcon /> {copied ? "Copied!" : "Copy"}
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
new file mode 100644
index 0000000000..5dfa3324f8
--- /dev/null
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -0,0 +1,222 @@
+import { useEffect, useRef, useState } from "react";
+import { startRegistration } from "@simplewebauthn/browser";
+import { FingerprintIcon } from "lucide-react";
+import QRCode from "qrcode";
+
+import { createNotification } from "@app/components/notifications";
+import { ContentLoader } from "@app/components/v2";
+import { Button, Input } from "@app/components/v3";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+import {
+ useGetUserTotpRegistration,
+ useSendEmailMfaSetupCode,
+ useVerifyEmailMfaSetupCode,
+ useVerifyUserTotpRegistration
+} from "@app/hooks/api/users";
+import { useGenerateRegistrationOptions, useVerifyRegistration } from "@app/hooks/api/webauthn";
+
+type Props = {
+ method: MfaMethod;
+ onVerified: () => void | Promise<void>;
+};
+
+const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
+ const { data: registration, isPending } = useGetUserTotpRegistration();
+ const { mutateAsync: verifyTotp, isPending: isVerifying } = useVerifyUserTotpRegistration();
+ const [qrCodeUrl, setQrCodeUrl] = useState("");
+ const [totp, setTotp] = useState("");
+
+ useEffect(() => {
+ if (registration?.otpUrl) {
+ QRCode.toDataURL(registration.otpUrl).then(setQrCodeUrl);
+ }
+ }, [registration?.otpUrl]);
+
+ const manualSecret = registration?.otpUrl?.split("secret=")[1]?.split("&")[0];
+
+ const handleVerify = async () => {
+ try {
+ await verifyTotp({ totp: totp.trim() });
+ createNotification({ text: "Authenticator app configured", type: "success" });
+ await onVerified();
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Invalid verification code",
+ type: "error"
+ });
+ }
+ };
+
+ if (isPending) return <ContentLoader />;
+
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted">
+ Scan the QR code with an authenticator app, then enter the 6-digit code it generates.
+ </p>
+ <div className="flex items-center justify-center rounded-lg bg-white p-4">
+ {qrCodeUrl ? (
+ <img src={qrCodeUrl} alt="Authenticator QR code" className="h-44 w-44" />
+ ) : (
+ <div className="h-44 w-44" />
+ )}
+ </div>
+ {manualSecret && (
+ <p className="text-xs text-muted">
+ Can&apos;t scan? Enter this key manually:{" "}
+ <code className="rounded bg-mineshaft-700 px-2 py-0.5 font-mono text-mineshaft-100">
+ {manualSecret}
+ </code>
+ </p>
+ )}
+ <Input
+ value={totp}
+ onChange={(e) => setTotp(e.target.value.replace(/\D/g, "").slice(0, 6))}
+ placeholder="Enter 6-digit code"
+ maxLength={6}
+ />
+ <Button
+ variant="org"
+ isPending={isVerifying}
+ isDisabled={totp.trim().length !== 6}
+ onClick={handleVerify}
+ >
+ Verify code
+ </Button>
+ </div>
+ );
+};
+
+const RESEND_COOLDOWN_SECONDS = 60;
+
+const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
+ const { mutateAsync: sendCode } = useSendEmailMfaSetupCode();
+ const { mutateAsync: verifyCode, isPending: isVerifying } = useVerifyEmailMfaSetupCode();
+ const [code, setCode] = useState("");
+ const [cooldown, setCooldown] = useState(0);
+
+ const hasSentRef = useRef(false);
+
+ const sendAndStartCooldown = () => {
+ setCooldown(RESEND_COOLDOWN_SECONDS);
+ sendCode().catch((error: any) => {
+ const remaining = error?.response?.data?.details?.cooldownSeconds;
+ if (typeof remaining === "number") {
+ setCooldown(remaining);
+ return;
+ }
+ setCooldown(0);
+ createNotification({
+ text: error?.response?.data?.message || "Failed to send verification code",
+ type: "error"
+ });
+ });
+ };
+
+ useEffect(() => {
+ if (hasSentRef.current) return;
+ hasSentRef.current = true;
+ sendAndStartCooldown();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ useEffect(() => {
+ if (cooldown <= 0) return undefined;
+ const timer = setTimeout(() => setCooldown((remaining) => remaining - 1), 1000);
+ return () => clearTimeout(timer);
+ }, [cooldown]);
+
+ const handleVerify = async () => {
+ try {
+ await verifyCode({ code: code.trim() });
+ createNotification({ text: "Email verified", type: "success" });
+ await onVerified();
+ } catch {
+ // The global mutation error handler surfaces the failure toast.
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted">
+ We sent a one-time code to your account email. Enter it below to confirm.
+ </p>
+ <Input
+ value={code}
+ onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
+ placeholder="Enter 6-digit code"
+ maxLength={6}
+ />
+ <div className="flex items-center gap-3">
+ <Button
+ variant="org"
+ isPending={isVerifying}
+ isDisabled={code.trim().length !== 6}
+ onClick={handleVerify}
+ >
+ Verify code
+ </Button>
+ <Button variant="ghost" isDisabled={cooldown > 0} onClick={sendAndStartCooldown}>
+ {cooldown > 0 ? `Resend code in ${cooldown}s` : "Resend code"}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+const WebAuthnVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
+ const { mutateAsync: generateOptions } = useGenerateRegistrationOptions();
+ const { mutateAsync: verifyRegistration, isPending } = useVerifyRegistration();
+ const [name, setName] = useState("");
+
+ const handleRegister = async () => {
+ try {
+ if (
+ !window.PublicKeyCredential ||
+ !window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
+ ) {
+ createNotification({ text: "WebAuthn is not supported on this browser", type: "error" });
+ return;
+ }
+
+ const options = await generateOptions();
+ const registrationResponse = await startRegistration({ optionsJSON: options });
+ await verifyRegistration({ registrationResponse, name: name.trim() || "Passkey" });
+
+ createNotification({ text: "Passkey registered", type: "success" });
+ await onVerified();
+ } catch (error: any) {
+ let text = "Failed to register passkey";
+ if (error.name === "NotAllowedError")
+ text = "Passkey registration was cancelled or timed out";
+ else if (error.name === "InvalidStateError")
+ text = "This passkey has already been registered";
+ else if (error?.response?.data?.message) text = error.response.data.message;
+ else if (error.message) text = error.message;
+ createNotification({ text, type: "error" });
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted">
+ Register a passkey using Face ID, Touch ID, a security key, or your device. Optionally give
+ it a name so you can recognize it later.
+ </p>
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Passkey name (optional)"
+ />
+ <Button variant="org" isPending={isPending} onClick={handleRegister}>
+ <FingerprintIcon /> Register passkey
+ </Button>
+ </div>
+ );
+};
+
+export const VerifyStep = ({ method, onVerified }: Props) => {
+ if (method === MfaMethod.TOTP) return <TotpVerify onVerified={onVerified} />;
+ if (method === MfaMethod.EMAIL) return <EmailVerify onVerified={onVerified} />;
+ return <WebAuthnVerify onVerified={onVerified} />;
+};
diff --git a/frontend/src/components/mfa/setup/index.ts b/frontend/src/components/mfa/setup/index.ts
new file mode 100644
index 0000000000..6ff5aa2905
--- /dev/null
+++ b/frontend/src/components/mfa/setup/index.ts
@@ -0,0 +1,6 @@
+export { MethodStep } from "./MethodStep";
+export { RecoveryCodesView } from "./RecoveryCodesView";
+export type { MfaMethodOption, WizardStep } from "./types";
+export { MFA_METHOD_LABELS as METHOD_LABELS, MFA_METHOD_LABELS, MFA_METHOD_OPTIONS } from "./types";
+export { WIZARD_STEPS } from "./types";
+export { VerifyStep } from "./VerifyStep";
diff --git a/frontend/src/components/mfa/setup/types.ts b/frontend/src/components/mfa/setup/types.ts
new file mode 100644
index 0000000000..2b2d223197
--- /dev/null
+++ b/frontend/src/components/mfa/setup/types.ts
@@ -0,0 +1,49 @@
+import { FingerprintIcon, LucideIcon, MailIcon, SmartphoneIcon } from "lucide-react";
+
+import { MfaMethod } from "@app/hooks/api/auth/types";
+
+export type MfaMethodOption = {
+ value: MfaMethod;
+ label: string;
+ description: string;
+ icon: LucideIcon;
+};
+
+export const MFA_METHOD_OPTIONS: MfaMethodOption[] = [
+ {
+ value: MfaMethod.TOTP,
+ label: "Authenticator app",
+ description: "Use a TOTP app like 1Password or Authy.",
+ icon: SmartphoneIcon
+ },
+ {
+ value: MfaMethod.EMAIL,
+ label: "Email",
+ description: "Receive one-time codes by email.",
+ icon: MailIcon
+ },
+ {
+ value: MfaMethod.WEBAUTHN,
+ label: "Passkey",
+ description: "Use Face ID, Touch ID, a security key, or your device.",
+ icon: FingerprintIcon
+ }
+];
+
+export const MFA_METHOD_LABELS: Record<MfaMethod, string> = {
+ [MfaMethod.TOTP]: "Authenticator app",
+ [MfaMethod.EMAIL]: "Email",
+ [MfaMethod.WEBAUTHN]: "Passkey"
+};
+
+export type WizardStep = {
+ key: "method" | "verify" | "recovery";
+ title: string;
+ description: string;
+};
+
+export const WIZARD_STEPS: WizardStep[] = [
+ { key: "method", title: "Method", description: "Choose method" },
+ { key: "verify", title: "Verify", description: "Confirm it works" },
+ { key: "recovery", title: "Recovery", description: "Save backup codes" }
+];
diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsx
index 672139e6e0..3bca7df88e 100644
--- a/frontend/src/hooks/api/users/index.tsx
+++ b/frontend/src/hooks/api/users/index.tsx
@@ -1,17 +1,24 @@
export {
useAddUserToWsNonE2EE,
+ useDeleteUserTotpConfiguration,
useRemoveMyDuplicateAccounts,
useRequestEmailChangeOTP,
useRevokeMySessionById,
+ useRotateMfaRecoveryCodes,
+ useSendEmailMfaSetupCode,
useSendEmailVerificationCode,
useUpdateUserEmail,
- useVerifyCurrentEmailOTP
+ useVerifyCurrentEmailOTP,
+ useVerifyEmailMfaSetupCode,
+ useVerifyUserTotpRegistration
} from "./mutation";
export {
+ fetchMfaRecoveryCodes,
fetchOrgUsers,
useAddUsersToOrg,
useDeleteMe,
useDeleteOrgMembership,
+ useGetMfaRecoveryCodes,
useGetMyDuplicateAccount,
useGetMyIp,
useGetMyOrganizationProjects,
@@ -21,6 +28,7 @@ export {
useGetOrgUsers,
useGetUser,
useGetUserAction,
+ useGetUserTotpConfiguration,
useGetUserTotpRegistration,
useListUserGroupMemberships,
useLogoutUser,
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index b811b06a09..cdd86f7e53 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -66,15 +66,37 @@ export const useUpdateUserProjectFavorites = () => {
};
export const useVerifyUserTotpRegistration = () => {
- return useMutation<{ recoveryCodes: string[] }, unknown, { totp: string }>({
+ const queryClient = useQueryClient();
+ return useMutation<{ success: boolean }, unknown, { totp: string }>({
mutationFn: async ({ totp }: { totp: string }) => {
- const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(
- "/api/v1/user/me/totp/verify",
- {
- totp
- }
- );
+ const { data } = await apiRequest.post<{ success: boolean }>("/api/v1/user/me/totp/verify", {
+ totp
+ });
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
+ }
+ });
+};
+
+export const useSendEmailMfaSetupCode = () => {
+ return useMutation<{ message: string }, unknown, void>({
+ mutationFn: async () => {
+ const { data } = await apiRequest.post<{ message: string }>("/api/v1/user/me/mfa/email/send");
+ return data;
+ }
+ });
+};
+
+export const useVerifyEmailMfaSetupCode = () => {
+ return useMutation<{ success: boolean }, unknown, { code: string }>({
+ mutationFn: async ({ code }: { code: string }) => {
+ const { data } = await apiRequest.post<{ success: boolean }>(
+ "/api/v1/user/me/mfa/email/verify",
+ { code }
+ );
return data;
}
});
@@ -94,8 +116,6 @@ export const useDeleteUserTotpConfiguration = () => {
});
};
-// Rotates the account-level recovery codes: issues a fresh set and invalidates
-// the old ones. Returns the new codes so the caller can display them once.
export const useRotateMfaRecoveryCodes = () => {
const queryClient = useQueryClient();
return useMutation<{ recoveryCodes: string[] }, unknown, void>({
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index a04103628b..fa4065fa29 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -467,9 +467,7 @@ export const useGetUserTotpRegistration = (options?: { enabled?: boolean }) => {
return useQuery({
queryKey: userKeys.totpRegistration,
queryFn: async () => {
- const { data } = await apiRequest.post<{ otpUrl: string; recoveryCodes: string[] }>(
- "/api/v1/user/me/totp/register"
- );
+ const { data } = await apiRequest.post<{ otpUrl: string }>("/api/v1/user/me/totp/register");
return data;
},
@@ -482,16 +480,13 @@ export const useGetUserTotpConfiguration = () => {
queryKey: userKeys.totpConfiguration,
queryFn: async () => {
try {
- const { data } = await apiRequest.get<{ isVerified: boolean; recoveryCodes: string[] }>(
- "/api/v1/user/me/totp"
- );
+ const { data } = await apiRequest.get<{ isVerified: boolean }>("/api/v1/user/me/totp");
return data;
} catch (error) {
if (error instanceof AxiosError && [404, 400].includes(error.response?.data?.statusCode)) {
return {
- isVerified: false,
- recoveryCodes: []
+ isVerified: false
};
}
throw error;
diff --git a/frontend/src/hooks/api/webauthn/types.ts b/frontend/src/hooks/api/webauthn/types.ts
index 5f7a4c984a..f936790d39 100644
--- a/frontend/src/hooks/api/webauthn/types.ts
+++ b/frontend/src/hooks/api/webauthn/types.ts
@@ -24,7 +24,6 @@ export type TVerifyRegistrationDTO = {
export type TVerifyRegistrationResponse = {
credentialId: string;
name?: string | null;
- recoveryCodes: string[];
};
export type TGenerateAuthenticationOptionsResponse = PublicKeyCredentialRequestOptionsJSON;
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index 8be9578a9c..3279287c6c 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
@@ -1,963 +1,239 @@
-import { useEffect, useState } from "react";
-import { startRegistration } from "@simplewebauthn/browser";
+import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
-import QRCode from "qrcode";
+import {
+ CircleAlertIcon,
+ FingerprintIcon,
+ MailIcon,
+ PowerIcon,
+ ShieldCheckIcon,
+ SmartphoneIcon
+} from "lucide-react";
-import { RecoveryCodesDownload } from "@app/components/mfa/RecoveryCodesDownload";
import { createNotification } from "@app/components/notifications";
+import { ContentLoader } from "@app/components/v2";
import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Badge,
Button,
- ContentLoader,
- DeleteActionModal,
- EmailServiceSetupModal,
- FormControl,
- Input,
- Modal,
- ModalContent,
Select,
- SelectItem
-} from "@app/components/v2";
-import { useToggle } from "@app/hooks";
-import { useGetUser, userKeys, useUpdateUserMfa } from "@app/hooks/api";
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useGetOrganizations, useGetUser, userKeys, useUpdateUserMfa } from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
-import { useFetchServerStatus } from "@app/hooks/api/serverDetails";
-import {
- useDeleteUserTotpConfiguration,
- useRotateMfaRecoveryCodes,
- useVerifyUserTotpRegistration
-} from "@app/hooks/api/users/mutation";
-import {
- fetchMfaRecoveryCodes,
- useGetMfaRecoveryCodes,
- useGetUserTotpConfiguration,
- useGetUserTotpRegistration
-} from "@app/hooks/api/users/queries";
+import { useGetUserTotpConfiguration } from "@app/hooks/api/users";
import { AuthMethod } from "@app/hooks/api/users/types";
-import {
- useDeleteWebAuthnCredential,
- useGenerateRegistrationOptions,
- useGetWebAuthnCredentials,
- useUpdateWebAuthnCredential,
- useVerifyRegistration
-} from "@app/hooks/api/webauthn";
-import { usePopUp } from "@app/hooks/usePopUp";
+import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
-export const MFASection = () => {
- const { data: user } = useGetUser();
- const { mutateAsync } = useUpdateUserMfa();
-
- const [formData, setFormData] = useState({
- isMfaEnabled: user?.isMfaEnabled || false,
- selectedMfaMethod: user?.selectedMfaMethod || MfaMethod.EMAIL
- });
- const [isLoading, setIsLoading] = useState(false);
- const [totpCode, setTotpCode] = useState("");
- const [qrCodeUrl, setQrCodeUrl] = useState("");
- const [showMobileAuthSetup, setShowMobileAuthSetup] = useState(false);
-
- const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
- "setUpEmail",
- "deleteTotpConfig",
- "downloadRecoveryCodes",
- "regenerateRecoveryCodes",
- "deleteWebAuthnCredential",
- "renameWebAuthnCredential",
- "registerPasskey"
- ] as const);
- const [shouldShowRecoveryCodes, setShouldShowRecoveryCodes] = useToggle();
- const { data: totpConfiguration } = useGetUserTotpConfiguration();
- const { data: totpRegistration, isPending: isTotpRegistrationLoading } =
- useGetUserTotpRegistration({
- enabled: showMobileAuthSetup
- });
- const { mutateAsync: deleteTotpConfiguration } = useDeleteUserTotpConfiguration();
- const { mutateAsync: verifyUserTotp } = useVerifyUserTotpRegistration();
- const queryClient = useQueryClient();
- const { data: serverDetails } = useFetchServerStatus();
+import { MfaMethodsCard } from "./MfaMethodsCard";
+import { MfaSetupWizard } from "./MfaSetupWizard";
+import { RecoveryOptionsCard } from "./RecoveryOptionsCard";
- // WebAuthn/Passkey hooks
- const { data: webAuthnCredentials, isPending: isWebAuthnCredentialsLoading } =
- useGetWebAuthnCredentials();
- const { mutateAsync: generateRegistrationOptions, isPending: isGeneratingOptions } =
- useGenerateRegistrationOptions();
- const { mutateAsync: verifyRegistration, isPending: isVerifyingRegistration } =
- useVerifyRegistration();
- const { mutateAsync: deleteWebAuthnCredential } = useDeleteWebAuthnCredential();
- const { mutateAsync: updateWebAuthnCredential } = useUpdateWebAuthnCredential();
+const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";
- const [selectedCredentialId, setSelectedCredentialId] = useState<string>("");
- const [credentialName, setCredentialName] = useState<string>("");
- const [isRegisteringPasskey, setIsRegisteringPasskey] = useState(false);
- const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[]>([]);
-
- const hasPasskeys = Boolean(webAuthnCredentials && webAuthnCredentials.length > 0);
- // Recovery codes are account-level and shared across every MFA method, so surface
- // them whenever the user has MFA enabled or any MFA credential configured.
- const shouldShowRecoveryCodesSection = Boolean(
- user?.isMfaEnabled || totpConfiguration?.isVerified || hasPasskeys
- );
- const { data: mfaRecoveryCodes } = useGetMfaRecoveryCodes(shouldShowRecoveryCodesSection);
- const hasRecoveryCodes = Boolean(mfaRecoveryCodes && mfaRecoveryCodes.length > 0);
- const { mutateAsync: rotateMfaRecoveryCodes, isPending: isRotatingRecoveryCodes } =
- useRotateMfaRecoveryCodes();
-
- // Update form data when user data changes
- useEffect(() => {
- if (user) {
- setFormData({
- isMfaEnabled: user.isMfaEnabled,
- selectedMfaMethod: user.selectedMfaMethod || MfaMethod.EMAIL
- });
- }
- }, [user]);
-
- useEffect(() => {
- const generateQRCode = async () => {
- if (totpRegistration?.otpUrl) {
- const url = await QRCode.toDataURL(totpRegistration.otpUrl);
- setQrCodeUrl(url);
- }
- };
-
- if (showMobileAuthSetup && totpRegistration?.otpUrl) {
- generateQRCode();
- }
- }, [totpRegistration, showMobileAuthSetup]);
-
- const handleTotpDeletion = async () => {
- await deleteTotpConfiguration();
-
- await mutateAsync({
- selectedMfaMethod: MfaMethod.EMAIL
- });
-
- createNotification({
- text: "Successfully deleted mobile authenticator and switched to email authentication",
- type: "success"
- });
-
- handlePopUpClose("deleteTotpConfig");
- };
-
- // Generates a fresh account-level recovery code pool and surfaces it for saving.
- // `isRotation` distinguishes replacing an existing pool (confirmed via modal,
- // invalidates the old codes) from first-time generation for users with none yet.
- const generateAndShowRecoveryCodes = async (isRotation: boolean) => {
- try {
- const { recoveryCodes } = await rotateMfaRecoveryCodes();
-
- if (isRotation) {
- handlePopUpClose("regenerateRecoveryCodes");
- }
+const PREFERRED_METHOD_ICONS: Record<MfaMethod, typeof MailIcon> = {
+ [MfaMethod.TOTP]: SmartphoneIcon,
+ [MfaMethod.EMAIL]: MailIcon,
+ [MfaMethod.WEBAUTHN]: FingerprintIcon
+};
- setNewRecoveryCodes(recoveryCodes);
- handlePopUpOpen("downloadRecoveryCodes");
+const PREFERRED_METHOD_LABELS: Record<MfaMethod, string> = {
+ [MfaMethod.TOTP]: "Authenticator app",
+ [MfaMethod.EMAIL]: "Email",
+ [MfaMethod.WEBAUTHN]: "Passkey"
+};
- createNotification({
- text: isRotation
- ? "Generated a new set of recovery codes. Your previous codes no longer work."
- : "Generated your recovery codes. Save them somewhere safe.",
- type: "success"
- });
- } catch (error: any) {
- createNotification({
- text: error?.response?.data?.message || "Failed to generate recovery codes",
- type: "error"
- });
- }
- };
+export const MFASection = () => {
+ const { data: user, isPending } = useGetUser();
+ const { mutateAsync: updateUserMfa, isPending: isUpdating } = useUpdateUserMfa();
+ const { data: totpConfiguration } = useGetUserTotpConfiguration();
+ const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
+ const { data: organizations = [] } = useGetOrganizations();
+ const queryClient = useQueryClient();
- const handleRegisterPasskey = async () => {
+ const isMfaEnforced = organizations.some((org) => org.enforceMfa);
+
+ const [isWizardOpen, setIsWizardOpen] = useState(false);
+ const [isDisableOpen, setIsDisableOpen] = useState(false);
+
+ if (isPending || !user) {
+ return <ContentLoader />;
+ }
+
+ if (user.authMethods?.includes(AuthMethod.LDAP)) {
+ return (
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <h2 className="text-lg font-medium text-mineshaft-100">Two-factor Authentication</h2>
+ <p className="mt-1 text-sm text-muted">
+ Two-factor authentication is managed by your identity provider for LDAP accounts.
+ </p>
+ </div>
+ );
+ }
+
+ const availableMethods = [
+ MfaMethod.EMAIL,
+ ...(totpConfiguration?.isVerified ? [MfaMethod.TOTP] : []),
+ ...(webAuthnCredentials.length > 0 ? [MfaMethod.WEBAUTHN] : [])
+ ];
+ const selectedMethod = user.selectedMfaMethod || MfaMethod.EMAIL;
+
+ const handlePreferredMethodChange = async (method: MfaMethod) => {
try {
- setIsRegisteringPasskey(true);
-
- // Check if WebAuthn is supported
- if (
- !window.PublicKeyCredential ||
- !window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
- ) {
- createNotification({
- text: "WebAuthn is not supported on this browser",
- type: "error"
- });
- return;
- }
-
- // Check if platform authenticator is available
- const available =
- await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
- if (!available) {
- createNotification({
- text: "No passkey-compatible authenticator found on this device",
- type: "error"
- });
- return;
- }
-
- // Generate registration options from server
- const options = await generateRegistrationOptions();
- const registrationResponse = await startRegistration({ optionsJSON: options });
-
- // Verify registration with server
- const { recoveryCodes } = await verifyRegistration({
- registrationResponse,
- name: credentialName || "Passkey"
- });
-
- createNotification({
- text: "Successfully registered passkey",
- type: "success"
- });
-
- handlePopUpClose("registerPasskey");
- setCredentialName("");
-
- // Surface account-level recovery codes generated on the first passkey.
- if (recoveryCodes && recoveryCodes.length > 0) {
- setNewRecoveryCodes(recoveryCodes);
- handlePopUpOpen("downloadRecoveryCodes");
- }
+ await updateUserMfa({ selectedMfaMethod: method });
+ createNotification({ text: "Updated preferred 2FA method", type: "success" });
} catch (error: any) {
- console.error("Failed to register passkey:", error);
-
- // Better error messages
- let errorMessage = "Failed to register passkey";
- if (error.name === "NotAllowedError") {
- errorMessage = "Passkey registration was cancelled or timed out";
- } else if (error.name === "InvalidStateError") {
- errorMessage = "This passkey has already been registered";
- } else if (error.message) {
- errorMessage = error.message;
- }
-
createNotification({
- text: errorMessage,
+ text: error?.response?.data?.message || "Failed to update preferred method",
type: "error"
});
- } finally {
- setIsRegisteringPasskey(false);
}
};
- const handleDeleteWebAuthnCredential = async () => {
+ const handleDisable = async () => {
try {
- await deleteWebAuthnCredential({ id: selectedCredentialId });
-
- createNotification({
- text: "Successfully deleted passkey",
- type: "success"
- });
-
- handlePopUpClose("deleteWebAuthnCredential");
- setSelectedCredentialId("");
+ await updateUserMfa({ isMfaEnabled: false });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser }),
+ queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration }),
+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes })
+ ]);
+ setIsDisableOpen(false);
+ createNotification({ text: "Two-factor authentication disabled", type: "success" });
} catch (error: any) {
createNotification({
- text: error.message || "Failed to delete passkey",
+ text: error?.response?.data?.message || "Failed to disable two-factor authentication",
type: "error"
});
}
};
- const handleRenameWebAuthnCredential = async () => {
- try {
- await updateWebAuthnCredential({
- id: selectedCredentialId,
- name: credentialName
- });
-
- createNotification({
- text: "Successfully renamed passkey",
- type: "success"
- });
-
- handlePopUpClose("renameWebAuthnCredential");
- setSelectedCredentialId("");
- setCredentialName("");
- } catch (error: any) {
- createNotification({
- text: error.message || "Failed to rename passkey",
- type: "error"
- });
- }
- };
-
- const handleFormDataChange = (field: string, value: any) => {
- setFormData((prev) => ({
- ...prev,
- [field]: value
- }));
-
- // Show mobile auth setup when mobile authenticator is selected and we're enabling 2FA
- if (field === "selectedMfaMethod" && value === MfaMethod.TOTP && formData.isMfaEnabled) {
- setShowMobileAuthSetup(true);
- } else if (field === "selectedMfaMethod" && value !== MfaMethod.TOTP) {
- // Switching the selected method away from TOTP is only a local form edit
- // until the user saves. Do not delete the existing TOTP configuration here:
- // it can coexist with another active method and is managed (removed)
- // explicitly via the "Remove Authenticator" button.
- setShowMobileAuthSetup(false);
- setTotpCode("");
- setShouldShowRecoveryCodes.off();
- } else if (field === "isMfaEnabled" && value && formData.selectedMfaMethod === MfaMethod.TOTP) {
- setShowMobileAuthSetup(true);
- } else if (field === "isMfaEnabled" && !value) {
- setShowMobileAuthSetup(false);
- setTotpCode("");
- setShouldShowRecoveryCodes.off();
- }
- };
-
- const handleSaveChanges = async () => {
- try {
- if (!user) return;
-
- const isEnablingMfa = !user.isMfaEnabled && formData.isMfaEnabled;
-
- if (user.authMethods.includes(AuthMethod.LDAP)) {
- createNotification({
- text: "Two-factor authentication is not available for LDAP users.",
- type: "error"
- });
- return;
- }
-
- if (!serverDetails?.emailConfigured && formData.isMfaEnabled) {
- handlePopUpOpen("setUpEmail");
- return;
- }
-
- // If selecting passkey as 2FA method but no passkeys registered
- if (
- formData.isMfaEnabled &&
- formData.selectedMfaMethod === MfaMethod.WEBAUTHN &&
- (!webAuthnCredentials || webAuthnCredentials.length === 0)
- ) {
- createNotification({
- text: "Please register at least one passkey before selecting it as your two-factor authentication method",
- type: "error"
- });
- return;
- }
-
- setIsLoading(true);
-
- // If enabling 2FA with mobile authenticator, verify TOTP first
- if (
- formData.isMfaEnabled &&
- formData.selectedMfaMethod === MfaMethod.TOTP &&
- !totpConfiguration?.isVerified
- ) {
- if (!totpCode.trim()) {
- createNotification({
- text: "Please enter the verification code from your authenticator app",
- type: "error"
- });
- setIsLoading(false);
- return;
- }
-
- try {
- await verifyUserTotp({ totp: totpCode });
-
- createNotification({
- text: "Successfully configured mobile authenticator",
- type: "success"
- });
-
- await queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
- } catch {
- setIsLoading(false);
- return;
- }
- }
-
- // If disabling 2FA and there's a TOTP configuration, delete it
- if (!formData.isMfaEnabled && user.isMfaEnabled && totpConfiguration?.isVerified) {
- try {
- await deleteTotpConfiguration();
- createNotification({
- text: "Mobile authenticator removed",
- type: "success"
- });
-
- // Refresh TOTP configuration
- await queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
- } catch {
- // Continue with disabling 2FA even if TOTP deletion fails
- }
- }
-
- const updates: any = {};
-
- // Only update if values have changed
- if (formData.isMfaEnabled !== user.isMfaEnabled) {
- updates.isMfaEnabled = formData.isMfaEnabled;
- }
-
- if (formData.selectedMfaMethod !== user.selectedMfaMethod) {
- updates.selectedMfaMethod = formData.selectedMfaMethod;
- }
-
- if (Object.keys(updates).length > 0) {
- await mutateAsync(updates);
-
- createNotification({
- text: "Successfully updated two-factor authentication settings",
- type: "success"
- });
- }
-
- // Turning MFA on provisions a fresh account-level recovery code pool
- // server-side (regardless of method). Surface it once so the user can save
- // the codes before leaving the page.
- if (isEnablingMfa) {
- const recoveryCodes = await fetchMfaRecoveryCodes();
- if (recoveryCodes.length > 0) {
- setNewRecoveryCodes(recoveryCodes);
- handlePopUpOpen("downloadRecoveryCodes");
- }
- await queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });
- }
-
- // Reset form state
- setShowMobileAuthSetup(false);
- setTotpCode("");
- setShouldShowRecoveryCodes.off();
- } finally {
- setIsLoading(false);
- }
- };
-
- const hasChanges =
- user &&
- (formData.isMfaEnabled !== user.isMfaEnabled ||
- formData.selectedMfaMethod !== user.selectedMfaMethod);
-
- const isFormValid = () => {
- if (!formData.isMfaEnabled) return true;
- if (formData.selectedMfaMethod === MfaMethod.EMAIL) return true;
- if (formData.selectedMfaMethod === MfaMethod.TOTP) {
- if (totpConfiguration?.isVerified) return true;
- return totpCode.trim().length > 0;
- }
- if (formData.selectedMfaMethod === MfaMethod.WEBAUTHN) return true;
-
- return false;
- };
+ const disabledView = (
+ <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
+ <div className="flex items-start justify-between">
+ <h2 className="text-lg font-medium text-mineshaft-100">Two-factor Authentication</h2>
+ <Badge variant="danger">
+ <CircleAlertIcon /> Not enabled
+ </Badge>
+ </div>
+ <p className="mt-2 max-w-2xl text-sm text-muted">
+ Two-factor authentication adds an additional layer of security to your account by requiring
+ more than just a password to sign in. Want to learn more about two-factor authentication?{" "}
+ <a
+ href={LEARN_MORE_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-mineshaft-200"
+ >
+ Click here
+ </a>
+ </p>
+ <div className="mt-5">
+ <Button variant="org" onClick={() => setIsWizardOpen(true)}>
+ <ShieldCheckIcon /> Enable two-factor authentication
+ </Button>
+ </div>
+ </div>
+ );
- const registerPasskeyModal = (
- <Modal
- isOpen={popUp.registerPasskey?.isOpen || false}
- onOpenChange={(isOpen) => {
- if (!isOpen) {
- handlePopUpClose("registerPasskey");
- setCredentialName("");
- }
- }}
- >
- <ModalContent title="Register New Passkey">
- <div className="space-y-4">
- <p className="text-sm text-mineshaft-300">
- Give your passkey a name to help you identify it later. After clicking
- &quot;Register&quot;, you&apos;ll be prompted to use your device&apos;s biometric
- authentication (Touch ID, Face ID, Windows Hello, etc.).
+ const enabledView = (
+ <div className="mb-6 flex flex-col gap-6">
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
+ <div className="flex items-start justify-between">
+ <h2 className="text-lg font-medium text-mineshaft-100">Two-factor Authentication</h2>
+ <Badge variant="success">
+ <ShieldCheckIcon /> Enabled
+ </Badge>
+ </div>
+ <p className="mt-2 max-w-2xl text-sm text-muted">
+ Two-factor authentication is protecting your account. Manage your methods and recovery
+ options below.
+ </p>
+
+ <div className="mt-6 border-t border-mineshaft-700 pt-6">
+ <p className="text-sm font-medium text-mineshaft-100">Preferred 2FA method</p>
+ <p className="mb-3 text-sm text-muted">
+ Set the method used first when signing in to Infisical.
</p>
- <FormControl label="Passkey Name">
- <Input
- value={credentialName}
- onChange={(e) => setCredentialName(e.target.value)}
- placeholder="e.g., My MacBook Pro"
- />
- </FormControl>
- <div className="flex gap-2">
- <Button
- onClick={handleRegisterPasskey}
- isLoading={isRegisteringPasskey || isVerifyingRegistration}
- disabled={!credentialName.trim()}
- colorSchema="primary"
+ <div className="max-w-xs">
+ <Select
+ value={selectedMethod}
+ onValueChange={(value) => handlePreferredMethodChange(value as MfaMethod)}
>
- Register
- </Button>
- <Button
- variant="outline_bg"
- onClick={() => handlePopUpClose("registerPasskey")}
- disabled={isRegisteringPasskey || isVerifyingRegistration}
- >
- Cancel
- </Button>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a method" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableMethods.map((method) => {
+ const Icon = PREFERRED_METHOD_ICONS[method];
+ return (
+ <SelectItem key={method} value={method}>
+ <span className="flex items-center gap-2">
+ <Icon />
+ {PREFERRED_METHOD_LABELS[method]}
+ </span>
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
</div>
</div>
- </ModalContent>
- </Modal>
- );
- const renamePasskeyModal = (
- <Modal
- isOpen={popUp.renameWebAuthnCredential?.isOpen || false}
- onOpenChange={(isOpen) => {
- if (!isOpen) {
- handlePopUpClose("renameWebAuthnCredential");
- setCredentialName("");
- setSelectedCredentialId("");
- }
- }}
- >
- <ModalContent title="Rename Passkey">
- <div className="space-y-4">
- <FormControl label="Passkey Name">
- <Input
- value={credentialName}
- onChange={(e) => setCredentialName(e.target.value)}
- placeholder="e.g., My MacBook Pro"
- />
- </FormControl>
- <div className="flex gap-2">
- <Button
- onClick={handleRenameWebAuthnCredential}
- disabled={!credentialName.trim()}
- colorSchema="primary"
- >
- Save
- </Button>
- <Button
- variant="outline_bg"
- onClick={() => handlePopUpClose("renameWebAuthnCredential")}
- >
- Cancel
- </Button>
- </div>
+ <div className="mt-6 flex items-center justify-between gap-4 border-t border-mineshaft-700 pt-6">
+ <p className="text-sm text-muted">
+ {isMfaEnforced
+ ? "Your organization requires two-factor authentication, so it can't be disabled."
+ : "Turning this off removes all configured methods and recovery codes."}
+ </p>
+ <Button
+ variant="danger"
+ isDisabled={isMfaEnforced}
+ onClick={() => setIsDisableOpen(true)}
+ >
+ <PowerIcon /> Disable two-factor authentication
+ </Button>
</div>
- </ModalContent>
- </Modal>
+ </div>
+
+ <MfaMethodsCard />
+ <RecoveryOptionsCard />
+
+ <AlertDialog open={isDisableOpen} onOpenChange={setIsDisableOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Disable two-factor authentication?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This removes every configured method (authenticator app, passkeys) and your recovery
+ codes. You can re-enable it at any time.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" isPending={isUpdating} onClick={handleDisable}>
+ Disable
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
);
return (
<>
- <form
- onSubmit={(e) => {
- e.preventDefault();
- handleSaveChanges();
- }}
- className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
- >
- <h2 className="mb-6 text-xl font-medium text-mineshaft-100">Two-factor Authentication</h2>
-
- {user && (
- <div className="space-y-4">
- <div className="max-w-sm">
- <FormControl
- label="Enable two-factor authentication"
- helperText="Protect your account with an additional verification step"
- >
- <Select
- value={formData.isMfaEnabled ? "enabled" : "disabled"}
- onValueChange={(value) =>
- handleFormDataChange("isMfaEnabled", value === "enabled")
- }
- className="w-full"
- position="popper"
- dropdownContainerClassName="max-w-none"
- >
- <SelectItem value="disabled">Disabled</SelectItem>
- <SelectItem value="enabled">Enabled</SelectItem>
- </Select>
- </FormControl>
- </div>
-
- {formData.isMfaEnabled && (
- <div className="max-w-sm">
- <FormControl
- label="Authentication method"
- helperText="Choose your preferred method for two-factor authentication"
- >
- <Select
- value={formData.selectedMfaMethod}
- onValueChange={(value) =>
- handleFormDataChange("selectedMfaMethod", value as MfaMethod)
- }
- className="w-full"
- position="popper"
- dropdownContainerClassName="max-w-none"
- >
- <SelectItem value={MfaMethod.EMAIL}>Email</SelectItem>
- <SelectItem value={MfaMethod.TOTP}>Mobile Authenticator</SelectItem>
- <SelectItem value={MfaMethod.WEBAUTHN}>Passkey (WebAuthn)</SelectItem>
- </Select>
- </FormControl>
- </div>
- )}
-
- {showMobileAuthSetup && !totpConfiguration?.isVerified && (
- <div className="space-y-6">
- <h3 className="mb-6 text-lg font-medium text-mineshaft-100">
- Setup Mobile Authenticator
- </h3>
-
- <div className="mb-8">
- <h4 className="mb-2 text-sm font-medium text-mineshaft-200">
- Step 1: Scan QR Code
- </h4>
- <p className="mb-4 text-sm text-mineshaft-300">
- Download a two-factor authentication app (Google Authenticator, Authy, etc.) and
- scan the QR code below
- </p>
-
- <div>
- {isTotpRegistrationLoading && (
- <div className="py-12">
- <ContentLoader />
- </div>
- )}
- {!isTotpRegistrationLoading && qrCodeUrl && (
- <div>
- <div className="mb-4 w-72 pl-4">
- <div className="inline-flex items-center justify-center rounded-xl bg-white p-6 shadow-lg">
- <img
- src={qrCodeUrl}
- alt="QR Code for mobile authenticator setup"
- className="h-48 w-48"
- />
- </div>
- </div>
- {totpRegistration?.otpUrl && (
- <div>
- <p className="mb-2 text-xs text-mineshaft-400">
- Can&apos;t scan? Enter this code manually:{" "}
- <code className="rounded-sm bg-mineshaft-700 px-3 py-1 font-mono text-sm text-mineshaft-100">
- {totpRegistration.otpUrl.split("secret=")[1]?.split("&")[0] ||
- "Loading..."}
- </code>
- </p>
- </div>
- )}
- </div>
- )}
- </div>
- </div>
-
- <div>
- <h4 className="mb-2 text-sm font-medium text-mineshaft-200">
- Step 2: Enter verification code
- </h4>
- <p className="mb-4 text-sm text-mineshaft-300">
- Enter the 6-digit code from your authenticator app to complete setup
- </p>
-
- <div className="max-w-48">
- <FormControl isRequired>
- <Input
- value={totpCode}
- onChange={(e) => {
- const value = e.target.value.replace(/\D/g, "").slice(0, 6);
- setTotpCode(value);
- }}
- onPaste={(e) => {
- e.preventDefault();
- const pastedData = e.clipboardData
- .getData("text")
- .replace(/\D/g, "")
- .slice(0, 6);
- setTotpCode(pastedData);
- }}
- placeholder="Enter 2FA code"
- maxLength={6}
- />
- </FormControl>
- </div>
- </div>
- </div>
- )}
-
- {hasChanges && (
- <div className="flex gap-2 pt-4">
- <Button
- type="submit"
- isLoading={isLoading}
- disabled={!isFormValid()}
- colorSchema="primary"
- variant="outline_bg"
- >
- Save Changes
- </Button>
- <Button
- type="button"
- variant="outline_bg"
- onClick={() => {
- if (user) {
- setFormData({
- isMfaEnabled: user.isMfaEnabled,
- selectedMfaMethod: user.selectedMfaMethod || MfaMethod.EMAIL
- });
- }
- setShowMobileAuthSetup(false);
- setTotpCode("");
- setShouldShowRecoveryCodes.off();
- }}
- disabled={isLoading}
- className="border-mineshaft-500 text-mineshaft-300 hover:border-mineshaft-400"
- >
- Cancel
- </Button>
- </div>
- )}
- </div>
- )}
- </form>
-
- {/* Management Sections - Separate from configuration form */}
- {user && (
- <div className="mt-6 mb-6 space-y-6">
- {/* Recovery Codes - account-level, shared across all MFA methods */}
- {shouldShowRecoveryCodesSection && (
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <h3 className="mb-1 text-lg font-medium text-mineshaft-100">Recovery Codes</h3>
- <p className="mb-4 text-sm text-mineshaft-400">
- Use a recovery code to sign in if you lose access to your two-factor authentication
- method.
- </p>
-
- {hasRecoveryCodes ? (
- <div className="space-y-4">
- <div className="flex flex-wrap gap-2">
- <Button
- colorSchema="secondary"
- variant="outline_bg"
- onClick={setShouldShowRecoveryCodes.toggle}
- >
- {shouldShowRecoveryCodes ? "Hide recovery codes" : "Show recovery codes"}
- </Button>
- <Button
- colorSchema="secondary"
- variant="outline_bg"
- onClick={() => handlePopUpOpen("regenerateRecoveryCodes")}
- >
- Regenerate recovery codes
- </Button>
- </div>
-
- {shouldShowRecoveryCodes && (
- <div className="w-fit rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4 pr-8">
- <div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">
- {(mfaRecoveryCodes || []).map((code, index) => (
- <div key={code} className="flex items-center text-mineshaft-200">
- <span className="w-8 text-right text-mineshaft-400">{index + 1}.</span>
- <span className="pl-2">{code}</span>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- ) : (
- <div>
- <p className="mb-3 text-sm text-mineshaft-400">
- You don&apos;t have any recovery codes yet. Generate a set and store them
- somewhere safe.
- </p>
- <Button
- colorSchema="secondary"
- variant="outline_bg"
- onClick={() => generateAndShowRecoveryCodes(false)}
- isLoading={isRotatingRecoveryCodes}
- >
- Generate recovery codes
- </Button>
- </div>
- )}
- </div>
- )}
-
- {/* Mobile Authenticator Management - Show if configured, regardless of active method */}
- {totpConfiguration?.isVerified && (
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <h3 className="mb-4 text-lg font-medium text-mineshaft-100">
- Mobile Authenticator Management
- </h3>
- <p className="mb-4 text-sm text-mineshaft-400">
- Manage your mobile authenticator configuration.
- </p>
-
- <div className="flex flex-wrap gap-2">
- <Button
- colorSchema="danger"
- variant="outline_bg"
- onClick={() => handlePopUpOpen("deleteTotpConfig")}
- >
- Remove Authenticator
- </Button>
- </div>
- </div>
- )}
-
- {/* Passkey Management - Always show */}
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-4 flex items-center justify-between">
- <div>
- <h3 className="text-lg font-medium text-mineshaft-100">Passkey Management</h3>
- <p className="mt-1 text-sm text-mineshaft-400">
- Manage your passkeys. Passkeys can be used for two-factor authentication.
- </p>
- </div>
- <Button
- colorSchema="primary"
- variant="outline_bg"
- onClick={() => {
- setCredentialName("");
- handlePopUpOpen("registerPasskey");
- }}
- isLoading={isGeneratingOptions}
- >
- Add Passkey
- </Button>
- </div>
-
- {(() => {
- if (isWebAuthnCredentialsLoading) {
- return <ContentLoader />;
- }
- if (webAuthnCredentials && webAuthnCredentials.length > 0) {
- return (
- <div className="space-y-3">
- {webAuthnCredentials.map((credential) => (
- <div
- key={credential.id}
- className="flex items-center justify-between rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4"
- >
- <div className="flex-1">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium text-mineshaft-100">
- {credential.name || "Unnamed Passkey"}
- </span>
- {credential.transports && credential.transports.length > 0 && (
- <span className="text-xs text-mineshaft-400">
- ({credential.transports.join(", ")})
- </span>
- )}
- </div>
- <div className="mt-1 text-xs text-mineshaft-400">
- Added {new Date(credential.createdAt).toLocaleDateString()}
- {credential.lastUsedAt && (
- <>
- {" "}
- · Last used {new Date(credential.lastUsedAt).toLocaleDateString()}
- </>
- )}
- </div>
- </div>
- <div className="flex gap-2">
- <Button
- size="xs"
- colorSchema="secondary"
- variant="outline_bg"
- onClick={() => {
- setSelectedCredentialId(credential.id);
- setCredentialName(credential.name || "");
- handlePopUpOpen("renameWebAuthnCredential");
- }}
- >
- Rename
- </Button>
- <Button
- size="xs"
- colorSchema="danger"
- variant="outline_bg"
- onClick={() => {
- setSelectedCredentialId(credential.id);
- handlePopUpOpen("deleteWebAuthnCredential");
- }}
- >
- Remove
- </Button>
- </div>
- </div>
- ))}
- </div>
- );
- }
- return (
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-6 text-center">
- <p className="text-sm text-mineshaft-300">
- No passkeys registered yet. Add a passkey to use it for two-factor
- authentication.
- </p>
- </div>
- );
- })()}
- </div>
- </div>
- )}
-
- <EmailServiceSetupModal
- isOpen={popUp.setUpEmail?.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("setUpEmail", isOpen)}
- />
- <DeleteActionModal
- isOpen={popUp.deleteTotpConfig.isOpen}
- title="Remove mobile authenticator?"
- subTitle="This action is irreversible. You'll have to go through the setup process to enable it again."
- onChange={(isOpen) => handlePopUpToggle("deleteTotpConfig", isOpen)}
- deleteKey="confirm"
- onDeleteApproved={handleTotpDeletion}
- />
-
- <RecoveryCodesDownload
- isOpen={popUp.downloadRecoveryCodes?.isOpen || false}
- onClose={() => {
- handlePopUpClose("downloadRecoveryCodes");
- setNewRecoveryCodes([]);
- }}
- recoveryCodes={
- newRecoveryCodes.length > 0 ? newRecoveryCodes : totpRegistration?.recoveryCodes || []
- }
- onDownloadComplete={() => {
- handlePopUpClose("downloadRecoveryCodes");
- setNewRecoveryCodes([]);
- }}
- />
-
- {registerPasskeyModal}
- {renamePasskeyModal}
-
- {/* Regenerate (rotate) recovery codes confirmation */}
- <Modal
- isOpen={popUp.regenerateRecoveryCodes?.isOpen || false}
- onOpenChange={(isOpen) => handlePopUpToggle("regenerateRecoveryCodes", isOpen)}
- >
- <ModalContent title="Regenerate recovery codes?">
- <div className="space-y-4">
- <p className="text-sm text-mineshaft-300">
- This generates a brand-new set of recovery codes and immediately invalidates all of
- your existing ones. Make sure to save the new codes.
- </p>
- <div className="flex gap-2">
- <Button
- colorSchema="danger"
- onClick={() => generateAndShowRecoveryCodes(true)}
- isLoading={isRotatingRecoveryCodes}
- >
- Regenerate codes
- </Button>
- <Button
- variant="outline_bg"
- onClick={() => handlePopUpClose("regenerateRecoveryCodes")}
- disabled={isRotatingRecoveryCodes}
- >
- Cancel
- </Button>
- </div>
- </div>
- </ModalContent>
- </Modal>
-
- {/* Delete Passkey Modal */}
- <DeleteActionModal
- isOpen={popUp.deleteWebAuthnCredential?.isOpen || false}
- title="Remove passkey?"
- subTitle="This action is irreversible. You'll need to register this passkey again if you want to use it in the future."
- onChange={(isOpen) => handlePopUpToggle("deleteWebAuthnCredential", isOpen)}
- deleteKey="confirm"
- onDeleteApproved={handleDeleteWebAuthnCredential}
- />
+ {user.isMfaEnabled ? enabledView : disabledView}
+ {/* Mounted at a stable position so enabling MFA mid-wizard (which flips the
+ view above) does not unmount the dialog and interrupt the flow. */}
+ <MfaSetupWizard isOpen={isWizardOpen} onOpenChange={setIsWizardOpen} />
</>
);
};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MethodSetupDialog.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MethodSetupDialog.tsx
new file mode 100644
index 0000000000..c144899e3c
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MethodSetupDialog.tsx
@@ -0,0 +1,37 @@
+import { MFA_METHOD_LABELS, VerifyStep } from "@app/components/mfa/setup";
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@app/components/v3";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+
+type Props = {
+ method: MfaMethod | null;
+ onOpenChange: (isOpen: boolean) => void;
+ onCompleted: () => void;
+};
+
+// Lightweight single-method setup used from the enabled view (MFA is already on
+// and recovery codes already exist, so no enable/recovery steps are needed).
+export const MethodSetupDialog = ({ method, onOpenChange, onCompleted }: Props) => {
+ return (
+ <Sheet open={Boolean(method)} onOpenChange={onOpenChange}>
+ <SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>
+ {method ? `Set up ${MFA_METHOD_LABELS[method]}` : "Set up method"}
+ </SheetTitle>
+ <SheetDescription>Configure this method as a second factor.</SheetDescription>
+ </SheetHeader>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-5">
+ {method && (
+ <VerifyStep
+ method={method}
+ onVerified={() => {
+ onCompleted();
+ onOpenChange(false);
+ }}
+ />
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx
new file mode 100644
index 0000000000..dad85af6c4
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx
@@ -0,0 +1,161 @@
+import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { FingerprintIcon, LucideIcon, MailIcon, SmartphoneIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Badge,
+ Button
+} from "@app/components/v3";
+import { userKeys } from "@app/hooks/api";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+import { useDeleteUserTotpConfiguration, useGetUserTotpConfiguration } from "@app/hooks/api/users";
+import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
+
+import { MethodSetupDialog } from "./MethodSetupDialog";
+import { PasskeyManagerDialog } from "./PasskeyManagerDialog";
+
+type MethodRowProps = {
+ icon: LucideIcon;
+ title: string;
+ description: string;
+ badge: React.ReactNode;
+ action: React.ReactNode;
+};
+
+const MethodRow = ({ icon: Icon, title, description, badge, action }: MethodRowProps) => (
+ <div className="flex items-center justify-between gap-4 py-3">
+ <div className="flex items-start gap-3">
+ <Icon className="mt-0.5 text-muted" />
+ <div>
+ <div className="flex items-center gap-2">
+ <p className="text-sm text-mineshaft-100">{title}</p>
+ {badge}
+ </div>
+ <p className="text-xs text-muted">{description}</p>
+ </div>
+ </div>
+ <div className="shrink-0">{action}</div>
+ </div>
+);
+
+export const MfaMethodsCard = () => {
+ const queryClient = useQueryClient();
+ const { data: totpConfiguration } = useGetUserTotpConfiguration();
+ const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
+ const { mutateAsync: deleteTotp, isPending: isDeletingTotp } = useDeleteUserTotpConfiguration();
+
+ const [setupMethod, setSetupMethod] = useState<MfaMethod | null>(null);
+ const [isPasskeyManagerOpen, setIsPasskeyManagerOpen] = useState(false);
+ const [isRemoveTotpOpen, setIsRemoveTotpOpen] = useState(false);
+
+ const isTotpConfigured = Boolean(totpConfiguration?.isVerified);
+ const passkeyCount = webAuthnCredentials.length;
+
+ const handleRemoveTotp = async () => {
+ try {
+ await deleteTotp();
+ setIsRemoveTotpOpen(false);
+ createNotification({ text: "Authenticator app removed", type: "success" });
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to remove authenticator app",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <h3 className="mb-2 text-sm font-medium text-mineshaft-100">Two-factor methods</h3>
+ <div className="divide-y divide-mineshaft-700">
+ <MethodRow
+ icon={MailIcon}
+ title="Email"
+ description="Receive one-time codes at your account email address to complete sign-in."
+ badge={<Badge variant="success">Configured</Badge>}
+ action={null}
+ />
+
+ <MethodRow
+ icon={SmartphoneIcon}
+ title="Authenticator app"
+ description="Use a TOTP authenticator app to get one-time codes when prompted at sign-in."
+ badge={
+ isTotpConfigured ? (
+ <Badge variant="success">Configured</Badge>
+ ) : (
+ <Badge variant="neutral">None</Badge>
+ )
+ }
+ action={
+ isTotpConfigured ? (
+ <Button variant="outline" size="sm" onClick={() => setIsRemoveTotpOpen(true)}>
+ Remove
+ </Button>
+ ) : (
+ <Button variant="outline" size="sm" onClick={() => setSetupMethod(MfaMethod.TOTP)}>
+ Set up
+ </Button>
+ )
+ }
+ />
+
+ <MethodRow
+ icon={FingerprintIcon}
+ title="Passkeys"
+ description="Passkeys use Face ID, Touch ID, a security key, or your device to sign in."
+ badge={
+ passkeyCount > 0 ? (
+ <Badge variant="success">{`${passkeyCount} registered`}</Badge>
+ ) : (
+ <Badge variant="neutral">None</Badge>
+ )
+ }
+ action={
+ <Button variant="outline" size="sm" onClick={() => setIsPasskeyManagerOpen(true)}>
+ Manage
+ </Button>
+ }
+ />
+ </div>
+
+ <MethodSetupDialog
+ method={setupMethod}
+ onOpenChange={(isOpen) => !isOpen && setSetupMethod(null)}
+ onCompleted={() => queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration })}
+ />
+
+ <PasskeyManagerDialog isOpen={isPasskeyManagerOpen} onOpenChange={setIsPasskeyManagerOpen} />
+
+ <AlertDialog open={isRemoveTotpOpen} onOpenChange={setIsRemoveTotpOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove authenticator app?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You&apos;ll need to set it up again to use it as a second factor.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isPending={isDeletingTotp}
+ onClick={handleRemoveTotp}
+ >
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
new file mode 100644
index 0000000000..bfacf23ba6
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
@@ -0,0 +1,151 @@
+import { useEffect, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { TriangleAlertIcon } from "lucide-react";
+
+import { MethodStep, RecoveryCodesView, VerifyStep, WIZARD_STEPS } from "@app/components/mfa/setup";
+import { createNotification } from "@app/components/notifications";
+import { ContentLoader } from "@app/components/v2";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Button,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Stepper,
+ StepperList,
+ StepperStep
+} from "@app/components/v3";
+import { userKeys, useUpdateUserMfa } from "@app/hooks/api";
+import { MfaMethod } from "@app/hooks/api/auth/types";
+import { useGetMfaRecoveryCodes } from "@app/hooks/api/users";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
+ const queryClient = useQueryClient();
+ const { mutateAsync: updateUserMfa } = useUpdateUserMfa();
+
+ const [step, setStep] = useState(0);
+ const [selectedMethod, setSelectedMethod] = useState<MfaMethod>(MfaMethod.TOTP);
+ const [hasDownloaded, setHasDownloaded] = useState(false);
+
+ const { data: recoveryCodes = [], isPending: isRecoveryCodesLoading } = useGetMfaRecoveryCodes(
+ isOpen && step === 2
+ );
+
+ useEffect(() => {
+ if (!isOpen) {
+ // Reset once the close animation is unlikely to be visible.
+ setStep(0);
+ setSelectedMethod(MfaMethod.TOTP);
+ setHasDownloaded(false);
+ }
+ }, [isOpen]);
+
+ const handleVerified = async () => {
+ try {
+ await updateUserMfa({ isMfaEnabled: true, selectedMfaMethod: selectedMethod });
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to enable two-factor authentication",
+ type: "error"
+ });
+ return;
+ }
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser }),
+ queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration }),
+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes })
+ ]);
+ setStep(2);
+ };
+
+ const handleDone = () => {
+ createNotification({ text: "Two-factor authentication enabled", type: "success" });
+ onOpenChange(false);
+ };
+
+ return (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Enable two-factor authentication</SheetTitle>
+ <SheetDescription>Add a second factor to protect your account.</SheetDescription>
+ </SheetHeader>
+
+ <div className="border-b border-border px-4 py-4">
+ <Stepper activeStep={step} orientation="horizontal">
+ <StepperList>
+ {WIZARD_STEPS.map((s, index) => (
+ <StepperStep
+ key={s.key}
+ index={index}
+ title={s.title}
+ description={s.description}
+ />
+ ))}
+ </StepperList>
+ </Stepper>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-5">
+ {step === 0 && (
+ <MethodStep selectedMethod={selectedMethod} onSelect={setSelectedMethod} />
+ )}
+ {step === 1 && <VerifyStep method={selectedMethod} onVerified={handleVerified} />}
+ {step === 2 && (
+ <div className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>Save your recovery codes</AlertTitle>
+ <AlertDescription>
+ Store these somewhere safe. Each code works once and lets you sign in if you lose
+ access to your other methods.
+ </AlertDescription>
+ </Alert>
+ {isRecoveryCodesLoading ? (
+ <ContentLoader />
+ ) : (
+ <RecoveryCodesView
+ recoveryCodes={recoveryCodes}
+ onDownloaded={() => setHasDownloaded(true)}
+ />
+ )}
+ </div>
+ )}
+ </div>
+
+ <SheetFooter className="items-center justify-between border-t">
+ <span className="text-xs text-muted">
+ Step {step + 1} of {WIZARD_STEPS.length}
+ </span>
+ <div className="flex items-center gap-3">
+ {step === 1 && (
+ <Button variant="outline" onClick={() => setStep(0)}>
+ Back
+ </Button>
+ )}
+ {step === 0 && (
+ <Button variant="org" onClick={() => setStep(1)}>
+ Continue
+ </Button>
+ )}
+ {step === 2 && (
+ <Button variant="org" isDisabled={!hasDownloaded} onClick={handleDone}>
+ Done
+ </Button>
+ )}
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/index.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/index.ts
new file mode 100644
index 0000000000..6a641a9078
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/index.ts
@@ -0,0 +1 @@
+export { MfaSetupWizard } from "./MfaSetupWizard";
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx
new file mode 100644
index 0000000000..ad358421ec
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx
@@ -0,0 +1,136 @@
+import { useState } from "react";
+import { startRegistration } from "@simplewebauthn/browser";
+import { FingerprintIcon, PlusIcon, TrashIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { ContentLoader } from "@app/components/v2";
+import {
+ Button,
+ Input,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle
+} from "@app/components/v3";
+import {
+ useDeleteWebAuthnCredential,
+ useGenerateRegistrationOptions,
+ useGetWebAuthnCredentials,
+ useVerifyRegistration
+} from "@app/hooks/api/webauthn";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {
+ const { data: credentials = [], isPending } = useGetWebAuthnCredentials();
+ const { mutateAsync: generateOptions } = useGenerateRegistrationOptions();
+ const { mutateAsync: verifyRegistration, isPending: isRegistering } = useVerifyRegistration();
+ const { mutateAsync: deleteCredential } = useDeleteWebAuthnCredential();
+
+ const [name, setName] = useState("");
+
+ const handleAdd = async () => {
+ try {
+ if (
+ !window.PublicKeyCredential ||
+ !window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
+ ) {
+ createNotification({ text: "WebAuthn is not supported on this browser", type: "error" });
+ return;
+ }
+ const options = await generateOptions();
+ const registrationResponse = await startRegistration({ optionsJSON: options });
+ await verifyRegistration({ registrationResponse, name: name.trim() || "Passkey" });
+ setName("");
+ createNotification({ text: "Passkey registered", type: "success" });
+ } catch (error: any) {
+ let text = "Failed to register passkey";
+ if (error.name === "NotAllowedError")
+ text = "Passkey registration was cancelled or timed out";
+ else if (error.name === "InvalidStateError")
+ text = "This passkey has already been registered";
+ else if (error?.response?.data?.message) text = error.response.data.message;
+ else if (error.message) text = error.message;
+ createNotification({ text, type: "error" });
+ }
+ };
+
+ const handleDelete = async (id: string) => {
+ try {
+ await deleteCredential({ id });
+ createNotification({ text: "Passkey removed", type: "success" });
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to remove passkey",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Manage passkeys</SheetTitle>
+ <SheetDescription>
+ Passkeys use Face ID, Touch ID, a security key, or your device to sign in.
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-5">
+ <div className="flex items-end gap-2">
+ <div className="flex-1">
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="New passkey name (optional)"
+ />
+ </div>
+ <Button variant="org" isPending={isRegistering} onClick={handleAdd}>
+ <PlusIcon /> Add
+ </Button>
+ </div>
+
+ {isPending ? (
+ <ContentLoader />
+ ) : (
+ <div className="flex flex-col gap-2">
+ {credentials.length === 0 && (
+ <p className="rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4 text-center text-sm text-muted">
+ No passkeys registered yet.
+ </p>
+ )}
+ {credentials.map((credential) => (
+ <div
+ key={credential.id}
+ className="flex items-center justify-between rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-3"
+ >
+ <div className="flex items-center gap-3">
+ <FingerprintIcon className="text-muted" />
+ <div>
+ <p className="text-sm text-mineshaft-100">
+ {credential.name || "Unnamed passkey"}
+ </p>
+ <p className="text-xs text-muted">
+ Added {new Date(credential.createdAt).toLocaleDateString()}
+ {credential.lastUsedAt &&
+ ` · Last used ${new Date(credential.lastUsedAt).toLocaleDateString()}`}
+ </p>
+ </div>
+ </div>
+ <Button variant="danger" size="sm" onClick={() => handleDelete(credential.id)}>
+ <TrashIcon /> Remove
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
new file mode 100644
index 0000000000..bbdbb767c4
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
@@ -0,0 +1,117 @@
+import { useState } from "react";
+import { EyeIcon, KeyRoundIcon, RefreshCwIcon } from "lucide-react";
+
+import { RecoveryCodesView } from "@app/components/mfa/setup";
+import { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Badge,
+ Button,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle
+} from "@app/components/v3";
+import { useGetMfaRecoveryCodes, useRotateMfaRecoveryCodes } from "@app/hooks/api/users";
+
+export const RecoveryOptionsCard = () => {
+ const { data: recoveryCodes = [] } = useGetMfaRecoveryCodes(true);
+ const { mutateAsync: rotate, isPending: isRotating } = useRotateMfaRecoveryCodes();
+
+ const [isViewOpen, setIsViewOpen] = useState(false);
+ const [isConfirmOpen, setIsConfirmOpen] = useState(false);
+ const [hasViewed, setHasViewed] = useState(false);
+
+ const handleRegenerate = async () => {
+ try {
+ await rotate();
+ setIsConfirmOpen(false);
+ setIsViewOpen(true);
+ createNotification({
+ text: "Generated new recovery codes. Your previous codes no longer work.",
+ type: "success"
+ });
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to regenerate recovery codes",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <h3 className="mb-4 text-sm font-medium text-mineshaft-100">Recovery options</h3>
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-start gap-3">
+ <KeyRoundIcon className="mt-0.5 text-muted" />
+ <div>
+ <div className="flex items-center gap-2">
+ <p className="text-sm text-mineshaft-100">Recovery codes</p>
+ {hasViewed && <Badge variant="neutral">Viewed</Badge>}
+ </div>
+ <p className="text-xs text-muted">
+ Recovery codes let you sign in if you lose access to your other methods. Each code
+ works once.
+ </p>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setHasViewed(true);
+ setIsViewOpen(true);
+ }}
+ >
+ <EyeIcon /> View
+ </Button>
+ <Button variant="outline" size="sm" onClick={() => setIsConfirmOpen(true)}>
+ <RefreshCwIcon /> Regenerate
+ </Button>
+ </div>
+ </div>
+
+ <Sheet open={isViewOpen} onOpenChange={setIsViewOpen}>
+ <SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Recovery codes</SheetTitle>
+ <SheetDescription>
+ Store these somewhere safe. Each code can only be used once.
+ </SheetDescription>
+ </SheetHeader>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-5">
+ <RecoveryCodesView recoveryCodes={recoveryCodes} />
+ </div>
+ </SheetContent>
+ </Sheet>
+
+ <AlertDialog open={isConfirmOpen} onOpenChange={setIsConfirmOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Regenerate recovery codes?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This generates a new set of recovery codes and immediately invalidates all existing
+ ones. Make sure to save the new codes.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" isPending={isRotating} onClick={handleRegenerate}>
+ Regenerate
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+};