Skip to content

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

break endpoint responsabilities

Thiago Araujo da Silva544770d65033
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 405ddcc41d..abf351658f 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1175,8 +1175,7 @@ export const registerRoutes = async (
userAliasDAL,
membershipUserDAL,
totpConfigDAL,
- webAuthnCredentialDAL,
- mfaRecoveryCodeService
+ webAuthnCredentialDAL
});
const totpService = totpServiceFactory({
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index a0dda21e93..6fb94072dd 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -1,3 +1,4 @@
+import type { RegistrationResponseJSON } from "@simplewebauthn/server";
import { z } from "zod";
import { AuthTokenSessionsSchema } from "@app/db/schemas";
@@ -32,6 +33,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
+ // Set the preferred challenge method among already-configured factors. This
+ // never enables/disables MFA and never issues recovery codes.
server.route({
method: "PATCH",
url: "/me/mfa",
@@ -39,27 +42,178 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
rateLimit: writeLimit
},
schema: {
- operationId: "updateUserMfa",
+ operationId: "updateUserMfaMethod",
body: z.object({
- isMfaEnabled: z.boolean().optional(),
- selectedMfaMethod: z.nativeEnum(MfaMethod).optional()
+ selectedMfaMethod: z.nativeEnum(MfaMethod)
}),
response: {
200: z.object({
- user: SanitizedUserSchema,
+ user: SanitizedUserSchema
+ })
+ }
+ },
+ preHandler: verifyAuth([AuthMode.JWT, AuthMode.API_KEY], { requireOrg: false }),
+ handler: async (req) => {
+ const user = await server.services.user.setSelectedMfaMethod({
+ userId: req.permission.id,
+ selectedMfaMethod: req.body.selectedMfaMethod
+ });
+
+ return { user };
+ }
+ });
+
+ // Enroll a factor: proves possession of the factor in-request and, on the first
+ // enrollment, mints and returns the recovery-code pool once. Recovery codes are
+ // only ever returned by this proven-factor flow (or the step-up-gated
+ // recovery-code endpoints), never by a bare enable toggle.
+ server.route({
+ method: "POST",
+ url: "/me/mfa/enroll",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "enrollUserMfa",
+ body: z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal(MfaMethod.EMAIL),
+ code: z.string().trim()
+ }),
+ z.object({
+ method: z.literal(MfaMethod.TOTP),
+ totp: z.string().trim()
+ }),
+ z.object({
+ method: z.literal(MfaMethod.WEBAUTHN),
+ registrationResponse: z
+ .object({
+ id: z.string(),
+ rawId: z.string(),
+ response: z
+ .object({
+ clientDataJSON: z.string(),
+ attestationObject: z.string()
+ })
+ .passthrough(),
+ clientExtensionResults: z.record(z.unknown()).default({}),
+ type: z.literal("public-key")
+ })
+ .passthrough(),
+ name: z.string().optional()
+ })
+ ]),
+ response: {
+ 200: z.object({
recoveryCodes: z.string().array().optional()
})
}
},
+ preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ if (req.body.method === MfaMethod.EMAIL) {
+ await server.services.user.verifyMfaEnrollmentEmailCode({
+ userId: req.permission.id,
+ code: req.body.code
+ });
+ } else if (req.body.method === MfaMethod.TOTP) {
+ await server.services.totp.verifyUserTotpConfig({
+ userId: req.permission.id,
+ totp: req.body.totp
+ });
+ } else {
+ await server.services.webAuthn.verifyRegistrationResponse({
+ userId: req.permission.id,
+ registrationResponse: req.body.registrationResponse as RegistrationResponseJSON,
+ name: req.body.name
+ });
+ }
+
+ const recoveryCodes = await server.services.mfaRecoveryCode.ensureRecoveryCodes({
+ userId: req.permission.id
+ });
+
+ return { recoveryCodes };
+ }
+ });
+
+ // Email enrollment begin: emails a one-time code the user submits to POST
+ // /me/mfa/enroll to prove control of the account inbox before codes are minted.
+ server.route({
+ method: "POST",
+ url: "/me/mfa/enroll/email/code",
+ config: {
+ rateLimit: smtpRateLimit({
+ keyGenerator: (req) => req.permission?.id ?? req.realIp
+ })
+ },
+ schema: {
+ operationId: "sendMfaEnrollmentEmailCode",
+ response: {
+ 200: z.object({})
+ }
+ },
+ preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ await server.services.user.sendMfaEnrollmentEmailCode({
+ userId: req.permission.id
+ });
+
+ return {};
+ }
+ });
+
+ // Enable MFA. Requires the selected method to be configured; does not mint codes.
+ server.route({
+ method: "POST",
+ url: "/me/mfa/activate",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "activateUserMfa",
+ body: z.object({
+ selectedMfaMethod: z.nativeEnum(MfaMethod).optional()
+ }),
+ response: {
+ 200: z.object({
+ user: SanitizedUserSchema
+ })
+ }
+ },
preHandler: verifyAuth([AuthMode.JWT, AuthMode.API_KEY], { requireOrg: false }),
handler: async (req) => {
- const { user, recoveryCodes } = await server.services.user.updateUserMfa({
+ const user = await server.services.user.activateMfa({
userId: req.permission.id,
- isMfaEnabled: req.body.isMfaEnabled,
selectedMfaMethod: req.body.selectedMfaMethod
});
- return { user, recoveryCodes };
+ return { user };
+ }
+ });
+
+ // Disable MFA. Enrolled factors and recovery codes are preserved (no wipe).
+ server.route({
+ method: "POST",
+ url: "/me/mfa/deactivate",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "deactivateUserMfa",
+ response: {
+ 200: z.object({
+ user: SanitizedUserSchema
+ })
+ }
+ },
+ preHandler: verifyAuth([AuthMode.JWT, AuthMode.API_KEY], { requireOrg: false }),
+ handler: async (req) => {
+ const user = await server.services.user.deactivateMfa({
+ userId: req.permission.id
+ });
+
+ return { user };
}
});
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 50253279be..32d44dd1fb 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -70,7 +70,8 @@ export const getTokenConfig = (tokenType: TokenType) => {
const expiresAt = new Date(new Date().getTime() + 600000);
return { token, triesLeft, expiresAt };
}
- case TokenType.TOKEN_EMAIL_MFA: {
+ case TokenType.TOKEN_EMAIL_MFA:
+ case TokenType.TOKEN_EMAIL_MFA_ENROLLMENT: {
const token = generateSixDigitToken();
const triesLeft = 3;
const expiresAt = new Date(new Date().getTime() + 300000);
diff --git a/backend/src/services/auth-token/auth-token-types.ts b/backend/src/services/auth-token/auth-token-types.ts
index 69423ebded..4d9ded865a 100644
--- a/backend/src/services/auth-token/auth-token-types.ts
+++ b/backend/src/services/auth-token/auth-token-types.ts
@@ -5,6 +5,7 @@ export enum TokenType {
TOKEN_EMAIL_CHANGE_OTP = "emailChangeOtp",
TOKEN_EMAIL_CHANGE_CURRENT_OTP = "emailChangeCurrentOtp",
TOKEN_EMAIL_MFA = "emailMfa",
+ TOKEN_EMAIL_MFA_ENROLLMENT = "emailMfaEnrollment",
TOKEN_EMAIL_ORG_INVITATION = "organizationInvitation",
TOKEN_EMAIL_PASSWORD_RESET = "passwordReset",
TOKEN_EMAIL_PASSWORD_SETUP = "passwordSetup",
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 5bda4214ab..02f3ea695c 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
@@ -8,6 +8,7 @@ import { TMfaRecoveryCodeDALFactory } from "./mfa-recovery-code-dal";
import { generateRecoveryCode } from "./mfa-recovery-code-fns";
import {
TDeleteRecoveryCodesDTO,
+ TEnsureRecoveryCodesDTO,
TGetRecoveryCodesDTO,
TRotateRecoveryCodesDTO,
TVerifyAndConsumeRecoveryCodeDTO
@@ -128,6 +129,19 @@ export const mfaRecoveryCodeServiceFactory = ({
return recoveryCodes;
};
+ /**
+ * Mints the initial recovery-code pool the first time a user enrolls an MFA
+ * factor. If a pool already exists (e.g. enrolling a second factor) it is left
+ * untouched so previously saved codes stay valid, and `undefined` is returned.
+ * Returns the freshly minted codes so the caller can display them once.
+ */
+ const ensureRecoveryCodes = async ({ userId, tx }: TEnsureRecoveryCodesDTO) => {
+ const existingConfig = await mfaRecoveryCodeDAL.findOne({ userId }, tx);
+ if (existingConfig) return undefined;
+
+ return rotateRecoveryCodes({ userId, tx, skipMfaEnabledCheck: true });
+ };
+
const deleteRecoveryCodes = async ({ userId, tx }: TDeleteRecoveryCodesDTO) => {
await mfaRecoveryCodeDAL.delete({ userId }, tx);
};
@@ -136,6 +150,7 @@ export const mfaRecoveryCodeServiceFactory = ({
getRecoveryCodes,
verifyAndConsumeRecoveryCode,
rotateRecoveryCodes,
+ ensureRecoveryCodes,
deleteRecoveryCodes
};
};
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 7811db2f53..9f34cf596b 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
@@ -15,6 +15,11 @@ export type TRotateRecoveryCodesDTO = {
skipMfaEnabledCheck?: boolean;
};
+export type TEnsureRecoveryCodesDTO = {
+ userId: string;
+ tx?: Knex;
+};
+
export type TDeleteRecoveryCodesDTO = {
userId: string;
tx?: Knex;
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index a81811025a..424c74c021 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -17,12 +17,20 @@ import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { ActorType, AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType, MfaMethod } from "../auth/auth-type";
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";
+import {
+ TActivateUserMfaDTO,
+ TDeactivateUserMfaDTO,
+ TListUserGroupsDTO,
+ TSendMfaEnrollmentEmailCodeDTO,
+ TSetSelectedMfaMethodDTO,
+ TUpdateUserEmailDTO,
+ TVerifyCurrentEmailOTPDTO,
+ TVerifyMfaEnrollmentEmailCodeDTO
+} from "./user-types";
type TUserServiceFactoryDep = {
userDAL: Pick<
@@ -47,9 +55,8 @@ type TUserServiceFactoryDep = {
smtpService: Pick<TSmtpService, "sendMail">;
permissionService: TPermissionServiceFactory;
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById" | "delete">;
- totpConfigDAL: Pick<TTotpConfigDALFactory, "delete" | "findOne">;
- webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "delete" | "find">;
- mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "deleteRecoveryCodes" | "rotateRecoveryCodes">;
+ totpConfigDAL: Pick<TTotpConfigDALFactory, "findOne">;
+ webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "find">;
};
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
@@ -64,8 +71,7 @@ export const userServiceFactory = ({
permissionService,
userAliasDAL,
totpConfigDAL,
- webAuthnCredentialDAL,
- mfaRecoveryCodeService
+ webAuthnCredentialDAL
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
const config = getConfig();
@@ -104,73 +110,114 @@ export const userServiceFactory = ({
});
};
- const updateUserMfa = async ({ userId, isMfaEnabled, selectedMfaMethod }: TUpdateUserMfaDTO) => {
+ // A method can only be selected/activated once the user has actually configured
+ // that factor. EMAIL is always available since it uses the account email.
+ const assertMfaMethodConfigured = async (userId: string, method: MfaMethod) => {
+ if (method === MfaMethod.TOTP) {
+ const totpConfig = await totpConfigDAL.findOne({ userId, isVerified: true });
+ if (!totpConfig) {
+ throw new BadRequestError({
+ message: "Cannot select an authenticator app without a verified authenticator configured"
+ });
+ }
+ } else if (method === MfaMethod.WEBAUTHN) {
+ const credentials = await webAuthnCredentialDAL.find({ userId });
+ if (credentials.length === 0) {
+ throw new BadRequestError({
+ message: "Cannot select a passkey without a registered passkey"
+ });
+ }
+ }
+ };
+
+ // Enables MFA for the account. Recovery codes are NOT minted here: they are
+ // issued only by the enrollment flow, which proves a live factor first (see
+ // POST /me/mfa/enroll). This keeps recovery codes off any session that has not
+ // proven a factor.
+ const activateMfa = async ({ userId, selectedMfaMethod }: TActivateUserMfaDTO) => {
const user = await userDAL.findById(userId);
+ if (!user || !user.email) throw new BadRequestError({ name: "Failed to enable MFA" });
- if (!user || !user.email) throw new BadRequestError({ name: "Failed to toggle MFA" });
+ const method = selectedMfaMethod ?? (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
+ await assertMfaMethodConfigured(userId, method);
+
+ return userDAL.updateById(userId, {
+ isMfaEnabled: true,
+ selectedMfaMethod: method
+ });
+ };
- const wasMfaEnabled = user.isMfaEnabled;
+ // Disables MFA. Enrolled factors and recovery codes are intentionally preserved
+ // so re-enabling does not require re-enrollment; removing a factor is done
+ // explicitly via its own endpoint.
+ const deactivateMfa = async ({ userId }: TDeactivateUserMfaDTO) => {
+ const user = await userDAL.findById(userId);
+ if (!user) throw new BadRequestError({ name: "Failed to disable MFA" });
// 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"
- });
- }
+ // it, since doing so would lock them out of that org on the next login.
+ 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"
+ });
}
}
- if (isMfaEnabled !== false && selectedMfaMethod && selectedMfaMethod !== MfaMethod.EMAIL) {
- if (selectedMfaMethod === MfaMethod.TOTP) {
- const totpConfig = await totpConfigDAL.findOne({ userId, isVerified: true });
- if (!totpConfig) {
- throw new BadRequestError({
- message: "Cannot select an authenticator app without a verified authenticator configured"
- });
- }
- } else if (selectedMfaMethod === MfaMethod.WEBAUTHN) {
- const credentials = await webAuthnCredentialDAL.find({ userId });
- if (credentials.length === 0) {
- throw new BadRequestError({
- message: "Cannot select a passkey without a registered passkey"
- });
- }
- }
- }
+ return userDAL.updateById(userId, {
+ isMfaEnabled: false
+ });
+ };
- let recoveryCodes: string[] | undefined;
+ // Updates only the preferred challenge method among already-configured factors.
+ const setSelectedMfaMethod = async ({ userId, selectedMfaMethod }: TSetSelectedMfaMethodDTO) => {
+ const user = await userDAL.findById(userId);
+ if (!user) throw new BadRequestError({ name: "Failed to update MFA method" });
- const updatedUser = await userDAL.transaction(async (tx) => {
- const user2fa = await userDAL.updateById(
- userId,
- {
- isMfaEnabled,
- selectedMfaMethod: isMfaEnabled === false ? MfaMethod.EMAIL : selectedMfaMethod
- },
- tx
- );
+ await assertMfaMethodConfigured(userId, selectedMfaMethod);
- if (isMfaEnabled === true && !wasMfaEnabled) {
- recoveryCodes = await mfaRecoveryCodeService.rotateRecoveryCodes({ userId, tx, skipMfaEnabledCheck: true });
- } else if (isMfaEnabled === false) {
- await mfaRecoveryCodeService.deleteRecoveryCodes({ userId, tx });
- await totpConfigDAL.delete({ userId }, tx);
- await webAuthnCredentialDAL.delete({ userId }, tx);
- }
+ return userDAL.updateById(userId, { selectedMfaMethod });
+ };
+
+ // Email enrollment begin: sends a one-time code to the account email so control
+ // of the inbox can be proven before recovery codes are minted (mirrors the login
+ // MFA email code, but scoped to a dedicated enrollment token type).
+ const sendMfaEnrollmentEmailCode = async ({ userId }: TSendMfaEnrollmentEmailCodeDTO) => {
+ const user = await userDAL.findById(userId);
+ if (!user || !user.email) throw new BadRequestError({ name: "Failed to send MFA enrollment code" });
- return user2fa;
+ const code = await tokenService.createTokenForUser({
+ type: TokenType.TOKEN_EMAIL_MFA_ENROLLMENT,
+ userId
});
- return { user: updatedUser, recoveryCodes };
+ await smtpService.sendMail({
+ template: SmtpTemplates.EmailMfa,
+ subjectLine: "Infisical MFA code",
+ recipients: [user.email],
+ substitutions: {
+ code
+ }
+ });
+ };
+
+ // Email enrollment proof: throws unless the code matches the one emailed above.
+ const verifyMfaEnrollmentEmailCode = async ({ userId, code }: TVerifyMfaEnrollmentEmailCodeDTO) => {
+ try {
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_MFA_ENROLLMENT,
+ userId,
+ code
+ });
+ } catch (error) {
+ throw new BadRequestError({ message: "Invalid verification code", name: "VerifyMfaEnrollmentEmailCode" });
+ }
};
const updateUserName = async (userId: string, firstName: string, lastName: string) => {
@@ -599,7 +646,11 @@ export const userServiceFactory = ({
return {
sendEmailVerificationCode,
- updateUserMfa,
+ activateMfa,
+ deactivateMfa,
+ setSelectedMfaMethod,
+ sendMfaEnrollmentEmailCode,
+ verifyMfaEnrollmentEmailCode,
updateUserName,
updateAuthMethods,
requestEmailChangeOTP,
diff --git a/backend/src/services/user/user-types.ts b/backend/src/services/user/user-types.ts
index ab107a1e2d..1041fb90da 100644
--- a/backend/src/services/user/user-types.ts
+++ b/backend/src/services/user/user-types.ts
@@ -11,12 +11,29 @@ export enum UserEncryption {
V2 = 2
}
-export type TUpdateUserMfaDTO = {
+export type TActivateUserMfaDTO = {
userId: string;
- isMfaEnabled?: boolean;
selectedMfaMethod?: MfaMethod;
};
+export type TDeactivateUserMfaDTO = {
+ userId: string;
+};
+
+export type TSetSelectedMfaMethodDTO = {
+ userId: string;
+ selectedMfaMethod: MfaMethod;
+};
+
+export type TSendMfaEnrollmentEmailCodeDTO = {
+ userId: string;
+};
+
+export type TVerifyMfaEnrollmentEmailCodeDTO = {
+ userId: string;
+ code: string;
+};
+
export type TUpdateUserEmailDTO = {
userId: string;
newEmail: string;
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index c2d85cf626..a9c29f0fe4 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -6,7 +6,7 @@ import { ContentLoader } from "@app/components/v2";
import { Button } from "@app/components/v3";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { getMfaTempToken } from "@app/hooks/api/reactQuery";
-import { useUpdateUserMfa } from "@app/hooks/api/users";
+import { useActivateMfa } from "@app/hooks/api/users";
import { MFA_METHOD_LABELS, RecoveryCodesStep, VerifyStep } from "./setup";
@@ -17,9 +17,10 @@ type Props = {
// 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.
+// enroll the method (which proves the factor and mints recovery codes) -> enable
+// MFA -> save codes.
export const MfaEnrollment = ({ method, onComplete }: Props) => {
- const { mutateAsync: updateUserMfa } = useUpdateUserMfa();
+ const { mutateAsync: activateMfa } = useActivateMfa();
const [phase, setPhase] = useState<"preparing" | "verify" | "recovery">("preparing");
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
const [hasSaved, setHasSaved] = useState(false);
@@ -31,19 +32,13 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
if (hasPrepared.current) return;
hasPrepared.current = true;
- // The verification/enable endpoints authenticate with the base access token, so clear the
- // temporary MFA token before mounting the verify step (TOTP fires a registration request on
- // mount). MFA itself is enabled only once the method is verified — see handleVerified.
SecurityClient.setMfaToken("");
setPhase("verify");
}, []);
- const handleVerified = async () => {
+ const handleVerified = async (codes?: string[]) => {
try {
- const { recoveryCodes: codes } = await updateUserMfa({
- isMfaEnabled: true,
- selectedMfaMethod: method
- });
+ await activateMfa({ selectedMfaMethod: method });
setRecoveryCodes(codes ?? []);
setPhase("recovery");
} catch (error: any) {
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index 3164215bf3..9536c25dee 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { FingerprintIcon, MailIcon } from "lucide-react";
import QRCode from "qrcode";
@@ -6,18 +6,22 @@ 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, useVerifyUserTotpRegistration } from "@app/hooks/api/users";
+import {
+ useEnrollMfa,
+ useGetUserTotpRegistration,
+ useSendMfaEnrollmentEmailCode
+} from "@app/hooks/api/users";
import { useRegisterPasskey } from "@app/hooks/api/webauthn";
type Props = {
method: MfaMethod;
- onVerified: () => void | Promise<void>;
+ onVerified: (recoveryCodes?: string[]) => void | Promise<void>;
};
const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const [hasRegistered, setHasRegistered] = useState(false);
const { data: registration, isPending } = useGetUserTotpRegistration({ enabled: !hasRegistered });
- const { mutateAsync: verifyTotp, isPending: isVerifying } = useVerifyUserTotpRegistration();
+ const { mutateAsync: enrollMfa, isPending: isVerifying } = useEnrollMfa();
const [qrCodeUrl, setQrCodeUrl] = useState("");
const [totp, setTotp] = useState("");
@@ -32,9 +36,9 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- await verifyTotp({ totp: totp.trim() });
+ const { recoveryCodes } = await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
createNotification({ text: "Authenticator app configured", type: "success" });
- await onVerified();
+ await onVerified(recoveryCodes);
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -84,14 +88,30 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
};
const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
- const [isEnabling, setIsEnabling] = useState(false);
+ const { mutateAsync: sendCode } = useSendMfaEnrollmentEmailCode();
+ const { mutateAsync: enrollMfa, isPending: isVerifying } = useEnrollMfa();
+ const [code, setCode] = useState("");
+ const hasSentInitialCode = useRef(false);
- const handleEnable = async () => {
- setIsEnabling(true);
+ // Send the first code automatically when the step mounts.
+ useEffect(() => {
+ if (hasSentInitialCode.current) return;
+ hasSentInitialCode.current = true;
+ sendCode().catch(() => {
+ createNotification({ text: "Failed to send verification code", type: "error" });
+ });
+ }, [sendCode]);
+
+ const handleVerify = async () => {
try {
- await onVerified();
- } finally {
- setIsEnabling(false);
+ const { recoveryCodes } = await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
+ createNotification({ text: "Email authentication configured", type: "success" });
+ await onVerified(recoveryCodes);
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Invalid verification code",
+ type: "error"
+ });
}
};
@@ -100,24 +120,47 @@ const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
<div className="flex items-start gap-3 rounded-lg border border-border bg-container p-4">
<MailIcon className="mt-0.5 text-muted" />
<p className="text-sm text-muted">
- A one-time code will be sent to your account email each time you sign in. No setup is
- needed for this method.
+ We sent a one-time code to your account email. Enter it below to confirm you can receive
+ codes. A code will be sent the same way each time you sign in.
</p>
</div>
- <Button variant="org" isPending={isEnabling} onClick={handleEnable}>
- Enable email authentication
- </Button>
+ <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>
+ </div>
</div>
);
};
const WebAuthnVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const { registerPasskey, isRegistering } = useRegisterPasskey();
+ const { mutateAsync: enrollMfa } = useEnrollMfa();
const [name, setName] = useState("");
const handleRegister = async () => {
- if (await registerPasskey(name)) {
- await onVerified();
+ let recoveryCodes: string[] | undefined;
+ const ok = await registerPasskey(name, async (registrationResponse, resolvedName) => {
+ const res = await enrollMfa({
+ method: MfaMethod.WEBAUTHN,
+ registrationResponse,
+ name: resolvedName
+ });
+ recoveryCodes = res.recoveryCodes;
+ });
+ if (ok) {
+ await onVerified(recoveryCodes);
}
};
diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsx
index b8028d6b6e..7102a96bda 100644
--- a/frontend/src/hooks/api/users/index.tsx
+++ b/frontend/src/hooks/api/users/index.tsx
@@ -11,9 +11,12 @@ export {
} from "./mutation";
export {
fetchOrgUsers,
+ useActivateMfa,
useAddUsersToOrg,
+ useDeactivateMfa,
useDeleteMe,
useDeleteOrgMembership,
+ useEnrollMfa,
useGetMyDuplicateAccount,
useGetMyIp,
useGetMyOrganizationProjects,
@@ -29,8 +32,9 @@ export {
useLogoutUser,
useRegisterUserAction,
useRevokeMySessions,
+ useSendMfaEnrollmentEmailCode,
+ useSetMfaMethod,
useUpdateOrgMembership,
- useUpdateUserAuthMethods,
- useUpdateUserMfa
+ useUpdateUserAuthMethods
} from "./queries";
export { userKeys } from "./query-keys";
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index 03a748778f..54113effbf 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -1,3 +1,4 @@
+import type { RegistrationResponseJSON } from "@simplewebauthn/browser";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
@@ -407,25 +408,88 @@ export const useRevokeMySessions = () => {
});
};
-export const useUpdateUserMfa = () => {
+// Enroll an MFA factor: proves the factor and, on the first enrollment, returns
+// the freshly minted recovery codes so they can be shown once. Recovery codes are
+// never returned by the enable toggle — only by this proven-factor flow (or the
+// step-up-gated recovery-code endpoints).
+export const useEnrollMfa = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- isMfaEnabled,
- selectedMfaMethod
- }: {
- isMfaEnabled?: boolean;
- selectedMfaMethod?: MfaMethod;
- }) => {
- const { data } = await apiRequest.patch<{ user: unknown; recoveryCodes?: string[] }>(
- "/api/v2/users/me/mfa",
- {
- isMfaEnabled,
- selectedMfaMethod
- }
+ mutationFn: async (
+ dto:
+ | { method: MfaMethod.EMAIL; code: string }
+ | { method: MfaMethod.TOTP; totp: string }
+ | {
+ method: MfaMethod.WEBAUTHN;
+ registrationResponse: RegistrationResponseJSON;
+ name?: string;
+ }
+ ) => {
+ const { data } = await apiRequest.post<{ recoveryCodes?: string[] }>(
+ "/api/v2/users/me/mfa/enroll",
+ dto
);
- return { user: data.user, recoveryCodes: data.recoveryCodes };
+ return { recoveryCodes: data.recoveryCodes };
+ },
+ onSuccess() {
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });
+ queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
+ }
+ });
+};
+
+// Email enrollment begin: emails a one-time code to the account address that the
+// user submits via useEnrollMfa to prove inbox control before codes are minted.
+export const useSendMfaEnrollmentEmailCode = () =>
+ useMutation({
+ mutationFn: async () => {
+ await apiRequest.post("/api/v2/users/me/mfa/enroll/email/code");
+ }
+ });
+
+// Enable MFA. Requires the selected method to be configured; never mints codes.
+export const useActivateMfa = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ selectedMfaMethod }: { selectedMfaMethod?: MfaMethod }) => {
+ const { data } = await apiRequest.post<{ user: unknown }>("/api/v2/users/me/mfa/activate", {
+ selectedMfaMethod
+ });
+
+ return { user: data.user };
+ },
+ onSuccess() {
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });
+ }
+ });
+};
+
+// Disable MFA. Enrolled factors and recovery codes are preserved (no wipe).
+export const useDeactivateMfa = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async () => {
+ const { data } = await apiRequest.post<{ user: unknown }>("/api/v2/users/me/mfa/deactivate");
+
+ return { user: data.user };
+ },
+ onSuccess() {
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });
+ }
+ });
+};
+
+// Set the preferred challenge method among already-configured factors.
+export const useSetMfaMethod = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ selectedMfaMethod }: { selectedMfaMethod: MfaMethod }) => {
+ const { data } = await apiRequest.patch<{ user: unknown }>("/api/v2/users/me/mfa", {
+ selectedMfaMethod
+ });
+
+ return { user: data.user };
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
diff --git a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
index 180348de77..0497ebf659 100644
--- a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
+++ b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { startRegistration } from "@simplewebauthn/browser";
+import { RegistrationResponseJSON, startRegistration } from "@simplewebauthn/browser";
import { createNotification } from "@app/components/notifications";
@@ -7,6 +7,11 @@ import { useGenerateRegistrationOptions, useVerifyRegistration } from "./mutatio
const DEFAULT_PASSKEY_NAME = "Passkey";
+type VerifyAttestation = (
+ registrationResponse: RegistrationResponseJSON,
+ name: string
+) => Promise<void>;
+
// Shared passkey registration flow (browser support guard -> options -> prompt ->
// verify) with consistent success/error notifications. Returns true on success so
// callers can chain follow-up work (e.g. advancing a wizard step).
@@ -15,7 +20,7 @@ export const useRegisterPasskey = () => {
const { mutateAsync: verifyRegistration } = useVerifyRegistration();
const [isRegistering, setIsRegistering] = useState(false);
- const registerPasskey = async (name?: string): Promise<boolean> => {
+ const registerPasskey = async (name?: string, verify?: VerifyAttestation): Promise<boolean> => {
if (
!window.PublicKeyCredential ||
!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable
@@ -38,10 +43,12 @@ export const useRegisterPasskey = () => {
try {
const options = await generateOptions();
const registrationResponse = await startRegistration({ optionsJSON: options });
- await verifyRegistration({
- registrationResponse,
- name: name?.trim() || DEFAULT_PASSKEY_NAME
- });
+ const resolvedName = name?.trim() || DEFAULT_PASSKEY_NAME;
+ if (verify) {
+ await verify(registrationResponse, resolvedName);
+ } else {
+ await verifyRegistration({ registrationResponse, name: resolvedName });
+ }
createNotification({ text: "Passkey registered", type: "success" });
return true;
} catch (error: any) {
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index 5727c4980e..9d225475d3 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
@@ -1,5 +1,4 @@
import { useState } from "react";
-import { useQueryClient } from "@tanstack/react-query";
import { CircleAlertIcon, PowerIcon, ShieldCheckIcon } from "lucide-react";
import { MFA_METHOD_ICONS, MFA_METHOD_LABELS } from "@app/components/mfa/setup";
@@ -22,12 +21,17 @@ import {
SelectTrigger,
SelectValue
} from "@app/components/v3";
-import { useGetOrganizations, useGetUser, userKeys, useUpdateUserMfa } from "@app/hooks/api";
+import {
+ useActivateMfa,
+ useDeactivateMfa,
+ useGetOrganizations,
+ useGetUser,
+ useSetMfaMethod
+} from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { useGetUserTotpConfiguration } from "@app/hooks/api/users";
import { AuthMethod } from "@app/hooks/api/users/types";
import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
-import { webAuthnKeys } from "@app/hooks/api/webauthn/queries";
import { MfaMethodsCard } from "./MfaMethodsCard";
import { MfaSetupWizard } from "./MfaSetupWizard";
@@ -37,11 +41,12 @@ const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";
export const MFASection = () => {
const { data: user, isPending } = useGetUser();
- const { mutateAsync: updateUserMfa, isPending: isUpdating } = useUpdateUserMfa();
+ const { mutateAsync: setMfaMethod } = useSetMfaMethod();
+ const { mutateAsync: activateMfa } = useActivateMfa();
+ const { mutateAsync: deactivateMfa, isPending: isUpdating } = useDeactivateMfa();
const { data: totpConfiguration } = useGetUserTotpConfiguration();
const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
const { data: organizations = [] } = useGetOrganizations();
- const queryClient = useQueryClient();
const isMfaEnforced = organizations.some((org) => org.enforceMfa);
@@ -74,9 +79,30 @@ export const MFASection = () => {
? preferredMethod
: availableMethods[0];
+ // A configured non-email factor means the user can re-enable MFA directly
+ // (factors and recovery codes survive a disable), without re-running enrollment.
+ const hasConfiguredFactor =
+ Boolean(totpConfiguration?.isVerified) || webAuthnCredentials.length > 0;
+
+ const handleEnable = async () => {
+ if (!hasConfiguredFactor) {
+ setIsWizardOpen(true);
+ return;
+ }
+ try {
+ await activateMfa({ selectedMfaMethod: selectedMethod });
+ createNotification({ text: "Two-factor authentication enabled", type: "success" });
+ } catch (error: any) {
+ createNotification({
+ text: error?.response?.data?.message || "Failed to enable two-factor authentication",
+ type: "error"
+ });
+ }
+ };
+
const handlePreferredMethodChange = async (method: MfaMethod) => {
try {
- await updateUserMfa({ selectedMfaMethod: method });
+ await setMfaMethod({ selectedMfaMethod: method });
createNotification({ text: "Updated preferred 2FA method", type: "success" });
} catch (error: any) {
createNotification({
@@ -88,13 +114,7 @@ export const MFASection = () => {
const handleDisable = async () => {
try {
- await updateUserMfa({ isMfaEnabled: false });
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: userKeys.getUser }),
- queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration }),
- queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes }),
- queryClient.invalidateQueries({ queryKey: webAuthnKeys.credentials })
- ]);
+ await deactivateMfa();
setIsDisableOpen(false);
createNotification({ text: "Two-factor authentication disabled", type: "success" });
} catch (error: any) {
@@ -126,7 +146,7 @@ export const MFASection = () => {
</a>
</p>
<div className="mt-5">
- <Button variant="org" onClick={() => setIsWizardOpen(true)}>
+ <Button variant="org" onClick={handleEnable}>
<ShieldCheckIcon /> Enable two-factor authentication
</Button>
</div>
@@ -181,7 +201,7 @@ export const MFASection = () => {
<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."}
+ : "Turning this off keeps your configured methods and recovery codes so you can re-enable it later."}
</p>
<Button
variant="danger"
@@ -201,8 +221,8 @@ export const MFASection = () => {
<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.
+ You will no longer be prompted for a second factor when signing in. Your configured
+ methods and recovery codes are kept, so you can re-enable it at any time.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
index 7c9fd0564c..ed9f351549 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
@@ -15,7 +15,7 @@ import {
StepperList,
StepperStep
} from "@app/components/v3";
-import { userKeys, useUpdateUserMfa } from "@app/hooks/api";
+import { useActivateMfa, userKeys } from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
type Props = {
@@ -25,7 +25,7 @@ type Props = {
export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
const queryClient = useQueryClient();
- const { mutateAsync: updateUserMfa } = useUpdateUserMfa();
+ const { mutateAsync: activateMfa } = useActivateMfa();
const [step, setStep] = useState(0);
const [selectedMethod, setSelectedMethod] = useState<MfaMethod>(MfaMethod.TOTP);
@@ -44,12 +44,9 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
}
}, [isOpen]);
- const handleVerified = async () => {
+ const handleVerified = async (codes?: string[]) => {
try {
- const { recoveryCodes: codes } = await updateUserMfa({
- isMfaEnabled: true,
- selectedMfaMethod: selectedMethod
- });
+ await activateMfa({ selectedMfaMethod: selectedMethod });
setRecoveryCodes(codes ?? []);
} catch (error: any) {
createNotification({