Skip to content

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

send email when recovery code is used

Thiago Araujo da Silvae38c8133685d
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
index 8f9e9284d0..19a5602177 100644
--- a/backend/src/server/routes/mfa-step-up-fns.ts
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -2,13 +2,16 @@ 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).
+// fresh MFA challenge, not just a valid session token. The session binds to a
+// resource id so a session minted for one flow can't be replayed against an
+// unrelated one (e.g. a PAM account-access session can't be used here).
+//
+// Viewing recovery codes, rotating recovery codes, and disabling MFA are all
+// MFA-management actions of comparable risk, so they intentionally share a single
+// resource id: one fresh challenge covers all of them for the session TTL (5 min)
+// rather than re-prompting the user for each action in quick succession.
export const MfaStepUpResource = {
- RecoveryCodes: "mfa-recovery-codes",
- DisableMfa: "mfa-disable"
+ MfaManagement: "mfa-management"
} as const;
export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index ea29c9b220..6f5f003bf4 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -310,7 +310,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
- resourceId: MfaStepUpResource.RecoveryCodes,
+ resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.query.mfaSessionId,
message: "MFA verification is required to access recovery codes"
});
@@ -344,7 +344,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
- resourceId: MfaStepUpResource.RecoveryCodes,
+ resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.body?.mfaSessionId,
message: "MFA verification is required to access recovery codes"
});
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index ec299f150f..007840d8a2 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -194,7 +194,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
- resourceId: MfaStepUpResource.DisableMfa,
+ resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.body?.mfaSessionId,
message: "MFA verification is required to disable two-factor authentication"
});
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 75eca8deae..82795dea50 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -823,6 +823,22 @@ export const authLoginServiceFactory = ({
mfaMethod
});
+ if (isRecoveryCode && userEnc.email) {
+ await smtpService
+ .sendMail({
+ template: SmtpTemplates.MfaRecoveryCodeUsed,
+ subjectLine: "A recovery code was used to sign in to your Infisical account",
+ recipients: [userEnc.email],
+ substitutions: {
+ email: userEnc.email,
+ timestamp: new Date().toString(),
+ ip,
+ userAgent
+ }
+ })
+ .catch((err) => logger.error(err, "Failed to send MFA recovery code used email"));
+ }
+
return { token, user: { ...userEnc, hashedPassword: null } };
};
/*
diff --git a/backend/src/services/smtp/emails/MfaRecoveryCodeUsedTemplate.tsx b/backend/src/services/smtp/emails/MfaRecoveryCodeUsedTemplate.tsx
new file mode 100644
index 0000000000..a22f518da0
--- /dev/null
+++ b/backend/src/services/smtp/emails/MfaRecoveryCodeUsedTemplate.tsx
@@ -0,0 +1,68 @@
+import { Heading, Section, Text } from "@react-email/components";
+import React from "react";
+
+import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
+import { BaseLink } from "./BaseLink";
+
+interface MfaRecoveryCodeUsedTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
+ email: string;
+ timestamp: string;
+ ip: string;
+ userAgent: string;
+ isCloud: boolean;
+}
+
+export const MfaRecoveryCodeUsedTemplate = ({
+ email,
+ timestamp,
+ ip,
+ userAgent,
+ siteUrl,
+ isCloud
+}: MfaRecoveryCodeUsedTemplateProps) => {
+ return (
+ <BaseEmailWrapper
+ title="Recovery Code Used to Sign In"
+ preview="A recovery code was used to sign in to your Infisical account."
+ siteUrl={siteUrl}
+ >
+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
+ A recovery code was used to sign in to
+ <br />
+ <strong>{email}</strong>
+ </Heading>
+ <Section className="px-[24px] mt-[36px] pt-[26px] pb-[4px] text-[14px] border border-solid border-gray-200 rounded-md bg-gray-50">
+ <strong>Timestamp</strong>
+ <Text className="text-[14px] mt-[4px]">{timestamp}</Text>
+ <strong>IP Address</strong>
+ <Text className="text-[14px] mt-[4px]">{ip}</Text>
+ <strong>User Agent</strong>
+ <Text className="text-[14px] mt-[4px]">{userAgent}</Text>
+ </Section>
+ <Section className="mt-[24px] bg-gray-50 px-[24px] pt-[2px] pb-[16px] border border-solid border-gray-200 rounded-md text-gray-800">
+ <Text className="mb-[0px]">
+ If this was you, no action is needed. If you did not sign in, your account may be compromised: reset your
+ password, rotate your recovery codes and contact{" "}
+ {isCloud ? (
+ <BaseLink href="mailto:[email protected]">[email protected]</BaseLink>
+ ) : (
+ "your administrator"
+ )}
+ {" "}immediately.
+ </Text>
+ </Section>
+ </BaseEmailWrapper>
+ );
+};
+
+export default MfaRecoveryCodeUsedTemplate;
+
+MfaRecoveryCodeUsedTemplate.PreviewProps = {
+ email: "[email protected]",
+ ip: "127.0.0.1",
+ userAgent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15",
+ timestamp: "Tue Apr 29 2025 23:03:27 GMT+0000 (Coordinated Universal Time)",
+ isCloud: true,
+ siteUrl: "https://infisical.com"
+} as MfaRecoveryCodeUsedTemplateProps;
diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.ts
index cd04bbab4a..249db32cba 100644
--- a/backend/src/services/smtp/emails/index.ts
+++ b/backend/src/services/smtp/emails/index.ts
@@ -14,6 +14,7 @@ export * from "./ExternalImportSucceededTemplate";
export * from "./HealthAlertTemplate";
export * from "./HoneyTokenTriggeredTemplate";
export * from "./IntegrationSyncFailedTemplate";
+export * from "./MfaRecoveryCodeUsedTemplate";
export * from "./NewDeviceLoginTemplate";
export * from "./OAuthPasswordResetTemplate";
export * from "./OrgAdminBreakglassAccessTemplate";
diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.ts
index 5cefba33a5..9eef6e88ab 100644
--- a/backend/src/services/smtp/smtp-service.ts
+++ b/backend/src/services/smtp/smtp-service.ts
@@ -24,6 +24,7 @@ import {
HealthAlertTemplate,
HoneyTokenTriggeredTemplate,
IntegrationSyncFailedTemplate,
+ MfaRecoveryCodeUsedTemplate,
NewDeviceLoginTemplate,
OAuthPasswordResetTemplate,
OrgAdminBreakglassAccessTemplate,
@@ -76,6 +77,7 @@ export enum SmtpTemplates {
EmailChangeRequestNotification = "emailChangeRequestNotification",
SecretReminder = "secretReminder",
EmailMfa = "emailMfa",
+ MfaRecoveryCodeUsed = "mfaRecoveryCodeUsed",
UnlockAccount = "unlockAccount",
AccessApprovalRequest = "accessApprovalRequest",
AccessApprovalRequestUpdated = "accessApprovalRequestUpdated",
@@ -135,6 +137,7 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {
[SmtpTemplates.SignupEmailVerification]: SignupEmailVerificationTemplate,
[SmtpTemplates.SignupExistingAccount]: SignupExistingAccountTemplate,
[SmtpTemplates.EmailMfa]: EmailMfaTemplate,
+ [SmtpTemplates.MfaRecoveryCodeUsed]: MfaRecoveryCodeUsedTemplate,
[SmtpTemplates.AccessApprovalRequest]: AccessApprovalRequestTemplate,
[SmtpTemplates.AccessApprovalRequestUpdated]: AccessApprovalRequestUpdatedTemplate,
[SmtpTemplates.EmailVerification]: EmailVerificationTemplate,
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
index 47d6d47fce..c08e4d4a41 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
@@ -8,6 +8,15 @@ import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaS
const MFA_POLL_INTERVAL = 2000;
const MFA_TIMEOUT = 5 * 60 * 1000;
+// The most recently verified step-up MFA session id, shared across every
+// useMfaStepUp instance. The MFA-management actions (view/rotate recovery codes,
+// disable MFA) live in sibling components with their own hook instances but the
+// backend accepts one step-up session for all of them, so remembering the id in
+// module scope lets a challenge completed for one action satisfy the next until it
+// expires. It never drives rendering, and a stale id (e.g. after logout) is
+// harmless: the backend rejects it and a fresh challenge transparently re-runs.
+const sharedStepUpSession = { id: null as string | null };
+
// 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
@@ -38,8 +47,6 @@ export const useMfaStepUp = () => {
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);
@@ -79,7 +86,7 @@ export const useMfaStepUp = () => {
try {
const result = await action(mfaSessionId);
- activeSessionIdRef.current = mfaSessionId;
+ sharedStepUpSession.id = mfaSessionId;
opts.onSuccess(result);
} catch {
createNotification({
@@ -116,12 +123,12 @@ export const useMfaStepUp = () => {
async <T>(action: StepUpAction<T>, opts: RunOptions<T>) => {
setIsBusy(true);
try {
- const result = await action(activeSessionIdRef.current ?? undefined);
+ const result = await action(sharedStepUpSession.id ?? undefined);
opts.onSuccess(result);
setIsBusy(false);
} catch (err) {
if (axios.isAxiosError(err) && err.response?.data?.error === "SESSION_MFA_REQUIRED") {
- activeSessionIdRef.current = null;
+ sharedStepUpSession.id = null;
const mfaSessionId = err.response.data.details?.mfaSessionId as string | undefined;
if (!mfaSessionId) {