Skip to content

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

prompt MFA when viewing/rotating recovery keys

Thiago Araujo da Silvac95662fbb127
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 8bbb9b21a6..8616c7ed17 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -3,15 +3,72 @@ 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 } from "@app/services/auth/auth-type";
+import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";
+import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
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) {
+ const mfaSession = await server.services.mfaSession.getMfaSession(mfaSessionId);
+ if (
+ mfaSession &&
+ mfaSession.userId === userId &&
+ mfaSession.resourceId === RECOVERY_CODE_MFA_RESOURCE &&
+ mfaSession.status === MfaSessionStatus.ACTIVE
+ ) {
+ 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();
@@ -295,6 +352,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
schema: {
operationId: "getUserMfaRecoveryCodes",
+ querystring: z.object({
+ mfaSessionId: z.string().trim().optional()
+ }),
response: {
200: z.object({
recoveryCodes: z.string().array()
@@ -303,6 +363,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
+ await ensureRecoveryCodeMfa(server, req.permission.id, req.query.mfaSessionId);
const recoveryCodes = await server.services.mfaRecoveryCode.getRecoveryCodes({
userId: req.permission.id
});
@@ -318,6 +379,11 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
schema: {
operationId: "regenerateUserMfaRecoveryCodes",
+ body: z
+ .object({
+ mfaSessionId: z.string().trim().optional()
+ })
+ .optional(),
response: {
200: z.object({
recoveryCodes: z.string().array()
@@ -326,6 +392,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
+ await ensureRecoveryCodeMfa(server, req.permission.id, req.body?.mfaSessionId);
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 941ee1f5ac..2ecbbbe5fc 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -46,19 +46,20 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- user: SanitizedUserSchema
+ user: SanitizedUserSchema,
+ recoveryCodes: z.string().array().optional()
})
}
},
preHandler: verifyAuth([AuthMode.JWT, AuthMode.API_KEY], { requireOrg: false }),
handler: async (req) => {
- const user = await server.services.user.updateUserMfa({
+ const { user, recoveryCodes } = await server.services.user.updateUserMfa({
userId: req.permission.id,
isMfaEnabled: req.body.isMfaEnabled,
selectedMfaMethod: req.body.selectedMfaMethod
});
- return { user };
+ return { user, recoveryCodes };
}
});
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index a68eea9565..22a438d75c 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -136,6 +136,8 @@ export const userServiceFactory = ({
mfaMethods = isMfaEnabled ? ["email"] : [];
}
+ let recoveryCodes: string[] | undefined;
+
const updatedUser = await userDAL.transaction(async (tx) => {
const user2fa = await userDAL.updateById(
userId,
@@ -148,8 +150,7 @@ export const userServiceFactory = ({
);
if (isMfaEnabled === true && !wasMfaEnabled) {
- // MFA was just enabled in this transaction, so skip the redundant re-read.
- await mfaRecoveryCodeService.rotateRecoveryCodes({ userId, tx, skipMfaEnabledCheck: true });
+ recoveryCodes = await mfaRecoveryCodeService.rotateRecoveryCodes({ userId, tx, skipMfaEnabledCheck: true });
} else if (isMfaEnabled === false) {
await mfaRecoveryCodeService.deleteRecoveryCodes({ userId, tx });
await totpConfigDAL.delete({ userId }, tx);
@@ -159,7 +160,7 @@ export const userServiceFactory = ({
return user2fa;
});
- return updatedUser;
+ return { user: updatedUser, recoveryCodes };
};
const updateUserName = async (userId: string, firstName: string, lastName: string) => {
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index 25630f1ae2..591c0913d0 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -7,7 +7,7 @@ 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 { useUpdateUserMfa } from "@app/hooks/api/users";
import { MFA_METHOD_LABELS, RecoveryCodesView, VerifyStep } from "./setup";
@@ -23,7 +23,6 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
const { mutateAsync: updateUserMfa } = useUpdateUserMfa();
const [phase, setPhase] = useState<"preparing" | "verify" | "recovery">("preparing");
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
- const [isLoadingCodes, setIsLoadingCodes] = useState(false);
const [hasSaved, setHasSaved] = useState(false);
const hasPrepared = useRef(false);
@@ -40,9 +39,12 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
const mfaTempToken = getMfaTempToken();
SecurityClient.setMfaToken("");
try {
- // Enabling is the single place recovery codes are minted; idempotent if
- // MFA is already on.
- await updateUserMfa({ isMfaEnabled: true });
+ // Enabling is the single place recovery codes are minted; the response
+ // returns them once so we can show them after verification without a
+ // step-up MFA challenge (idempotent if MFA is already on, in which case
+ // no codes come back).
+ const { recoveryCodes: codes } = await updateUserMfa({ isMfaEnabled: true });
+ setRecoveryCodes(codes ?? []);
setPhase("verify");
} catch (error: any) {
// Restore the temp token so the user can reload and retry the normal
@@ -58,17 +60,6 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
prepare();
}, [updateUserMfa]);
- const loadRecoveryCodes = async () => {
- setIsLoadingCodes(true);
- try {
- setRecoveryCodes(await fetchMfaRecoveryCodes());
- } catch {
- setRecoveryCodes([]);
- } finally {
- setIsLoadingCodes(false);
- }
- };
-
const handleVerified = async () => {
try {
await updateUserMfa({ selectedMfaMethod: method });
@@ -76,7 +67,6 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
// preference update is best-effort
}
setPhase("recovery");
- await loadRecoveryCodes();
};
const handleContinue = async () => {
@@ -98,49 +88,41 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
{phase === "verify" && <VerifyStep method={method} onVerified={handleVerified} />}
- {phase === "recovery" &&
- (isLoadingCodes ? (
- <ContentLoader />
- ) : (
- <div className="flex flex-col gap-4">
- {hasRecoveryCodes ? (
- <>
- <Alert variant="warning">
- <TriangleAlertIcon />
- <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}
- onSaved={() => setHasSaved(true)}
- />
- </>
- ) : (
- <Alert variant="danger">
+ {phase === "recovery" && (
+ <div className="flex flex-col gap-4">
+ {hasRecoveryCodes ? (
+ <>
+ <Alert variant="warning">
<TriangleAlertIcon />
- <AlertTitle>Couldn&apos;t load recovery codes</AlertTitle>
- <AlertDescription className="flex flex-col items-start gap-3">
- Two-factor authentication is enabled, but we couldn&apos;t retrieve your recovery
- codes. Generate them before continuing so you don&apos;t get locked out.
- <Button variant="outline" size="sm" onClick={loadRecoveryCodes}>
- Try again
- </Button>
+ <AlertTitle>Save your recovery codes</AlertTitle>
+ <AlertDescription>
+ Store these somewhere safe. Each works once if you lose access to your other
+ methods.
</AlertDescription>
</Alert>
- )}
- <Button
- variant="org"
- isFullWidth
- isDisabled={!hasRecoveryCodes || !hasSaved}
- onClick={handleContinue}
- >
- Continue
- </Button>
- </div>
- ))}
+ <RecoveryCodesView recoveryCodes={recoveryCodes} onSaved={() => setHasSaved(true)} />
+ </>
+ ) : (
+ <Alert variant="danger">
+ <TriangleAlertIcon />
+ <AlertTitle>Couldn&apos;t load recovery codes</AlertTitle>
+ <AlertDescription>
+ Two-factor authentication is enabled, but we couldn&apos;t display your recovery
+ codes. Regenerate them from your security settings after signing in so you
+ don&apos;t get locked out.
+ </AlertDescription>
+ </Alert>
+ )}
+ <Button
+ variant="org"
+ isFullWidth
+ isDisabled={!hasRecoveryCodes || !hasSaved}
+ onClick={handleContinue}
+ >
+ Continue
+ </Button>
+ </div>
+ )}
</div>
);
};
diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsx
index 091df51856..b8028d6b6e 100644
--- a/frontend/src/hooks/api/users/index.tsx
+++ b/frontend/src/hooks/api/users/index.tsx
@@ -4,19 +4,16 @@ export {
useRemoveMyDuplicateAccounts,
useRequestEmailChangeOTP,
useRevokeMySessionById,
- useRotateMfaRecoveryCodes,
useSendEmailVerificationCode,
useUpdateUserEmail,
useVerifyCurrentEmailOTP,
useVerifyUserTotpRegistration
} from "./mutation";
export {
- fetchMfaRecoveryCodes,
fetchOrgUsers,
useAddUsersToOrg,
useDeleteMe,
useDeleteOrgMembership,
- useGetMfaRecoveryCodes,
useGetMyDuplicateAccount,
useGetMyIp,
useGetMyOrganizationProjects,
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index c99d0491d4..a07f162279 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -98,23 +98,6 @@ export const useDeleteUserTotpConfiguration = () => {
});
};
-export const useRotateMfaRecoveryCodes = () => {
- const queryClient = useQueryClient();
- return useMutation<{ recoveryCodes: string[] }, unknown, void>({
- mutationFn: async () => {
- const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(
- "/api/v1/user/me/mfa/recovery-codes"
- );
-
- return data;
- },
- onSuccess: (data) => {
- queryClient.setQueryData(userKeys.mfaRecoveryCodes, data.recoveryCodes);
- queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
- }
- });
-};
-
export const useResendOrgMemberInvitation = () => {
return useMutation({
mutationFn: async (dto: { membershipId: string }) => {
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index fa4065fa29..03a748778f 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -417,14 +417,15 @@ export const useUpdateUserMfa = () => {
isMfaEnabled?: boolean;
selectedMfaMethod?: MfaMethod;
}) => {
- const {
- data: { user }
- } = await apiRequest.patch("/api/v2/users/me/mfa", {
- isMfaEnabled,
- selectedMfaMethod
- });
+ const { data } = await apiRequest.patch<{ user: unknown; recoveryCodes?: string[] }>(
+ "/api/v2/users/me/mfa",
+ {
+ isMfaEnabled,
+ selectedMfaMethod
+ }
+ );
- return user;
+ return { user: data.user, recoveryCodes: data.recoveryCodes };
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
@@ -494,26 +495,3 @@ export const useGetUserTotpConfiguration = () => {
}
});
};
-
-export const fetchMfaRecoveryCodes = async () => {
- try {
- const { data } = await apiRequest.get<{ recoveryCodes: string[] }>(
- "/api/v1/user/me/mfa/recovery-codes"
- );
-
- return data.recoveryCodes;
- } catch (error) {
- if (error instanceof AxiosError && [404, 400].includes(error.response?.data?.statusCode)) {
- return [];
- }
- throw error;
- }
-};
-
-export const useGetMfaRecoveryCodes = (enabled = true) => {
- return useQuery({
- queryKey: userKeys.mfaRecoveryCodes,
- enabled,
- queryFn: fetchMfaRecoveryCodes
- });
-};
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 671149f272..7a1f55c575 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
@@ -4,7 +4,6 @@ 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,
@@ -22,7 +21,6 @@ import {
} 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;
@@ -36,12 +34,7 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
const [step, setStep] = useState(0);
const [selectedMethod, setSelectedMethod] = useState<MfaMethod>(MfaMethod.TOTP);
const [hasSaved, setHasSaved] = useState(false);
-
- const {
- data: recoveryCodes = [],
- isFetching: isRecoveryCodesFetching,
- refetch: refetchRecoveryCodes
- } = useGetMfaRecoveryCodes(isOpen && step === 2);
+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
const hasRecoveryCodes = recoveryCodes.length > 0;
@@ -51,12 +44,17 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
setStep(0);
setSelectedMethod(MfaMethod.TOTP);
setHasSaved(false);
+ setRecoveryCodes([]);
}
}, [isOpen]);
const handleVerified = async () => {
try {
- await updateUserMfa({ isMfaEnabled: true, selectedMfaMethod: selectedMethod });
+ const { recoveryCodes: codes } = await updateUserMfa({
+ isMfaEnabled: true,
+ selectedMfaMethod: selectedMethod
+ });
+ setRecoveryCodes(codes ?? []);
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Failed to enable two-factor authentication",
@@ -105,41 +103,36 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
<MethodStep selectedMethod={selectedMethod} onSelect={setSelectedMethod} />
)}
{step === 1 && <VerifyStep method={selectedMethod} onVerified={handleVerified} />}
- {step === 2 &&
- (isRecoveryCodesFetching ? (
- <ContentLoader />
- ) : (
- <div className="flex flex-col gap-4">
- {hasRecoveryCodes ? (
- <>
- <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>
- <RecoveryCodesView
- recoveryCodes={recoveryCodes}
- onSaved={() => setHasSaved(true)}
- />
- </>
- ) : (
- <Alert variant="danger">
+ {step === 2 && (
+ <div className="flex flex-col gap-4">
+ {hasRecoveryCodes ? (
+ <>
+ <Alert variant="warning">
<TriangleAlertIcon />
- <AlertTitle>Couldn&apos;t load recovery codes</AlertTitle>
- <AlertDescription className="flex flex-col items-start gap-3">
- Two-factor authentication is enabled, but we couldn&apos;t retrieve your
- recovery codes. Generate them before closing so you don&apos;t get locked out.
- <Button variant="outline" size="sm" onClick={() => refetchRecoveryCodes()}>
- Try again
- </Button>
+ <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>
- )}
- </div>
- ))}
+ <RecoveryCodesView
+ recoveryCodes={recoveryCodes}
+ onSaved={() => setHasSaved(true)}
+ />
+ </>
+ ) : (
+ <Alert variant="danger">
+ <TriangleAlertIcon />
+ <AlertTitle>Couldn&apos;t load recovery codes</AlertTitle>
+ <AlertDescription>
+ Two-factor authentication is enabled, but we couldn&apos;t display your recovery
+ codes. Regenerate them from the Recovery options section so you don&apos;t get
+ locked out.
+ </AlertDescription>
+ </Alert>
+ )}
+ </div>
+ )}
</div>
<SheetFooter className="items-center justify-between border-t">
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
index 0f9c5a5b51..3eb80034d7 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
@@ -2,7 +2,6 @@ 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,
@@ -12,7 +11,6 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
- Badge,
Button,
Sheet,
SheetContent,
@@ -20,31 +18,20 @@ import {
SheetHeader,
SheetTitle
} from "@app/components/v3";
-import { useGetMfaRecoveryCodes, useRotateMfaRecoveryCodes } from "@app/hooks/api/users";
+
+import { useRecoveryCodesMfa } from "./useRecoveryCodesMfa";
export const RecoveryOptionsCard = () => {
- const [isViewOpen, setIsViewOpen] = useState(false);
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
- const [hasViewed, setHasViewed] = useState(false);
- const { data: recoveryCodes = [] } = useGetMfaRecoveryCodes(isViewOpen);
- const { mutateAsync: rotate, isPending: isRotating } = useRotateMfaRecoveryCodes();
+ // Viewing and regenerating recovery codes both require a fresh MFA challenge,
+ // which this hook drives before returning the codes.
+ const { isBusy, codes, isSheetOpen, closeSheet, viewCodes, regenerateCodes } =
+ useRecoveryCodesMfa();
- 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"
- });
- }
+ const handleRegenerate = () => {
+ setIsConfirmOpen(false);
+ regenerateCodes();
};
return (
@@ -54,10 +41,7 @@ export const RecoveryOptionsCard = () => {
<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-foreground">Recovery codes</p>
- {hasViewed && <Badge variant="neutral">Viewed</Badge>}
- </div>
+ <p className="text-sm text-foreground">Recovery codes</p>
<p className="text-xs text-muted">
Recovery codes let you sign in if you lose access to your other methods. Each code
works once.
@@ -65,23 +49,21 @@ export const RecoveryOptionsCard = () => {
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
+ <Button variant="outline" size="sm" isDisabled={isBusy} onClick={viewCodes}>
+ <EyeIcon /> View
+ </Button>
<Button
variant="outline"
size="sm"
- onClick={() => {
- setHasViewed(true);
- setIsViewOpen(true);
- }}
+ isDisabled={isBusy}
+ onClick={() => setIsConfirmOpen(true)}
>
- <EyeIcon /> View
- </Button>
- <Button variant="outline" size="sm" onClick={() => setIsConfirmOpen(true)}>
<RefreshCwIcon /> Regenerate
</Button>
</div>
</div>
- <Sheet open={isViewOpen} onOpenChange={setIsViewOpen}>
+ <Sheet open={isSheetOpen} onOpenChange={(open) => !open && closeSheet()}>
<SheetContent side="right" className="flex flex-col gap-0 sm:max-w-lg">
<SheetHeader className="border-b">
<SheetTitle>Recovery codes</SheetTitle>
@@ -90,7 +72,7 @@ export const RecoveryOptionsCard = () => {
</SheetDescription>
</SheetHeader>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-5">
- <RecoveryCodesView recoveryCodes={recoveryCodes} />
+ <RecoveryCodesView recoveryCodes={codes ?? []} />
</div>
</SheetContent>
</Sheet>
@@ -101,12 +83,12 @@ export const RecoveryOptionsCard = () => {
<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.
+ ones. You&apos;ll be asked to verify with MFA first. Make sure to save the new codes.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction variant="danger" isPending={isRotating} onClick={handleRegenerate}>
+ <AlertDialogAction variant="danger" isPending={isBusy} onClick={handleRegenerate}>
Regenerate
</AlertDialogAction>
</AlertDialogFooter>
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts
new file mode 100644
index 0000000000..8a2b222015
--- /dev/null
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRecoveryCodesMfa.ts
@@ -0,0 +1,190 @@
+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;
+
+// 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[]>;
+
+/**
+ * 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.
+ */
+export const useRecoveryCodesMfa = () => {
+ const [isBusy, setIsBusy] = useState(false);
+ 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);
+ 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 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]
+ );
+
+ 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]
+ );
+
+ const closeSheet = useCallback(() => {
+ setIsSheetOpen(false);
+ setCodes(null);
+ }, []);
+
+ return { isBusy, codes, isSheetOpen, closeSheet, viewCodes, regenerateCodes };
+};