Skip to content

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

simplify components

Thiago Araujo da Silvae98f324b9e54
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 6d83e9bf71..f1ba2eea85 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1167,7 +1167,7 @@ export const registerRoutes = async (
membershipUserDAL,
totpConfigDAL,
webAuthnCredentialDAL,
- mfaRecoveryCodeDAL
+ mfaRecoveryCodeService
});
const totpService = totpServiceFactory({
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
new file mode 100644
index 0000000000..286de2693b
--- /dev/null
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -0,0 +1,64 @@
+import { BadRequestError } from "@app/lib/errors";
+import { MfaMethod } from "@app/services/auth/auth-type";
+
+// Sensitive account actions that expose or weaken a login second factor require a
+// fresh MFA challenge, not just a valid session token. Each action binds its
+// step-up MFA session to a dedicated resource id so a session minted for one
+// action (e.g. viewing recovery codes) can't be replayed against another (e.g.
+// disabling MFA).
+export const MfaStepUpResource = {
+ RecoveryCodes: "mfa-recovery-codes",
+ DisableMfa: "mfa-disable"
+} as const;
+
+export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
+
+/**
+ * Enforces that the caller has completed a fresh MFA challenge before a sensitive
+ * action, reusing the Redis-backed step-up MFA session primitive (mirrors the PAM
+ * account-access flow).
+ *
+ * A verified session is reusable for the remainder of its TTL (5 min) and is bound
+ * to `resourceId`, so it cannot be replayed against a different action.
+ *
+ * - With a valid, verified session for this user + resource: returns immediately.
+ * - Otherwise (no session id, or one that is missing/expired/unverified/foreign):
+ * mints a fresh pending session (emailing the code when the user's method is
+ * email) and throws `SESSION_MFA_REQUIRED` carrying the new session id + method
+ * so the client can drive the challenge and retry.
+ */
+export const ensureStepUpMfa = async (
+ server: FastifyZodProvider,
+ {
+ userId,
+ resourceId,
+ mfaSessionId,
+ message
+ }: { userId: string; resourceId: TMfaStepUpResource; mfaSessionId?: string; message: string }
+) => {
+ if (
+ mfaSessionId &&
+ (await server.services.mfaSession.isMfaSessionActive({
+ mfaSessionId,
+ userId,
+ resourceId
+ }))
+ ) {
+ return;
+ }
+
+ const user = await server.services.user.getMe(userId);
+ const mfaMethod = (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
+
+ const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId, resourceId, mfaMethod);
+
+ if (mfaMethod === MfaMethod.EMAIL && user.email) {
+ await server.services.mfaSession.sendMfaCode(userId, user.email);
+ }
+
+ throw new BadRequestError({
+ message,
+ name: "SESSION_MFA_REQUIRED",
+ details: { mfaSessionId: newMfaSessionId, mfaMethod }
+ });
+};
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 0d4644f069..8a000d8892 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -3,70 +3,17 @@ import { z } from "zod";
import { UsersSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
-import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { ensureStepUpMfa, MfaStepUpResource } from "../mfa-step-up-fns";
const SantizedUserSchema = UsersSchema.omit({
hashedPassword: true
});
-// Recovery codes double as a login second factor, so reading or rotating them must
-// require a fresh MFA challenge — not just a valid session token. This binds the
-// step-up MFA session to a dedicated resource so a session minted for another
-// feature (e.g. PAM access) can't be replayed here.
-const RECOVERY_CODE_MFA_RESOURCE = "mfa-recovery-codes";
-
-/**
- * Enforces that the caller has completed an MFA challenge before recovery codes
- * are revealed or rotated, reusing the Redis-backed step-up MFA session primitive
- * (mirrors the PAM account-access flow).
- *
- * A verified session is reusable for the remainder of its TTL (5 min): once the
- * user has completed MFA they can view and rotate their codes repeatedly without
- * re-challenging. The session is NOT consumed on use — expiry is handled purely by
- * the Redis TTL.
- *
- * - With a valid, verified session for this user + resource: returns immediately.
- * - Otherwise (no session id, or one that is missing/expired/unverified/foreign):
- * mints a fresh pending session (emailing the code when the user's method is
- * email) and throws `SESSION_MFA_REQUIRED` carrying the new session id + method
- * so the client can drive the challenge and retry.
- */
-const ensureRecoveryCodeMfa = async (server: FastifyZodProvider, userId: string, mfaSessionId?: string) => {
- if (
- mfaSessionId &&
- (await server.services.mfaSession.isMfaSessionActive({
- mfaSessionId,
- userId,
- resourceId: RECOVERY_CODE_MFA_RESOURCE
- }))
- ) {
- return;
- }
-
- const user = await server.services.user.getMe(userId);
- const mfaMethod = (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
-
- const newMfaSessionId = await server.services.mfaSession.createMfaSession(
- userId,
- RECOVERY_CODE_MFA_RESOURCE,
- mfaMethod
- );
-
- if (mfaMethod === MfaMethod.EMAIL && user.email) {
- await server.services.mfaSession.sendMfaCode(userId, user.email);
- }
-
- throw new BadRequestError({
- message: "MFA verification is required to access recovery codes",
- name: "SESSION_MFA_REQUIRED",
- details: { mfaSessionId: newMfaSessionId, mfaMethod }
- });
-};
-
export const registerUserRouter = async (server: FastifyZodProvider) => {
const appCfg = getConfig();
@@ -361,7 +308,12 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
- await ensureRecoveryCodeMfa(server, req.permission.id, req.query.mfaSessionId);
+ await ensureStepUpMfa(server, {
+ userId: req.permission.id,
+ resourceId: MfaStepUpResource.RecoveryCodes,
+ mfaSessionId: req.query.mfaSessionId,
+ message: "MFA verification is required to access recovery codes"
+ });
const recoveryCodes = await server.services.mfaRecoveryCode.getRecoveryCodes({
userId: req.permission.id
});
@@ -390,7 +342,12 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
- await ensureRecoveryCodeMfa(server, req.permission.id, req.body?.mfaSessionId);
+ await ensureStepUpMfa(server, {
+ userId: req.permission.id,
+ resourceId: MfaStepUpResource.RecoveryCodes,
+ mfaSessionId: req.body?.mfaSessionId,
+ message: "MFA verification is required to access recovery codes"
+ });
const recoveryCodes = await server.services.mfaRecoveryCode.rotateRecoveryCodes({
userId: req.permission.id
});
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index c9d218339e..82e8098df9 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -7,6 +7,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMethod, AuthMode, MfaMethod } from "@app/services/auth/auth-type";
import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";
+import { ensureStepUpMfa, MfaStepUpResource } from "../mfa-step-up-fns";
import { SanitizedUserSchema } from "../sanitizedSchemas";
export const registerUserRouter = async (server: FastifyZodProvider) => {
@@ -63,10 +64,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
- // 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.
+ // Enroll a factor: proves possession of the factor in-request and persists it.
+ // This does NOT mint recovery codes; those are issued only when MFA is enabled
+ // (POST /me/mfa/activate).
server.route({
method: "POST",
url: "/me/mfa/enroll",
@@ -104,9 +104,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
})
]),
response: {
- 200: z.object({
- recoveryCodes: z.string().array().optional()
- })
+ 200: z.object({})
}
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
@@ -129,11 +127,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
});
}
- const recoveryCodes = await server.services.mfaRecoveryCode.ensureRecoveryCodes({
- userId: req.permission.id
- });
-
- return { recoveryCodes };
+ // Enrollment only proves/persists the factor. Recovery codes are minted
+ // solely when MFA is enabled (POST /me/mfa/activate), not here.
+ return {};
}
});
@@ -163,7 +159,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
- // Enable MFA. Requires the selected method to be configured; does not mint codes.
+ // Enable MFA. Requires the selected method to be configured (email always is),
+ // and issues a fresh recovery-code pool (invalidating any prior codes), returned
+ // once so the client can surface them to the user.
server.route({
method: "POST",
url: "/me/mfa/activate",
@@ -177,22 +175,25 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- user: SanitizedUserSchema
+ user: SanitizedUserSchema,
+ recoveryCodes: z.string().array()
})
}
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
- const user = await server.services.user.activateMfa({
+ const { user, recoveryCodes } = await server.services.user.activateMfa({
userId: req.permission.id,
selectedMfaMethod: req.body.selectedMfaMethod
});
- return { user };
+ return { user, recoveryCodes };
}
});
- // Disable MFA. Enrolled factors and recovery codes are preserved (no wipe).
+ // Disable MFA. Disabling weakens account security, so it is gated behind a fresh
+ // step-up MFA challenge (same primitive as viewing recovery codes). Enrolled
+ // factors are preserved; the recovery-code pool is wiped by the service.
server.route({
method: "POST",
url: "/me/mfa/deactivate",
@@ -201,6 +202,11 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
schema: {
operationId: "deactivateUserMfa",
+ body: z
+ .object({
+ mfaSessionId: z.string().trim().optional()
+ })
+ .optional(),
response: {
200: z.object({
user: SanitizedUserSchema
@@ -209,6 +215,13 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
+ await ensureStepUpMfa(server, {
+ userId: req.permission.id,
+ resourceId: MfaStepUpResource.DisableMfa,
+ mfaSessionId: req.body?.mfaSessionId,
+ message: "MFA verification is required to disable two-factor authentication"
+ });
+
const user = await server.services.user.deactivateMfa({
userId: req.permission.id
});
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 2e05cb583d..8ea1ebac30 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
@@ -5,7 +5,7 @@ import { TUserDALFactory } from "../user/user-dal";
import { TMfaRecoveryCodeDALFactory } from "./mfa-recovery-code-dal";
import { generateRecoveryCode } from "./mfa-recovery-code-fns";
import {
- TEnsureRecoveryCodesDTO,
+ TDeleteRecoveryCodesDTO,
TGetRecoveryCodesDTO,
TRotateRecoveryCodesDTO,
TVerifyAndConsumeRecoveryCodeDTO
@@ -112,23 +112,16 @@ 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 });
+ // Wipes the user's recovery-code pool. Used when MFA is disabled so codes never
+ // outlive the enabled state; a fresh pool is minted on the next enable.
+ const deleteRecoveryCodes = async ({ userId, tx }: TDeleteRecoveryCodesDTO) => {
+ await mfaRecoveryCodeDAL.delete({ userId }, tx);
};
return {
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 d537a6a041..7811db2f53 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,7 +15,7 @@ export type TRotateRecoveryCodesDTO = {
skipMfaEnabledCheck?: boolean;
};
-export type TEnsureRecoveryCodesDTO = {
+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 8c079ceb24..d4ee9ef24b 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -17,7 +17,7 @@ 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 { TMfaRecoveryCodeDALFactory } from "../mfa-recovery-code/mfa-recovery-code-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";
@@ -58,7 +58,7 @@ type TUserServiceFactoryDep = {
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById" | "delete">;
totpConfigDAL: Pick<TTotpConfigDALFactory, "findOne">;
webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "find">;
- mfaRecoveryCodeDAL: Pick<TMfaRecoveryCodeDALFactory, "findOne">;
+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "rotateRecoveryCodes" | "deleteRecoveryCodes">;
};
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
@@ -74,7 +74,7 @@ export const userServiceFactory = ({
userAliasDAL,
totpConfigDAL,
webAuthnCredentialDAL,
- mfaRecoveryCodeDAL
+ mfaRecoveryCodeService
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
const config = getConfig();
@@ -133,10 +133,10 @@ export const userServiceFactory = ({
}
};
- // 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.
+ // Enables MFA for the account. Enabling always issues a fresh recovery-code pool
+ // (invalidating any prior codes) and returns it so the caller can surface the
+ // codes to the user once. EMAIL requires no prior enrollment, so this doubles as
+ // first-time setup; other methods must already be configured (asserted below).
const activateMfa = async ({ userId, selectedMfaMethod }: TActivateUserMfaDTO) => {
const user = await userDAL.findById(userId);
if (!user || !user.email) throw new BadRequestError({ name: "Failed to enable MFA" });
@@ -144,22 +144,22 @@ export const userServiceFactory = ({
const method = selectedMfaMethod ?? (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
await assertMfaMethodConfigured(userId, method);
- const recoveryCodeConfig = await mfaRecoveryCodeDAL.findOne({ userId });
- if (!recoveryCodeConfig) {
- throw new BadRequestError({
- message: "Cannot enable MFA before enrolling a factor. Complete enrollment to generate recovery codes first."
- });
- }
+ const recoveryCodes = await mfaRecoveryCodeService.rotateRecoveryCodes({
+ userId,
+ skipMfaEnabledCheck: true
+ });
- return userDAL.updateById(userId, {
+ const updatedUser = await userDAL.updateById(userId, {
isMfaEnabled: true,
selectedMfaMethod: method
});
+
+ return { user: updatedUser, recoveryCodes };
};
- // 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.
+ // Disables MFA. Enrolled factors are preserved so re-enabling does not require
+ // re-enrollment, but the recovery-code pool is wiped so codes never outlive the
+ // enabled state; a fresh pool is issued on the next enable.
const deactivateMfa = async ({ userId }: TDeactivateUserMfaDTO) => {
const user = await userDAL.findById(userId);
if (!user) throw new BadRequestError({ name: "Failed to disable MFA" });
@@ -180,9 +180,13 @@ export const userServiceFactory = ({
}
}
- return userDAL.updateById(userId, {
+ const updatedUser = await userDAL.updateById(userId, {
isMfaEnabled: false
});
+
+ await mfaRecoveryCodeService.deleteRecoveryCodes({ userId });
+
+ return updatedUser;
};
// Updates only the preferred challenge method among already-configured factors.
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index 5c9011e410..7fbfd0e5f6 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -34,10 +34,10 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
SecurityClient.setMfaToken("");
}, []);
- const handleVerified = async (codes?: string[]) => {
+ const handleVerified = async () => {
try {
- await activateMfa({ selectedMfaMethod: method });
- setRecoveryCodes(codes ?? []);
+ const { recoveryCodes: codes } = await activateMfa({ selectedMfaMethod: method });
+ setRecoveryCodes(codes);
setPhase("recovery");
} catch (error: any) {
createNotification({
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index 70de04ff27..d9e83bec8e 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -15,7 +15,7 @@ import { useRegisterPasskey } from "@app/hooks/api/webauthn";
type Props = {
method: MfaMethod;
- onVerified: (recoveryCodes?: string[]) => void | Promise<void>;
+ onVerified: () => void | Promise<void>;
};
const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
@@ -36,9 +36,9 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- const { recoveryCodes } = await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
+ await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
createNotification({ text: "Authenticator app configured", type: "success" });
- await onVerified(recoveryCodes);
+ await onVerified();
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -104,9 +104,9 @@ const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- const { recoveryCodes } = await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
+ await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
createNotification({ text: "Email authentication configured", type: "success" });
- await onVerified(recoveryCodes);
+ await onVerified();
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -150,17 +150,15 @@ const WebAuthnVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) =>
const [name, setName] = useState("");
const handleRegister = async () => {
- let recoveryCodes: string[] | undefined;
const ok = await registerPasskey(name, async (registrationResponse, resolvedName) => {
- const res = await enrollMfa({
+ await enrollMfa({
method: MfaMethod.WEBAUTHN,
registrationResponse,
name: resolvedName
});
- recoveryCodes = res.recoveryCodes;
});
if (ok) {
- await onVerified(recoveryCodes);
+ await onVerified();
}
};
diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsx
index fbf37d732c..98fc60a9ac 100644
--- a/frontend/src/hooks/api/users/index.tsx
+++ b/frontend/src/hooks/api/users/index.tsx
@@ -12,7 +12,6 @@ export {
fetchOrgUsers,
useActivateMfa,
useAddUsersToOrg,
- useDeactivateMfa,
useDeleteMe,
useDeleteOrgMembership,
useEnrollMfa,
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index 72e58f37e9..ba740224d7 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -409,10 +409,8 @@ export const useRevokeMySessions = () => {
});
};
-// 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).
+// Enroll an MFA factor: proves and persists the factor. This does not mint or
+// return recovery codes; those are issued only when MFA is enabled (useActivateMfa).
export const useEnrollMfa = () => {
const queryClient = useQueryClient();
return useMutation({
@@ -426,12 +424,7 @@ export const useEnrollMfa = () => {
name?: string;
}
) => {
- const { data } = await apiRequest.post<{ recoveryCodes?: string[] }>(
- "/api/v2/users/me/mfa/enroll",
- dto
- );
-
- return { recoveryCodes: data.recoveryCodes };
+ await apiRequest.post("/api/v2/users/me/mfa/enroll", dto);
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
@@ -452,34 +445,24 @@ export const useSendMfaEnrollmentEmailCode = () =>
}
});
-// Enable MFA. Requires the selected method to be configured; never mints codes.
+// Enable MFA. Issues a fresh recovery-code pool (invalidating any prior codes)
+// and returns it once so the caller can display it to the user.
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");
+ const { data } = await apiRequest.post<{ user: unknown; recoveryCodes: string[] }>(
+ "/api/v2/users/me/mfa/activate",
+ {
+ selectedMfaMethod
+ }
+ );
- return { user: data.user };
+ return { user: data.user, recoveryCodes: data.recoveryCodes };
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });
}
});
};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index 9eb73a5825..fa1b691bc4 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
@@ -1,7 +1,7 @@
import { useState } from "react";
import { CircleAlertIcon, PowerIcon, ShieldCheckIcon } from "lucide-react";
-import { MFA_METHOD_ICONS, MFA_METHOD_LABELS } from "@app/components/mfa/setup";
+import { MFA_METHOD_ICONS, MFA_METHOD_LABELS, RecoveryCodesView } from "@app/components/mfa/setup";
import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
import {
@@ -19,23 +19,22 @@ import {
SelectContent,
SelectItem,
SelectTrigger,
- SelectValue
+ SelectValue,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle
} from "@app/components/v3";
-import {
- useActivateMfa,
- useDeactivateMfa,
- useGetOrganizations,
- useGetUser,
- useSetMfaMethod
-} from "@app/hooks/api";
+import { useActivateMfa, useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { useGetUserTotpConfiguration } from "@app/hooks/api/users";
import { AuthMethod } from "@app/hooks/api/users/types";
import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
import { MfaMethodsCard } from "./MfaMethodsCard";
-import { MfaSetupWizard } from "./MfaSetupWizard";
import { RecoveryOptionsCard } from "./RecoveryOptionsCard";
+import { useDisableMfa } from "./useDisableMfa";
const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";
@@ -43,15 +42,16 @@ export const MFASection = () => {
const { data: user, isPending } = useGetUser();
const { mutateAsync: setMfaMethod } = useSetMfaMethod();
const { mutateAsync: activateMfa } = useActivateMfa();
- const { mutateAsync: deactivateMfa, isPending: isUpdating } = useDeactivateMfa();
+ const { isBusy: isDisabling, disableMfa } = useDisableMfa();
const { data: totpConfiguration } = useGetUserTotpConfiguration();
const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
const { data: organizations = [] } = useGetOrganizations();
const isMfaEnforced = organizations.some((org) => org.enforceMfa);
- const [isWizardOpen, setIsWizardOpen] = useState(false);
const [isDisableOpen, setIsDisableOpen] = useState(false);
+ // Holds the fresh recovery codes returned on enable so they can be shown once.
+ const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[] | null>(null);
if (isPending || !user) {
return <ContentLoader />;
@@ -79,20 +79,14 @@ 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 hasRecoveryCodes = hasConfiguredFactor || user.isMfaEnabled;
+ // Recovery codes are issued on enable and wiped on disable, so they exist iff
+ // MFA is currently enabled.
+ const hasRecoveryCodes = user.isMfaEnabled;
const handleEnable = async () => {
- if (!hasConfiguredFactor) {
- setIsWizardOpen(true);
- return;
- }
try {
- await activateMfa({ selectedMfaMethod: selectedMethod });
+ const { recoveryCodes } = await activateMfa({ selectedMfaMethod: selectedMethod });
+ setNewRecoveryCodes(recoveryCodes);
createNotification({ text: "Two-factor authentication enabled", type: "success" });
} catch (error: any) {
createNotification({
@@ -114,18 +108,9 @@ export const MFASection = () => {
}
};
- const handleDisable = async () => {
- try {
- await deactivateMfa();
- setIsDisableOpen(false);
- createNotification({ text: "Two-factor authentication disabled", type: "success" });
- } catch (error: any) {
- createNotification({
- text: error?.response?.data?.message || "Failed to disable two-factor authentication",
- type: "error"
- });
- }
- };
+ // Disabling is a sensitive action, so it requires a fresh MFA challenge (same
+ // step-up flow as viewing recovery codes) before it goes through.
+ const handleDisable = () => disableMfa(() => setIsDisableOpen(false));
const disabledBanner = (
<div className="rounded-lg border border-border bg-card p-6">
@@ -202,7 +187,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 keeps your configured methods and recovery codes so you can re-enable it later."}
+ : "Turning this off keeps your configured methods, but your recovery codes are invalidated and a new set is issued when you re-enable."}
</p>
<Button variant="danger" isDisabled={isMfaEnforced} onClick={() => setIsDisableOpen(true)}>
<PowerIcon /> Disable two-factor authentication
@@ -224,22 +209,37 @@ export const MFASection = () => {
<AlertDialogHeader>
<AlertDialogTitle>Disable two-factor authentication?</AlertDialogTitle>
<AlertDialogDescription>
- 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.
+ You will first be asked to verify with MFA. After that, you will no longer be prompted
+ for a second factor when signing in. Your configured methods are kept, but your
+ current recovery codes are invalidated. Re-enabling issues a fresh set.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction variant="danger" isPending={isUpdating} onClick={handleDisable}>
+ <AlertDialogAction variant="danger" isPending={isDisabling} onClick={handleDisable}>
Disable
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- {/* Mounted at a stable position so enabling MFA mid-wizard (which flips the
- banner above) does not unmount the dialog and interrupt the flow. */}
- <MfaSetupWizard isOpen={isWizardOpen} onOpenChange={setIsWizardOpen} />
+ <Sheet
+ open={newRecoveryCodes !== null}
+ onOpenChange={(open) => !open && setNewRecoveryCodes(null)}
+ >
+ <SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Save your recovery codes</SheetTitle>
+ <SheetDescription>
+ Store these somewhere safe. Each code can only be used once, and this is the only time
+ they are shown.
+ </SheetDescription>
+ </SheetHeader>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-5">
+ <RecoveryCodesView recoveryCodes={newRecoveryCodes ?? []} />
+ </div>
+ </SheetContent>
+ </Sheet>
</>
);
};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
deleted file mode 100644
index ed9f351549..0000000000
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { useEffect, useState } from "react";
-import { useQueryClient } from "@tanstack/react-query";
-
-import { MethodStep, RecoveryCodesStep, VerifyStep, WIZARD_STEPS } from "@app/components/mfa/setup";
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- Stepper,
- StepperList,
- StepperStep
-} from "@app/components/v3";
-import { useActivateMfa, userKeys } from "@app/hooks/api";
-import { MfaMethod } from "@app/hooks/api/auth/types";
-
-type Props = {
- isOpen: boolean;
- onOpenChange: (isOpen: boolean) => void;
-};
-
-export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
- const queryClient = useQueryClient();
- const { mutateAsync: activateMfa } = useActivateMfa();
-
- const [step, setStep] = useState(0);
- const [selectedMethod, setSelectedMethod] = useState<MfaMethod>(MfaMethod.TOTP);
- const [hasSaved, setHasSaved] = useState(false);
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
-
- const hasRecoveryCodes = recoveryCodes.length > 0;
-
- useEffect(() => {
- if (!isOpen) {
- // Reset once the close animation is unlikely to be visible.
- setStep(0);
- setSelectedMethod(MfaMethod.TOTP);
- setHasSaved(false);
- setRecoveryCodes([]);
- }
- }, [isOpen]);
-
- const handleVerified = async (codes?: string[]) => {
- try {
- await activateMfa({ selectedMfaMethod: selectedMethod });
- setRecoveryCodes(codes ?? []);
- } 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">
- <RecoveryCodesStep recoveryCodes={recoveryCodes} onSaved={() => setHasSaved(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={hasRecoveryCodes && !hasSaved} 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
deleted file mode 100644
index 6a641a9078..0000000000
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { MfaSetupWizard } from "./MfaSetupWizard";
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useDisableMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useDisableMfa.ts
new file mode 100644
index 0000000000..c96af382f2
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useDisableMfa.ts
@@ -0,0 +1,47 @@
+import { useCallback } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+
+import { createNotification } from "@app/components/notifications";
+import { apiRequest } from "@app/config/request";
+import { userKeys } from "@app/hooks/api/users/query-keys";
+
+import { useMfaStepUp } from "./useMfaStepUp";
+
+/**
+ * Disabling MFA weakens account security, so it is gated behind a fresh step-up
+ * MFA challenge (the same primitive used to view/rotate recovery codes). This
+ * wraps the shared {@link useMfaStepUp} driver with the deactivate request. It
+ * calls apiRequest directly (rather than a mutation) so the expected
+ * SESSION_MFA_REQUIRED 400 doesn't surface a global mutation error toast.
+ */
+export const useDisableMfa = () => {
+ const queryClient = useQueryClient();
+ const { isBusy, runWithMfa } = useMfaStepUp();
+
+ const disableMfa = useCallback(
+ (onDisabled?: () => void) =>
+ runWithMfa(
+ async (mfaSessionId) => {
+ await apiRequest.post(
+ "/api/v2/users/me/mfa/deactivate",
+ mfaSessionId ? { mfaSessionId } : {}
+ );
+ },
+ {
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });
+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });
+ createNotification({
+ text: "Two-factor authentication disabled",
+ type: "success"
+ });
+ onDisabled?.();
+ },
+ errorText: "Failed to disable two-factor authentication"
+ }
+ ),
+ [runWithMfa, queryClient]
+ );
+
+ return { isBusy, disableMfa };
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
new file mode 100644
index 0000000000..47d6d47fce
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
@@ -0,0 +1,164 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import axios from "axios";
+
+import { createNotification } from "@app/components/notifications";
+import { apiRequest } from "@app/config/request";
+import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession";
+
+const MFA_POLL_INTERVAL = 2000;
+const MFA_TIMEOUT = 5 * 60 * 1000;
+
+// An action guarded by step-up MFA. It receives the verified session id (once
+// available) so it can replay itself against the backend. When the backend
+// requires a fresh challenge it responds with SESSION_MFA_REQUIRED, and the same
+// action is retried with the verified mfaSessionId.
+type StepUpAction<T> = (mfaSessionId?: string) => Promise<T>;
+
+type RunOptions<T> = {
+ onSuccess: (result: T) => void;
+ // Fallback message when the action fails for a reason other than a backend
+ // message (e.g. after verification).
+ errorText?: string;
+};
+
+/**
+ * Drives the step-up MFA flow shared by sensitive account actions (viewing or
+ * rotating recovery codes, disabling MFA). Mirrors the PAM credentials-reveal
+ * flow: run the action, and if the backend replies SESSION_MFA_REQUIRED, open the
+ * shared /mfa-session popup, poll its status, and replay the action with the
+ * verified session id.
+ *
+ * A verified session id is remembered and reused for subsequent actions until the
+ * backend rejects it (expired), at which point the popup challenge transparently
+ * re-runs. Callers own their own result/UI state; this hook owns the challenge.
+ */
+export const useMfaStepUp = () => {
+ const [isBusy, setIsBusy] = useState(false);
+
+ const popupRef = useRef<Window | null>(null);
+ const pollIntervalRef = useRef<ReturnType<typeof setInterval>>();
+ const isPollingRef = useRef(false);
+ // The most recently verified MFA session id, reused until the backend rejects it.
+ const activeSessionIdRef = useRef<string | null>(null);
+
+ const cleanup = useCallback(() => {
+ if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
+ if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
+ isPollingRef.current = false;
+ }, []);
+
+ useEffect(() => cleanup, [cleanup]);
+
+ const startMfaPolling = useCallback(
+ <T>(mfaSessionId: string, action: StepUpAction<T>, opts: RunOptions<T>) => {
+ const startTime = Date.now();
+
+ pollIntervalRef.current = setInterval(async () => {
+ if (isPollingRef.current) return;
+ isPollingRef.current = true;
+
+ try {
+ if (Date.now() - startTime > MFA_TIMEOUT) {
+ clearInterval(pollIntervalRef.current);
+ if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
+ createNotification({
+ type: "error",
+ text: "MFA verification timed out. If a popup did not appear, check that popups are not blocked for this site."
+ });
+ setIsBusy(false);
+ return;
+ }
+
+ const resp = await apiRequest.get<TMfaSessionStatusResponse>(
+ `/api/v2/mfa-sessions/${mfaSessionId}/status`
+ );
+
+ if (resp.data.status === MfaSessionStatus.ACTIVE) {
+ clearInterval(pollIntervalRef.current);
+ if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
+
+ try {
+ const result = await action(mfaSessionId);
+ activeSessionIdRef.current = mfaSessionId;
+ opts.onSuccess(result);
+ } catch {
+ createNotification({
+ type: "error",
+ text: opts.errorText ?? "Action failed after verification."
+ });
+ } finally {
+ setIsBusy(false);
+ }
+ return;
+ }
+
+ if (popupRef.current?.closed) {
+ clearInterval(pollIntervalRef.current);
+ createNotification({
+ type: "error",
+ text: "MFA verification was not completed. Please verify again to continue."
+ });
+ setIsBusy(false);
+ }
+ } catch {
+ clearInterval(pollIntervalRef.current);
+ createNotification({ type: "error", text: "MFA verification failed." });
+ setIsBusy(false);
+ } finally {
+ isPollingRef.current = false;
+ }
+ }, MFA_POLL_INTERVAL);
+ },
+ []
+ );
+
+ const runWithMfa = useCallback(
+ async <T>(action: StepUpAction<T>, opts: RunOptions<T>) => {
+ setIsBusy(true);
+ try {
+ const result = await action(activeSessionIdRef.current ?? undefined);
+ opts.onSuccess(result);
+ setIsBusy(false);
+ } catch (err) {
+ if (axios.isAxiosError(err) && err.response?.data?.error === "SESSION_MFA_REQUIRED") {
+ activeSessionIdRef.current = null;
+ const mfaSessionId = err.response.data.details?.mfaSessionId as string | undefined;
+
+ if (!mfaSessionId) {
+ createNotification({ type: "error", text: "MFA session could not be created." });
+ setIsBusy(false);
+ return;
+ }
+
+ popupRef.current = window.open(
+ `${window.location.origin}/mfa-session/${mfaSessionId}`,
+ "_blank"
+ );
+
+ if (!popupRef.current) {
+ createNotification({
+ type: "error",
+ text: "Could not open MFA popup. Please allow popups for this site."
+ });
+ setIsBusy(false);
+ return;
+ }
+
+ startMfaPolling(mfaSessionId, action, opts);
+ } else {
+ createNotification({
+ type: "error",
+ text:
+ (axios.isAxiosError(err) && err.response?.data?.message) ||
+ opts.errorText ||
+ "Action failed."
+ });
+ setIsBusy(false);
+ }
+ }
+ },
+ [startMfaPolling]
+ );
+
+ return { isBusy, runWithMfa };
+};
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts
index 6d2c0ae969..885c9bc580 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts
@@ -1,185 +1,63 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import axios from "axios";
+import { useCallback, useState } from "react";
import { createNotification } from "@app/components/notifications";
import { apiRequest } from "@app/config/request";
-import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession";
-const MFA_POLL_INTERVAL = 2000;
-const MFA_TIMEOUT = 5 * 60 * 1000;
-
-// Fetches or rotates the recovery codes. When the backend requires a fresh MFA
-// challenge it responds with SESSION_MFA_REQUIRED; the same fetcher is then
-// retried with the verified mfaSessionId.
-type CodesFetcher = (mfaSessionId?: string) => Promise<string[]>;
+import { useMfaStepUp } from "./useMfaStepUp";
/**
- * Drives the step-up MFA flow used to view or regenerate recovery codes. Since
- * both actions expose a login second factor, the backend only serves them once a
- * fresh MFA session is ACTIVE. This mirrors the PAM credentials-reveal flow: open
- * the shared /mfa-session popup, poll its status, and replay the original request
- * with the verified session id.
- *
- * Once verified, the session id is remembered and reused for subsequent view/
- * rotate actions for the remainder of its ~5 min TTL, so the user isn't
- * re-challenged on every click. When the backend reports the session is no longer
- * valid (expired), it responds with SESSION_MFA_REQUIRED again and we transparently
- * re-run the popup challenge.
+ * Viewing and rotating recovery codes both expose a login second factor, so the
+ * backend only serves them once a fresh step-up MFA session is ACTIVE. This wraps
+ * the shared {@link useMfaStepUp} driver with the recovery-code specific requests
+ * and sheet state.
*/
export const useRecoveryCodesMfa = () => {
- const [isBusy, setIsBusy] = useState(false);
+ const { isBusy, runWithMfa } = useMfaStepUp();
const [codes, setCodes] = useState<string[] | null>(null);
const [isSheetOpen, setIsSheetOpen] = useState(false);
- const popupRef = useRef<Window | null>(null);
- const pollIntervalRef = useRef<ReturnType<typeof setInterval>>();
- const isPollingRef = useRef(false);
- // The most recently verified MFA session id, reused until the backend rejects it.
- const activeSessionIdRef = useRef<string | null>(null);
-
- const cleanup = useCallback(() => {
- if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
- if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
- isPollingRef.current = false;
- }, []);
-
- useEffect(() => cleanup, [cleanup]);
-
- const startMfaPolling = useCallback((mfaSessionId: string, fetcher: CodesFetcher) => {
- const startTime = Date.now();
-
- pollIntervalRef.current = setInterval(async () => {
- if (isPollingRef.current) return;
- isPollingRef.current = true;
-
- try {
- if (Date.now() - startTime > MFA_TIMEOUT) {
- clearInterval(pollIntervalRef.current);
- if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
- createNotification({
- type: "error",
- text: "MFA verification timed out. If a popup did not appear, check that popups are not blocked for this site."
- });
- setIsBusy(false);
- return;
- }
-
- const resp = await apiRequest.get<TMfaSessionStatusResponse>(
- `/api/v2/mfa-sessions/${mfaSessionId}/status`
- );
-
- if (resp.data.status === MfaSessionStatus.ACTIVE) {
- clearInterval(pollIntervalRef.current);
- if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
-
- try {
- const result = await fetcher(mfaSessionId);
- activeSessionIdRef.current = mfaSessionId;
- setCodes(result);
- setIsSheetOpen(true);
- } catch {
- createNotification({
- type: "error",
- text: "Failed to load recovery codes after verification."
- });
- } finally {
- setIsBusy(false);
- }
- return;
- }
-
- if (popupRef.current?.closed) {
- clearInterval(pollIntervalRef.current);
- createNotification({
- type: "error",
- text: "MFA verification was not completed. Verify again to view or rotate your recovery codes."
- });
- setIsBusy(false);
- }
- } catch {
- clearInterval(pollIntervalRef.current);
- createNotification({ type: "error", text: "MFA verification failed." });
- setIsBusy(false);
- } finally {
- isPollingRef.current = false;
- }
- }, MFA_POLL_INTERVAL);
+ const showCodes = useCallback((result: string[]) => {
+ setCodes(result);
+ setIsSheetOpen(true);
}, []);
- const run = useCallback(
- async (fetcher: CodesFetcher) => {
- setIsBusy(true);
- try {
- const result = await fetcher(activeSessionIdRef.current ?? undefined);
- setCodes(result);
- setIsSheetOpen(true);
- setIsBusy(false);
- } catch (err) {
- if (axios.isAxiosError(err) && err.response?.data?.error === "SESSION_MFA_REQUIRED") {
- activeSessionIdRef.current = null;
- const mfaSessionId = err.response.data.details?.mfaSessionId as string | undefined;
-
- if (!mfaSessionId) {
- createNotification({ type: "error", text: "MFA session could not be created." });
- setIsBusy(false);
- return;
- }
-
- popupRef.current = window.open(
- `${window.location.origin}/mfa-session/${mfaSessionId}`,
- "_blank"
- );
-
- if (!popupRef.current) {
- createNotification({
- type: "error",
- text: "Could not open MFA popup. Please allow popups for this site."
- });
- setIsBusy(false);
- return;
- }
-
- startMfaPolling(mfaSessionId, fetcher);
- } else {
- createNotification({
- type: "error",
- text:
- (axios.isAxiosError(err) && err.response?.data?.message) ||
- "Failed to load recovery codes."
- });
- setIsBusy(false);
- }
- }
- },
- [startMfaPolling]
- );
-
const viewCodes = useCallback(
() =>
- run(async (mfaSessionId) => {
- const { data } = await apiRequest.get<{ recoveryCodes: string[] }>(
- "/api/v1/user/me/mfa/recovery-codes",
- { params: mfaSessionId ? { mfaSessionId } : undefined }
- );
- return data.recoveryCodes;
- }),
- [run]
+ runWithMfa(
+ async (mfaSessionId) => {
+ const { data } = await apiRequest.get<{ recoveryCodes: string[] }>(
+ "/api/v1/user/me/mfa/recovery-codes",
+ { params: mfaSessionId ? { mfaSessionId } : undefined }
+ );
+ return data.recoveryCodes;
+ },
+ { onSuccess: showCodes, errorText: "Failed to load recovery codes." }
+ ),
+ [runWithMfa, showCodes]
);
const regenerateCodes = useCallback(
() =>
- run(async (mfaSessionId) => {
- const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(
- "/api/v1/user/me/mfa/recovery-codes",
- mfaSessionId ? { mfaSessionId } : {}
- );
- createNotification({
- type: "success",
- text: "Generated new recovery codes. Your previous codes no longer work."
- });
- return data.recoveryCodes;
- }),
- [run]
+ runWithMfa(
+ async (mfaSessionId) => {
+ const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(
+ "/api/v1/user/me/mfa/recovery-codes",
+ mfaSessionId ? { mfaSessionId } : {}
+ );
+ return data.recoveryCodes;
+ },
+ {
+ onSuccess: (result) => {
+ createNotification({
+ type: "success",
+ text: "Generated new recovery codes. Your previous codes no longer work."
+ });
+ showCodes(result);
+ },
+ errorText: "Failed to load recovery codes."
+ }
+ ),
+ [runWithMfa, showCodes]
);
const closeSheet = useCallback(() => {