Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
make recovery code account scope when enabled MFA
Thiago Araujo da Silvac513efff8958
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex a7a0bec039..b37df27786 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -136,6 +136,7 @@ import { TLicenseClientFactory } from "@app/services/license-client";import { TMembershipGroupServiceFactory } from "@app/services/membership-group/membership-group-service";import { TMembershipIdentityServiceFactory } from "@app/services/membership-identity/membership-identity-service";import { TMembershipUserServiceFactory } from "@app/services/membership-user/membership-user-service";+import { TMfaRecoveryCodeServiceFactory } from "@app/services/mfa-recovery-code/mfa-recovery-code-service";import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";@@ -397,6 +398,7 @@ declare module "fastify" {projectTemplate: TProjectTemplateServiceFactory;totp: TTotpServiceFactory;webAuthn: TWebAuthnServiceFactory;+ mfaRecoveryCode: TMfaRecoveryCodeServiceFactory;appConnection: TAppConnectionServiceFactory;hsmConnector: THsmConnectorServiceFactory;secretSync: TSecretSyncServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex ea40ab6f11..3d7b3cd2ae 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -686,6 +686,9 @@ import {TUserGroupMembership,TUserGroupMembershipInsert,TUserGroupMembershipUpdate,+ TUserMfaRecoveryCodes,+ TUserMfaRecoveryCodesInsert,+ TUserMfaRecoveryCodesUpdate,TUsers,TUsersInsert,TUsersUpdate,@@ -1827,6 +1830,11 @@ declare module "knex/types/tables" {TWebauthnCredentialsInsert,TWebauthnCredentialsUpdate>;+ [TableName.UserMfaRecoveryCode]: KnexOriginal.CompositeTableType<+ TUserMfaRecoveryCodes,+ TUserMfaRecoveryCodesInsert,+ TUserMfaRecoveryCodesUpdate+ >;[TableName.AiMcpServer]: KnexOriginal.CompositeTableType<TAiMcpServers, TAiMcpServersInsert, TAiMcpServersUpdate>;[TableName.AiMcpServerTool]: KnexOriginal.CompositeTableType<TAiMcpServerTools,diff --git a/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.tsnew file mode 100644index 0000000000..7968b7bd5b--- /dev/null+++ b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts@@ -0,0 +1,67 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.UserMfaRecoveryCode))) {+ await knex.schema.createTable(TableName.UserMfaRecoveryCode, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("userId").notNullable();+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");+ t.binary("encryptedRecoveryCodes").notNullable();+ t.timestamps(true, true, true);+ // One account-level recovery-code pool per user. The unique constraint+ // also serves as the index for the userId foreign key.+ t.unique("userId");+ });++ await createOnUpdateTrigger(knex, TableName.UserMfaRecoveryCode);++ // Backfill from existing TOTP recovery codes. Both stores use+ // kmsService.encryptWithRootKey() (root-key AES-GCM, table-independent),+ // so the ciphertext is portable and can be copied without decrypting.+ await knex.raw(+ `INSERT INTO ?? ("userId", "encryptedRecoveryCodes")+ SELECT "userId", "encryptedRecoveryCodes"+ FROM ??+ WHERE "isVerified" = true+ ON CONFLICT ("userId") DO NOTHING`,+ [TableName.UserMfaRecoveryCode, TableName.TotpConfig]+ );+ }++ // Recovery codes now live in user_mfa_recovery_codes; TOTP no longer writes+ // this column. Make it nullable so new TOTP configs can omit it. A follow-up+ // migration can drop the column entirely.+ if (await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes")) {+ await knex.schema.alterTable(TableName.TotpConfig, (t) => {+ t.binary("encryptedRecoveryCodes").nullable().alter();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ // Re-populate the TOTP column from the account-level store before restoring+ // the NOT NULL constraint so rollback does not fail on existing rows.+ if (await knex.schema.hasTable(TableName.UserMfaRecoveryCode)) {+ await knex.raw(+ `UPDATE ?? tc+ SET "encryptedRecoveryCodes" = rc."encryptedRecoveryCodes"+ FROM ?? rc+ WHERE tc."userId" = rc."userId" AND tc."encryptedRecoveryCodes" IS NULL`,+ [TableName.TotpConfig, TableName.UserMfaRecoveryCode]+ );+ }++ if (await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes")) {+ await knex.schema.alterTable(TableName.TotpConfig, (t) => {+ t.binary("encryptedRecoveryCodes").notNullable().alter();+ });+ }++ if (await knex.schema.hasTable(TableName.UserMfaRecoveryCode)) {+ await dropOnUpdateTrigger(knex, TableName.UserMfaRecoveryCode);+ await knex.schema.dropTable(TableName.UserMfaRecoveryCode);+ }+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 40287775b6..8a9ce69ee1 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -263,6 +263,7 @@ export * from "./user-actions";export * from "./user-aliases";export * from "./user-encryption-keys";export * from "./user-group-membership";+export * from "./user-mfa-recovery-codes";export * from "./users";export * from "./vault-external-migration-configs";export * from "./webauthn-credentials";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 79ea79d642..794be2f5f5 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -174,6 +174,7 @@ export enum TableName {InternalKmsKeyVersion = "internal_kms_key_version",TotpConfig = "totp_configs",WebAuthnCredential = "webauthn_credentials",+ UserMfaRecoveryCode = "user_mfa_recovery_codes",// @depreciatedKmsKeyVersion = "kms_key_versions",WorkflowIntegrations = "workflow_integrations",diff --git a/backend/src/db/schemas/totp-configs.ts b/backend/src/db/schemas/totp-configs.tsindex d6ec115925..2ec06b5233 100644--- a/backend/src/db/schemas/totp-configs.ts+++ b/backend/src/db/schemas/totp-configs.ts@@ -13,7 +13,7 @@ export const TotpConfigsSchema = z.object({id: z.string().uuid(),userId: z.string().uuid(),isVerified: z.boolean().default(false),- encryptedRecoveryCodes: zodBuffer,+ encryptedRecoveryCodes: zodBuffer.nullable().optional(),encryptedSecret: zodBuffer,createdAt: z.date(),updatedAt: z.date()diff --git a/backend/src/db/schemas/user-mfa-recovery-codes.ts b/backend/src/db/schemas/user-mfa-recovery-codes.tsnew file mode 100644index 0000000000..62462ebde7--- /dev/null+++ b/backend/src/db/schemas/user-mfa-recovery-codes.ts@@ -0,0 +1,22 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const UserMfaRecoveryCodesSchema = z.object({+ id: z.string().uuid(),+ userId: z.string().uuid(),+ encryptedRecoveryCodes: zodBuffer,+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TUserMfaRecoveryCodes = z.infer<typeof UserMfaRecoveryCodesSchema>;+export type TUserMfaRecoveryCodesInsert = Omit<z.input<typeof UserMfaRecoveryCodesSchema>, TImmutableDBKeys>;+export type TUserMfaRecoveryCodesUpdate = Partial<Omit<z.input<typeof UserMfaRecoveryCodesSchema>, TImmutableDBKeys>>;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 87ba2187eb..cc68da4a7b 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -403,6 +403,8 @@ import { membershipIdentityDALFactory } from "@app/services/membership-identity/import { membershipIdentityServiceFactory } from "@app/services/membership-identity/membership-identity-service";import { membershipUserDALFactory } from "@app/services/membership-user/membership-user-dal";import { membershipUserServiceFactory } from "@app/services/membership-user/membership-user-service";+import { mfaRecoveryCodeDALFactory } from "@app/services/mfa-recovery-code/mfa-recovery-code-dal";+import { mfaRecoveryCodeServiceFactory } from "@app/services/mfa-recovery-code/mfa-recovery-code-service";import { mfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";import { microsoftTeamsIntegrationDALFactory } from "@app/services/microsoft-teams/microsoft-teams-integration-dal";import { microsoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";@@ -734,6 +736,7 @@ export const registerRoutes = async (const workflowIntegrationDAL = workflowIntegrationDALFactory(db);const totpConfigDAL = totpConfigDALFactory(db);const webAuthnCredentialDAL = webAuthnCredentialDALFactory(db);+ const mfaRecoveryCodeDAL = mfaRecoveryCodeDALFactory(db);const externalGroupOrgRoleMappingDAL = externalGroupOrgRoleMappingDALFactory(db);@@ -1156,6 +1159,11 @@ export const registerRoutes = async (queueService});+ const mfaRecoveryCodeService = mfaRecoveryCodeServiceFactory({+ mfaRecoveryCodeDAL,+ kmsService+ });+const userService = userServiceFactory({userDAL,orgDAL,@@ -1164,21 +1172,24 @@ export const registerRoutes = async (groupProjectDAL,smtpService,userAliasDAL,- membershipUserDAL+ membershipUserDAL,+ mfaRecoveryCodeService});const totpService = totpServiceFactory({totpConfigDAL,userDAL,kmsService,- keyStore+ keyStore,+ mfaRecoveryCodeService});const webAuthnService = webAuthnServiceFactory({webAuthnCredentialDAL,userDAL,tokenService,- keyStore+ keyStore,+ mfaRecoveryCodeService});const loginService = authLoginServiceFactory({@@ -1188,6 +1199,7 @@ export const registerRoutes = async (tokenService,orgDAL,totpService,+ mfaRecoveryCodeService,auditLogService,notificationService,membershipRoleDAL,@@ -3931,6 +3943,7 @@ export const registerRoutes = async (projectTemplate: projectTemplateService,totp: totpService,webAuthn: webAuthnService,+ mfaRecoveryCode: mfaRecoveryCodeService,appConnection: appConnectionService,hsmConnector: hsmConnectorService,secretSync: secretSyncService,diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.tsindex b11d7420da..918084eea4 100644--- a/backend/src/server/routes/v1/user-router.ts+++ b/backend/src/server/routes/v1/user-router.ts@@ -289,20 +289,50 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {}});+ // Account-level MFA recovery codes (shared across TOTP and WebAuthn/passkey)+ server.route({+ method: "GET",+ url: "/me/mfa/recovery-codes",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "getUserMfaRecoveryCodes",+ response: {+ 200: z.object({+ recoveryCodes: z.string().array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const recoveryCodes = await server.services.mfaRecoveryCode.getRecoveryCodes({+ userId: req.permission.id+ });+ return { recoveryCodes };+ }+ });+server.route({method: "POST",- url: "/me/totp/recovery-codes",+ url: "/me/mfa/recovery-codes",config: {rateLimit: writeLimit},schema: {- operationId: "createUserTotpRecoveryCodes"+ operationId: "regenerateUserMfaRecoveryCodes",+ response: {+ 200: z.object({+ recoveryCodes: z.string().array()+ })+ }},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- return server.services.totp.createUserTotpRecoveryCodes({+ const recoveryCodes = await server.services.mfaRecoveryCode.rotateRecoveryCodes({userId: req.permission.id});+ return { recoveryCodes };}});@@ -389,7 +419,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {response: {200: z.object({credentialId: z.string(),- name: z.string().nullable().optional()+ name: z.string().nullable().optional(),+ recoveryCodes: z.string().array()})}},diff --git a/backend/src/server/routes/v2/mfa-router.ts b/backend/src/server/routes/v2/mfa-router.tsindex 5fc54a5e4a..9a2a663706 100644--- a/backend/src/server/routes/v2/mfa-router.ts+++ b/backend/src/server/routes/v2/mfa-router.ts@@ -191,7 +191,9 @@ export const registerMfaRouter = async (server: FastifyZodProvider) => {}},handler: async (req, res) => {- return handleMfaVerification(req, res, server, req.body.recoveryCode, MfaMethod.TOTP, true);+ // Recovery codes are account-level; pass the method the challenge required+ // so users on any MFA method (email, TOTP or WebAuthn) can fall back to them.+ return handleMfaVerification(req, res, server, req.body.recoveryCode, req.mfa.requiredMfaMethod, true);}});diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex ccc642faa6..f657eef233 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -41,6 +41,7 @@ import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";import { TokenType } from "../auth-token/auth-token-types";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";+import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";import { TNotificationServiceFactory } from "../notification/notification-service";import { NotificationType } from "../notification/notification-types";import { TOrgDALFactory } from "../org/org-dal";@@ -76,7 +77,8 @@ type TAuthLoginServiceFactoryDep = {orgDAL: TOrgDALFactory;tokenService: TAuthTokenServiceFactory;smtpService: TSmtpService;- totpService: Pick<TTotpServiceFactory, "verifyUserTotp" | "verifyWithUserRecoveryCode">;+ totpService: Pick<TTotpServiceFactory, "verifyUserTotp">;+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "verifyAndConsumeRecoveryCode">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;membershipUserDAL: TMembershipUserDALFactory;membershipRoleDAL: TMembershipRoleDALFactory;@@ -93,6 +95,7 @@ export const authLoginServiceFactory = ({smtpService,orgDAL,totpService,+ mfaRecoveryCodeService,auditLogService,notificationService,membershipUserDAL,@@ -698,36 +701,35 @@ export const authLoginServiceFactory = ({const user = await userDAL.findById(userId);try {- if (mfaMethod !== requiredMfaMethod) {+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);++ // Recovery codes are account-level and bypass the configured second+ // factor regardless of the required MFA method (email, TOTP or WebAuthn).+ if (isRecoveryCode) {+ await mfaRecoveryCodeService.verifyAndConsumeRecoveryCode({+ userId,+ recoveryCode: mfaToken+ });+ } else if (mfaMethod !== requiredMfaMethod) {throw new BadRequestError({message: `Invalid MFA method. ${requiredMfaMethod} verification is required.`});- }-- enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);- if (mfaMethod === MfaMethod.EMAIL) {+ } else if (mfaMethod === MfaMethod.EMAIL) {await tokenService.validateTokenForUser({type: TokenType.TOKEN_EMAIL_MFA,userId,code: mfaToken});} else if (mfaMethod === MfaMethod.TOTP) {- if (isRecoveryCode) {- await totpService.verifyWithUserRecoveryCode({- userId,- recoveryCode: mfaToken- });- } else {- if (mfaToken.length !== 6) {- throw new BadRequestError({- message: "Please use a valid TOTP code."- });- }- await totpService.verifyUserTotp({- userId,- totp: mfaToken+ if (mfaToken.length !== 6) {+ throw new BadRequestError({+ message: "Please use a valid TOTP code."});}+ await totpService.verifyUserTotp({+ userId,+ totp: mfaToken+ });} else if (mfaMethod === MfaMethod.WEBAUTHN) {if (!mfaToken) {throw new BadRequestError({diff --git a/backend/src/services/mfa-recovery-code/mfa-recovery-code-dal.ts b/backend/src/services/mfa-recovery-code/mfa-recovery-code-dal.tsnew file mode 100644index 0000000000..a27fd2edae--- /dev/null+++ b/backend/src/services/mfa-recovery-code/mfa-recovery-code-dal.ts@@ -0,0 +1,11 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TMfaRecoveryCodeDALFactory = ReturnType<typeof mfaRecoveryCodeDALFactory>;++export const mfaRecoveryCodeDALFactory = (db: TDbClient) => {+ const mfaRecoveryCodeDal = ormify(db, TableName.UserMfaRecoveryCode);++ return mfaRecoveryCodeDal;+};diff --git a/backend/src/services/totp/totp-fns.ts b/backend/src/services/mfa-recovery-code/mfa-recovery-code-fns.tssimilarity index 100%rename from backend/src/services/totp/totp-fns.tsrename to backend/src/services/mfa-recovery-code/mfa-recovery-code-fns.tsdiff --git a/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts b/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.tsnew file mode 100644index 0000000000..211c0d96e8--- /dev/null+++ b/backend/src/services/mfa-recovery-code/mfa-recovery-code-service.ts@@ -0,0 +1,132 @@+import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";++import { TKmsServiceFactory } from "../kms/kms-service";+import { TMfaRecoveryCodeDALFactory } from "./mfa-recovery-code-dal";+import { generateRecoveryCode } from "./mfa-recovery-code-fns";+import {+ TDeleteRecoveryCodesDTO,+ TEnsureRecoveryCodesDTO,+ TGetRecoveryCodesDTO,+ TRotateRecoveryCodesDTO,+ TVerifyAndConsumeRecoveryCodeDTO+} from "./mfa-recovery-code-types";++type TMfaRecoveryCodeServiceFactoryDep = {+ mfaRecoveryCodeDAL: TMfaRecoveryCodeDALFactory;+ kmsService: Pick<TKmsServiceFactory, "encryptWithRootKey" | "decryptWithRootKey">;+};++export type TMfaRecoveryCodeServiceFactory = ReturnType<typeof mfaRecoveryCodeServiceFactory>;++const MAX_RECOVERY_CODE_LIMIT = 10;++export const mfaRecoveryCodeServiceFactory = ({+ mfaRecoveryCodeDAL,+ kmsService+}: TMfaRecoveryCodeServiceFactoryDep) => {+ // Generates a fresh pool of recovery codes alongside its root-key ciphertext.+ const generateEncryptedRecoveryCodes = () => {+ const encryptWithRoot = kmsService.encryptWithRootKey();+ const recoveryCodes = Array.from({ length: MAX_RECOVERY_CODE_LIMIT }).map(generateRecoveryCode);+ const encryptedRecoveryCodes = encryptWithRoot(Buffer.from(recoveryCodes.join(",")));++ return { recoveryCodes, encryptedRecoveryCodes };+ };++ /**+ * Ensures the user has an account-level recovery code pool. Idempotent: if a+ * pool already exists (e.g. from a prior TOTP setup) the existing codes are+ * returned unchanged; otherwise a fresh pool of codes is generated.+ * Called from both TOTP and passkey registration.+ */+ const ensureRecoveryCodes = async ({ userId }: TEnsureRecoveryCodesDTO) => {+ const decryptWithRoot = kmsService.decryptWithRootKey();++ return mfaRecoveryCodeDAL.transaction(async (tx) => {+ const existing = await mfaRecoveryCodeDAL.findOne({ userId }, tx);+ if (existing) {+ return decryptWithRoot(existing.encryptedRecoveryCodes).toString().split(",");+ }++ const { recoveryCodes, encryptedRecoveryCodes } = generateEncryptedRecoveryCodes();+ await mfaRecoveryCodeDAL.create({ userId, encryptedRecoveryCodes }, tx);+ return recoveryCodes;+ });+ };++ const getRecoveryCodes = async ({ userId }: TGetRecoveryCodesDTO) => {+ const recoveryCodeConfig = await mfaRecoveryCodeDAL.findOne({ userId });++ if (!recoveryCodeConfig) {+ throw new NotFoundError({+ message: "Recovery codes not found"+ });+ }++ const decryptWithRoot = kmsService.decryptWithRootKey();+ const recoveryCodes = decryptWithRoot(recoveryCodeConfig.encryptedRecoveryCodes).toString().split(",");++ return recoveryCodes;+ };++ const verifyAndConsumeRecoveryCode = async ({ userId, recoveryCode }: TVerifyAndConsumeRecoveryCodeDTO) => {+ const decryptWithRoot = kmsService.decryptWithRootKey();+ const encryptWithRoot = kmsService.encryptWithRootKey();++ return mfaRecoveryCodeDAL.transaction(async (tx) => {+ const recoveryCodeConfig = await mfaRecoveryCodeDAL.findOne({ userId }, tx);++ if (!recoveryCodeConfig) {+ throw new NotFoundError({+ message: "Recovery codes not found"+ });+ }++ const recoveryCodes = decryptWithRoot(recoveryCodeConfig.encryptedRecoveryCodes).toString().split(",");+ const remainingRecoveryCodes = recoveryCodes.filter((code) => code !== recoveryCode);+ if (remainingRecoveryCodes.length === recoveryCodes.length) {+ throw new ForbiddenRequestError({+ message: "Invalid recovery code"+ });+ }++ const encryptedRecoveryCodes = encryptWithRoot(Buffer.from(remainingRecoveryCodes.join(",")));+ await mfaRecoveryCodeDAL.updateById(recoveryCodeConfig.id, {+ encryptedRecoveryCodes+ });+ });+ };++ /**+ * Generates a completely new set of recovery codes, invalidating any existing+ * ones. Returns the fresh codes so the caller can display them once. If no+ * pool exists yet it is created.+ */+ const rotateRecoveryCodes = async ({ userId }: TRotateRecoveryCodesDTO) => {+ const { recoveryCodes, encryptedRecoveryCodes } = generateEncryptedRecoveryCodes();++ await mfaRecoveryCodeDAL.transaction(async (tx) => {+ const recoveryCodeConfig = await mfaRecoveryCodeDAL.findOne({ userId }, tx);++ if (recoveryCodeConfig) {+ await mfaRecoveryCodeDAL.updateById(recoveryCodeConfig.id, { encryptedRecoveryCodes }, tx);+ } else {+ await mfaRecoveryCodeDAL.create({ userId, encryptedRecoveryCodes }, tx);+ }+ });++ return recoveryCodes;+ };++ const deleteRecoveryCodes = async ({ userId }: TDeleteRecoveryCodesDTO) => {+ await mfaRecoveryCodeDAL.delete({ userId });+ };++ return {+ ensureRecoveryCodes,+ getRecoveryCodes,+ verifyAndConsumeRecoveryCode,+ rotateRecoveryCodes,+ 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.tsnew file mode 100644index 0000000000..854a759a6a--- /dev/null+++ b/backend/src/services/mfa-recovery-code/mfa-recovery-code-types.ts@@ -0,0 +1,20 @@+export type TEnsureRecoveryCodesDTO = {+ userId: string;+};++export type TGetRecoveryCodesDTO = {+ userId: string;+};++export type TVerifyAndConsumeRecoveryCodeDTO = {+ userId: string;+ recoveryCode: string;+};++export type TRotateRecoveryCodesDTO = {+ userId: string;+};++export type TDeleteRecoveryCodesDTO = {+ userId: string;+};diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.tsindex fbe6f72ca4..11595b255d 100644--- a/backend/src/services/mfa-session/mfa-session-service.ts+++ b/backend/src/services/mfa-session/mfa-session-service.ts@@ -13,7 +13,7 @@ type TMfaSessionServiceFactoryDep = {keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser" | "validateTokenForUser">;smtpService: Pick<TSmtpService, "sendMail">;- totpService: Pick<TTotpServiceFactory, "verifyUserTotp" | "verifyWithUserRecoveryCode">;+ totpService: Pick<TTotpServiceFactory, "verifyUserTotp">;};export type TMfaSessionServiceFactory = ReturnType<typeof mfaSessionServiceFactory>;diff --git a/backend/src/services/totp/totp-service.ts b/backend/src/services/totp/totp-service.tsindex 8af265a9ba..581a26a883 100644--- a/backend/src/services/totp/totp-service.ts+++ b/backend/src/services/totp/totp-service.ts@@ -4,17 +4,15 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { TKmsServiceFactory } from "../kms/kms-service";+import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";import { TUserDALFactory } from "../user/user-dal";import { TTotpConfigDALFactory } from "./totp-config-dal";-import { generateRecoveryCode } from "./totp-fns";import {- TCreateUserTotpRecoveryCodesDTO,TDeleteUserTotpConfigDTO,TGetUserTotpConfigDTO,TRegisterUserTotpDTO,TVerifyUserTotpConfigDTO,- TVerifyUserTotpDTO,- TVerifyWithUserRecoveryCodeDTO+ TVerifyUserTotpDTO} from "./totp-types";type TTotpServiceFactoryDep = {@@ -22,15 +20,20 @@ type TTotpServiceFactoryDep = {totpConfigDAL: TTotpConfigDALFactory;kmsService: TKmsServiceFactory;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "ensureRecoveryCodes" | "getRecoveryCodes">;};authenticator.options = { window: 1 };export type TTotpServiceFactory = ReturnType<typeof totpServiceFactory>;-const MAX_RECOVERY_CODE_LIMIT = 10;--export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStore }: TTotpServiceFactoryDep) => {+export const totpServiceFactory = ({+ totpConfigDAL,+ kmsService,+ userDAL,+ keyStore,+ mfaRecoveryCodeService+}: TTotpServiceFactoryDep) => {const getUserTotpConfig = async ({ userId }: TGetUserTotpConfigDTO) => {const totpConfig = await totpConfigDAL.findOne({userId@@ -48,8 +51,7 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStor});}- const decryptWithRoot = kmsService.decryptWithRootKey();- const recoveryCodes = decryptWithRoot(totpConfig.encryptedRecoveryCodes).toString().split(",");+ const recoveryCodes = await mfaRecoveryCodeService.getRecoveryCodes({ userId });return {isVerified: totpConfig.isVerified,@@ -87,22 +89,21 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStor// create new TOTP configurationconst secret = authenticator.generateSecret();const encryptedSecret = encryptWithRoot(Buffer.from(secret));- const recoveryCodes = Array.from({ length: MAX_RECOVERY_CODE_LIMIT }).map(generateRecoveryCode);- const encryptedRecoveryCodes = encryptWithRoot(Buffer.from(recoveryCodes.join(",")));const newTotpConfig = await totpConfigDAL.create({userId,- encryptedRecoveryCodes,encryptedSecret});return newTotpConfig;});+ // Recovery codes are account-level and shared across MFA methods.+ const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });+const user = await userDAL.findById(userId);const decryptWithRoot = kmsService.decryptWithRootKey();const secret = decryptWithRoot(totpConfig.encryptedSecret).toString();- const recoveryCodes = decryptWithRoot(totpConfig.encryptedRecoveryCodes).toString().split(",");const otpUrl = authenticator.keyuri(user.username, "Infisical", secret);return {@@ -145,7 +146,7 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStorisVerified: true});- const recoveryCodes = decryptWithRoot(totpConfig.encryptedRecoveryCodes).toString().split(",");+ const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });return {recoveryCodes};@@ -191,41 +192,6 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStor}};- const verifyWithUserRecoveryCode = async ({ userId, recoveryCode }: TVerifyWithUserRecoveryCodeDTO) => {- const totpConfig = await totpConfigDAL.findOne({- userId- });-- if (!totpConfig) {- throw new NotFoundError({- message: "TOTP configuration not found"- });- }-- if (!totpConfig.isVerified) {- throw new BadRequestError({- message: "TOTP configuration has not been verified"- });- }-- const decryptWithRoot = kmsService.decryptWithRootKey();- const encryptWithRoot = kmsService.encryptWithRootKey();-- const recoveryCodes = decryptWithRoot(totpConfig.encryptedRecoveryCodes).toString().split(",");- const matchingCode = recoveryCodes.find((code) => recoveryCode === code);- if (!matchingCode) {- throw new ForbiddenRequestError({- message: "Invalid TOTP recovery code"- });- }-- const updatedRecoveryCodes = recoveryCodes.filter((code) => code !== matchingCode);- const encryptedRecoveryCodes = encryptWithRoot(Buffer.from(updatedRecoveryCodes.join(",")));- await totpConfigDAL.updateById(totpConfig.id, {- encryptedRecoveryCodes- });- };-const deleteUserTotpConfig = async ({ userId }: TDeleteUserTotpConfigDTO) => {const totpConfig = await totpConfigDAL.findOne({userId@@ -240,49 +206,11 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStorawait totpConfigDAL.deleteById(totpConfig.id);};- const createUserTotpRecoveryCodes = async ({ userId }: TCreateUserTotpRecoveryCodesDTO) => {- const decryptWithRoot = kmsService.decryptWithRootKey();- const encryptWithRoot = kmsService.encryptWithRootKey();-- return totpConfigDAL.transaction(async (tx) => {- const totpConfig = await totpConfigDAL.findOne(- {- userId,- isVerified: true- },- tx- );-- if (!totpConfig) {- throw new NotFoundError({- message: "Valid TOTP configuration not found"- });- }-- const recoveryCodes = decryptWithRoot(totpConfig.encryptedRecoveryCodes).toString().split(",");- if (recoveryCodes.length >= MAX_RECOVERY_CODE_LIMIT) {- throw new BadRequestError({- message: `Cannot have more than ${MAX_RECOVERY_CODE_LIMIT} recovery codes at a time`- });- }-- const toGenerateCount = MAX_RECOVERY_CODE_LIMIT - recoveryCodes.length;- const newRecoveryCodes = Array.from({ length: toGenerateCount }).map(generateRecoveryCode);- const encryptedRecoveryCodes = encryptWithRoot(Buffer.from([...recoveryCodes, ...newRecoveryCodes].join(",")));-- await totpConfigDAL.updateById(totpConfig.id, {- encryptedRecoveryCodes- });- });- };-return {registerUserTotp,verifyUserTotpConfig,getUserTotpConfig,verifyUserTotp,- verifyWithUserRecoveryCode,- deleteUserTotpConfig,- createUserTotpRecoveryCodes+ deleteUserTotpConfig};};diff --git a/backend/src/services/totp/totp-types.ts b/backend/src/services/totp/totp-types.tsindex 15c0156197..cc0e26e878 100644--- a/backend/src/services/totp/totp-types.ts+++ b/backend/src/services/totp/totp-types.ts@@ -16,15 +16,6 @@ export type TVerifyUserTotpDTO = {totp: string;};-export type TVerifyWithUserRecoveryCodeDTO = {- userId: string;- recoveryCode: string;-};-export type TDeleteUserTotpConfigDTO = {userId: string;};--export type TCreateUserTotpRecoveryCodesDTO = {- userId: string;-};diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex a3c150ded3..14e4042793 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -17,6 +17,7 @@ import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { ActorType, AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType } from "../auth/auth-type";import { TGroupProjectDALFactory } from "../group-project/group-project-dal";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";+import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";import { TUserDALFactory } from "./user-dal";import { TListUserGroupsDTO, TUpdateUserEmailDTO, TUpdateUserMfaDTO, TVerifyCurrentEmailOTPDTO } from "./user-types";@@ -44,6 +45,7 @@ type TUserServiceFactoryDep = {smtpService: Pick<TSmtpService, "sendMail">;permissionService: TPermissionServiceFactory;userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById" | "delete">;+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "deleteRecoveryCodes" | "ensureRecoveryCodes">;};export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;@@ -56,7 +58,8 @@ export const userServiceFactory = ({tokenService,smtpService,permissionService,- userAliasDAL+ userAliasDAL,+ mfaRecoveryCodeService}: TUserServiceFactoryDep) => {const sendEmailVerificationCode = async (token: string) => {const config = getConfig();@@ -113,6 +116,15 @@ export const userServiceFactory = ({selectedMfaMethod});+ // Recovery codes are account-level and tied to MFA being enabled, not to any+ // specific method. Provision the pool as soon as MFA is turned on, and clear+ // it when MFA is turned off so no usable codes are left behind.+ if (isMfaEnabled === true) {+ await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });+ } else if (isMfaEnabled === false) {+ await mfaRecoveryCodeService.deleteRecoveryCodes({ userId });+ }+return updatedUser;};diff --git a/backend/src/services/webauthn/webauthn-service.ts b/backend/src/services/webauthn/webauthn-service.tsindex 8648d17862..713a51175d 100644--- a/backend/src/services/webauthn/webauthn-service.ts+++ b/backend/src/services/webauthn/webauthn-service.ts@@ -14,6 +14,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";import { TokenType } from "../auth-token/auth-token-types";+import { TMfaRecoveryCodeServiceFactory } from "../mfa-recovery-code/mfa-recovery-code-service";import { TUserDALFactory } from "../user/user-dal";import { TWebAuthnCredentialDALFactory } from "./webauthn-credential-dal";import {@@ -31,6 +32,7 @@ type TWebAuthnServiceFactoryDep = {webAuthnCredentialDAL: TWebAuthnCredentialDALFactory;tokenService: TAuthTokenServiceFactory;keyStore: TKeyStoreFactory;+ mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "ensureRecoveryCodes">;};export type TWebAuthnServiceFactory = ReturnType<typeof webAuthnServiceFactory>;@@ -39,7 +41,8 @@ export const webAuthnServiceFactory = ({userDAL,webAuthnCredentialDAL,tokenService,- keyStore+ keyStore,+ mfaRecoveryCodeService}: TWebAuthnServiceFactoryDep) => {const storeChallenge = async (userId: string, challenge: string) => {const challengeKey = KeyStorePrefixes.WebAuthnChallenge(userId);@@ -178,9 +181,15 @@ export const webAuthnServiceFactory = ({// Clear the challengeawait clearChallenge(userId);+ // Ensure the user has account-level recovery codes as a passkey fallback.+ // Idempotent: only the first registered passkey (or a pre-existing TOTP+ // setup) generates codes; subsequent passkeys reuse the same pool.+ const recoveryCodes = await mfaRecoveryCodeService.ensureRecoveryCodes({ userId });+return {credentialId: credential.credentialId,- name: credential.name+ name: credential.name,+ recoveryCodes};};diff --git a/frontend/src/components/auth/Mfa.tsx b/frontend/src/components/auth/Mfa.tsxindex b6da43dce7..ea0aa69a22 100644--- a/frontend/src/components/auth/Mfa.tsx+++ b/frontend/src/components/auth/Mfa.tsx@@ -5,6 +5,7 @@ import { Link, useNavigate } from "@tanstack/react-router";import { t } from "i18next";import Error from "@app/components/basic/Error";+import { RecoveryCodesDownload } from "@app/components/mfa/RecoveryCodesDownload";import TotpRegistration from "@app/components/mfa/TotpRegistration";import { createNotification } from "@app/components/notifications";import SecurityClient from "@app/components/utilities/SecurityClient";@@ -84,6 +85,7 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Propconst [shouldShowWebAuthnRegistration, setShouldShowWebAuthnRegistration] = useState(false);const [credentialName, setCredentialName] = useState("");const [isRegisteringPasskey, setIsRegisteringPasskey] = useState(false);+ const [registrationRecoveryCodes, setRegistrationRecoveryCodes] = useState<string[]>([]);const logout = useLogoutUser();const { mutateAsync: generateWebAuthnAuthenticationOptions } = useGenerateAuthenticationOptions();@@ -111,13 +113,21 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop}, [method]);const getExpectedCodeLength = () => {- if (method === MfaMethod.EMAIL) return 6;- if (method === MfaMethod.TOTP) return showRecoveryCodeInput ? 8 : 6;+ // Recovery codes are account-level and 8 characters for every MFA method+ // (email, TOTP and passkeys).+ if (showRecoveryCodeInput) return 8;return 6;};const isCodeComplete = mfaCode.length === getExpectedCodeLength();+ const getRecoveryToggleLabel = () => {+ if (!showRecoveryCodeInput) return "Use a recovery code";+ if (method === MfaMethod.WEBAUTHN) return "Use passkey instead";+ if (method === MfaMethod.EMAIL) return "Use email code";+ return "Use authenticator code";+ };+const verifyMfa = async (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();@@ -127,7 +137,7 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Proptry {let result;- if (method === MfaMethod.TOTP && showRecoveryCodeInput) {+ if (showRecoveryCodeInput) {result = await verifyRecoveryCode(mfaCode.trim());} else {result = await verifyMfaToken({@@ -290,7 +300,7 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Propconst registrationResponse = await startRegistration({ optionsJSON: options });// Verify registration with server (using regular user endpoint)- await verifyRegistration.mutateAsync({+ const { recoveryCodes } = await verifyRegistration.mutateAsync({registrationResponse,name: credentialName || "Passkey"});@@ -300,8 +310,15 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Proptype: "success"});- setShouldShowWebAuthnRegistration(false);- await successCallback();+ // Surface account-level recovery codes generated on first passkey so the+ // user can save them before continuing. If none were returned (a pool+ // already existed), proceed immediately.+ if (recoveryCodes && recoveryCodes.length > 0) {+ setRegistrationRecoveryCodes(recoveryCodes);+ } else {+ setShouldShowWebAuthnRegistration(false);+ await successCallback();+ }} finally {// Restore MFA tokenSecurityClient.setMfaToken(mfaToken);@@ -371,6 +388,16 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop</div></div></div>+ <RecoveryCodesDownload+ isOpen={registrationRecoveryCodes.length > 0}+ recoveryCodes={registrationRecoveryCodes}+ onClose={() => setRegistrationRecoveryCodes([])}+ onDownloadComplete={async () => {+ setRegistrationRecoveryCodes([]);+ setShouldShowWebAuthnRegistration(false);+ await successCallback();+ }}+ /></>);}@@ -384,12 +411,20 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop</div></Link>)}- {method === MfaMethod.EMAIL && (- <>- <p className="text-l flex justify-center text-bunker-300">{t("mfa.step2-message")}</p>- <p className="text-l my-1 flex justify-center font-medium text-bunker-300">{email}</p>- </>- )}+ {method === MfaMethod.EMAIL &&+ (showRecoveryCodeInput ? (+ <div className="mb-8 text-center">+ <h2 className="mb-3 text-xl font-medium text-bunker-100">Two-Factor Authentication</h2>+ <p className="mx-auto max-w-md text-sm leading-relaxed text-bunker-300">+ Enter one of your backup recovery codes+ </p>+ </div>+ ) : (+ <>+ <p className="text-l flex justify-center text-bunker-300">{t("mfa.step2-message")}</p>+ <p className="text-l my-1 flex justify-center font-medium text-bunker-300">{email}</p>+ </>+ ))}{method === MfaMethod.TOTP && (<div className="mb-8 text-center"><h2 className="mb-3 text-xl font-medium text-bunker-100">Two-Factor Authentication</h2>@@ -404,11 +439,13 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop<div className="mb-8 text-center"><h2 className="mb-3 text-xl font-medium text-bunker-100">Passkey Authentication</h2><p className="mx-auto max-w-md text-sm leading-relaxed text-bunker-300">- Use your registered passkey to complete two-factor authentication+ {showRecoveryCodeInput+ ? "Enter one of your backup recovery codes"+ : "Use your registered passkey to complete two-factor authentication"}</p></div>)}- {method === MfaMethod.WEBAUTHN ? (+ {method === MfaMethod.WEBAUTHN && !showRecoveryCodeInput ? (<>{typeof triesLeft === "number" && (<Error text={`Failed authentication. You have ${triesLeft} attempt(s) remaining.`} />@@ -434,17 +471,18 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop{method === MfaMethod.EMAIL && (<div className="flex justify-center"><ReactCodeInput+ key={showRecoveryCodeInput ? "recovery" : "email"}name=""inputMode="tel"type="text"- fields={6}+ fields={showRecoveryCodeInput ? 8 : 6}onChange={setMfaCode}className="mt-6 mb-2"{...codeInputProps}/></div>)}- {method === MfaMethod.TOTP && (+ {(method === MfaMethod.TOTP || method === MfaMethod.WEBAUTHN) && (<div className="mt-8 mb-6 flex justify-center"><ReactCodeInputkey={showRecoveryCodeInput ? "recovery" : "totp"}@@ -463,17 +501,18 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop{method === MfaMethod.EMAIL && (<div className="flex justify-center"><ReactCodeInput+ key={showRecoveryCodeInput ? "recovery-mobile" : "email-mobile"}name=""inputMode="tel"type="text"- fields={6}+ fields={showRecoveryCodeInput ? 8 : 6}onChange={setMfaCode}className="mt-2 mb-2"{...codeInputPropsPhone}/></div>)}- {method === MfaMethod.TOTP && (+ {(method === MfaMethod.TOTP || method === MfaMethod.WEBAUTHN) && (<div className="mt-4 mb-6 flex justify-center"><ReactCodeInputkey={showRecoveryCodeInput ? "recovery-mobile" : "totp-mobile"}@@ -507,7 +546,9 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop</div></form>)}- {method === MfaMethod.TOTP && (+ {(method === MfaMethod.EMAIL ||+ method === MfaMethod.TOTP ||+ method === MfaMethod.WEBAUTHN) && (<div className="mt-6 flex flex-col items-center gap-4 text-sm"><buttontype="button"@@ -517,7 +558,7 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop}}className="text-bunker-400 transition-colors duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">- {showRecoveryCodeInput ? "Use authenticator code" : "Use a recovery code"}+ {getRecoveryToggleLabel()}</button><div className="text-center text-sm"><Tooltip@@ -551,7 +592,7 @@ export const Mfa = ({ successCallback, closeMfa, hideLogo, email, method }: Prop</div></div>)}- {method === MfaMethod.EMAIL && (+ {method === MfaMethod.EMAIL && !showRecoveryCodeInput && (<div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2"><div className="flex flex-row items-baseline gap-1 text-sm"><span className="text-bunker-400">{t("signup.step2-resend-alert")}</span>diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsxindex 3d6d308e26..b811b06a09 100644--- a/frontend/src/hooks/api/users/mutation.tsx+++ b/frontend/src/hooks/api/users/mutation.tsx@@ -94,15 +94,20 @@ export const useDeleteUserTotpConfiguration = () => {});};-export const useCreateNewTotpRecoveryCodes = () => {+// Rotates the account-level recovery codes: issues a fresh set and invalidates+// the old ones. Returns the new codes so the caller can display them once.+export const useRotateMfaRecoveryCodes = () => {const queryClient = useQueryClient();- return useMutation({+ return useMutation<{ recoveryCodes: string[] }, unknown, void>({mutationFn: async () => {- await apiRequest.post("/api/v1/user/me/totp/recovery-codes");+ const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(+ "/api/v1/user/me/mfa/recovery-codes"+ );- return {};+ return data;},onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });}});diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex f76be5007f..a04103628b 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -499,3 +499,26 @@ 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/hooks/api/users/query-keys.tsx b/frontend/src/hooks/api/users/query-keys.tsxindex aacbb73b92..162fd36cd4 100644--- a/frontend/src/hooks/api/users/query-keys.tsx+++ b/frontend/src/hooks/api/users/query-keys.tsx@@ -19,6 +19,7 @@ export const userKeys = {listUsers: ["user-list"] as const,totpRegistration: ["totp-registration"],totpConfiguration: ["totp-configuration"],+ mfaRecoveryCodes: ["mfa-recovery-codes"],listUserGroupMemberships: (username: string) => [{ username }, "user-group-memberships"] as const,myOrganizationProjects: (orgId: string) => [{ orgId }, "organization-projects"] as const};diff --git a/frontend/src/hooks/api/webauthn/mutations.tsx b/frontend/src/hooks/api/webauthn/mutations.tsxindex 3477c35060..f8294041ea 100644--- a/frontend/src/hooks/api/webauthn/mutations.tsx+++ b/frontend/src/hooks/api/webauthn/mutations.tsx@@ -9,7 +9,8 @@ import {TGenerateRegistrationOptionsResponse,TUpdateWebAuthnCredentialDTO,TVerifyAuthenticationDTO,- TVerifyRegistrationDTO+ TVerifyRegistrationDTO,+ TVerifyRegistrationResponse} from "./types";export const useGenerateRegistrationOptions = () =>@@ -27,7 +28,7 @@ export const useVerifyRegistration = () => {return useMutation({mutationFn: async (dto: TVerifyRegistrationDTO) => {- const { data } = await apiRequest.post<{ credentialId: string; name?: string | null }>(+ const { data } = await apiRequest.post<TVerifyRegistrationResponse>("/api/v1/user/me/webauthn/register/verify",dto);diff --git a/frontend/src/hooks/api/webauthn/types.ts b/frontend/src/hooks/api/webauthn/types.tsindex a19710ac4c..5f7a4c984a 100644--- a/frontend/src/hooks/api/webauthn/types.ts+++ b/frontend/src/hooks/api/webauthn/types.ts@@ -21,6 +21,12 @@ export type TVerifyRegistrationDTO = {name?: string;};+export type TVerifyRegistrationResponse = {+ credentialId: string;+ name?: string | null;+ recoveryCodes: string[];+};+export type TGenerateAuthenticationOptionsResponse = PublicKeyCredentialRequestOptionsJSON;export type TVerifyAuthenticationDTO = {diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsxindex 04a6e74f29..8be9578a9c 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx@@ -22,11 +22,13 @@ import { useGetUser, userKeys, useUpdateUserMfa } from "@app/hooks/api";import { MfaMethod } from "@app/hooks/api/auth/types";import { useFetchServerStatus } from "@app/hooks/api/serverDetails";import {- useCreateNewTotpRecoveryCodes,useDeleteUserTotpConfiguration,+ useRotateMfaRecoveryCodes,useVerifyUserTotpRegistration} from "@app/hooks/api/users/mutation";import {+ fetchMfaRecoveryCodes,+ useGetMfaRecoveryCodes,useGetUserTotpConfiguration,useGetUserTotpRegistration} from "@app/hooks/api/users/queries";@@ -57,6 +59,7 @@ export const MFASection = () => {"setUpEmail","deleteTotpConfig","downloadRecoveryCodes",+ "regenerateRecoveryCodes","deleteWebAuthnCredential","renameWebAuthnCredential","registerPasskey"@@ -68,7 +71,6 @@ export const MFASection = () => {enabled: showMobileAuthSetup});const { mutateAsync: deleteTotpConfiguration } = useDeleteUserTotpConfiguration();- const { mutateAsync: createTotpRecoveryCodes } = useCreateNewTotpRecoveryCodes();const { mutateAsync: verifyUserTotp } = useVerifyUserTotpRegistration();const queryClient = useQueryClient();const { data: serverDetails } = useFetchServerStatus();@@ -86,6 +88,18 @@ export const MFASection = () => {const [selectedCredentialId, setSelectedCredentialId] = useState<string>("");const [credentialName, setCredentialName] = useState<string>("");const [isRegisteringPasskey, setIsRegisteringPasskey] = useState(false);+ const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[]>([]);++ const hasPasskeys = Boolean(webAuthnCredentials && webAuthnCredentials.length > 0);+ // Recovery codes are account-level and shared across every MFA method, so surface+ // them whenever the user has MFA enabled or any MFA credential configured.+ const shouldShowRecoveryCodesSection = Boolean(+ user?.isMfaEnabled || totpConfiguration?.isVerified || hasPasskeys+ );+ const { data: mfaRecoveryCodes } = useGetMfaRecoveryCodes(shouldShowRecoveryCodesSection);+ const hasRecoveryCodes = Boolean(mfaRecoveryCodes && mfaRecoveryCodes.length > 0);+ const { mutateAsync: rotateMfaRecoveryCodes, isPending: isRotatingRecoveryCodes } =+ useRotateMfaRecoveryCodes();// Update form data when user data changesuseEffect(() => {@@ -125,13 +139,32 @@ export const MFASection = () => {handlePopUpClose("deleteTotpConfig");};- const handleGenerateMoreRecoveryCodes = async () => {- await createTotpRecoveryCodes();+ // Generates a fresh account-level recovery code pool and surfaces it for saving.+ // `isRotation` distinguishes replacing an existing pool (confirmed via modal,+ // invalidates the old codes) from first-time generation for users with none yet.+ const generateAndShowRecoveryCodes = async (isRotation: boolean) => {+ try {+ const { recoveryCodes } = await rotateMfaRecoveryCodes();- createNotification({- text: "Successfully generated new recovery codes",- type: "success"- });+ if (isRotation) {+ handlePopUpClose("regenerateRecoveryCodes");+ }++ setNewRecoveryCodes(recoveryCodes);+ handlePopUpOpen("downloadRecoveryCodes");++ createNotification({+ text: isRotation+ ? "Generated a new set of recovery codes. Your previous codes no longer work."+ : "Generated your recovery codes. Save them somewhere safe.",+ type: "success"+ });+ } catch (error: any) {+ createNotification({+ text: error?.response?.data?.message || "Failed to generate recovery codes",+ type: "error"+ });+ }};const handleRegisterPasskey = async () => {@@ -166,7 +199,7 @@ export const MFASection = () => {const registrationResponse = await startRegistration({ optionsJSON: options });// Verify registration with server- await verifyRegistration({+ const { recoveryCodes } = await verifyRegistration({registrationResponse,name: credentialName || "Passkey"});@@ -178,6 +211,12 @@ export const MFASection = () => {handlePopUpClose("registerPasskey");setCredentialName("");++ // Surface account-level recovery codes generated on the first passkey.+ if (recoveryCodes && recoveryCodes.length > 0) {+ setNewRecoveryCodes(recoveryCodes);+ handlePopUpOpen("downloadRecoveryCodes");+ }} catch (error: any) {console.error("Failed to register passkey:", error);@@ -242,7 +281,7 @@ export const MFASection = () => {}};- const handleFormDataChange = async (field: string, value: any) => {+ const handleFormDataChange = (field: string, value: any) => {setFormData((prev) => ({...prev,[field]: value@@ -252,12 +291,13 @@ export const MFASection = () => {if (field === "selectedMfaMethod" && value === MfaMethod.TOTP && formData.isMfaEnabled) {setShowMobileAuthSetup(true);} else if (field === "selectedMfaMethod" && value !== MfaMethod.TOTP) {+ // Switching the selected method away from TOTP is only a local form edit+ // until the user saves. Do not delete the existing TOTP configuration here:+ // it can coexist with another active method and is managed (removed)+ // explicitly via the "Remove Authenticator" button.setShowMobileAuthSetup(false);setTotpCode("");setShouldShowRecoveryCodes.off();- if (totpConfiguration?.isVerified) {- await deleteTotpConfiguration().catch(console.error);- }} else if (field === "isMfaEnabled" && value && formData.selectedMfaMethod === MfaMethod.TOTP) {setShowMobileAuthSetup(true);} else if (field === "isMfaEnabled" && !value) {@@ -271,6 +311,8 @@ export const MFASection = () => {try {if (!user) return;+ const isEnablingMfa = !user.isMfaEnabled && formData.isMfaEnabled;+if (user.authMethods.includes(AuthMethod.LDAP)) {createNotification({text: "Two-factor authentication is not available for LDAP users.",@@ -317,10 +359,8 @@ export const MFASection = () => {try {await verifyUserTotp({ totp: totpCode });- handlePopUpOpen("downloadRecoveryCodes");-createNotification({- text: "Successfully configured mobile authenticator. Please save your recovery codes!",+ text: "Successfully configured mobile authenticator",type: "success"});@@ -367,6 +407,18 @@ export const MFASection = () => {});}+ // Turning MFA on provisions a fresh account-level recovery code pool+ // server-side (regardless of method). Surface it once so the user can save+ // the codes before leaving the page.+ if (isEnablingMfa) {+ const recoveryCodes = await fetchMfaRecoveryCodes();+ if (recoveryCodes.length > 0) {+ setNewRecoveryCodes(recoveryCodes);+ handlePopUpOpen("downloadRecoveryCodes");+ }+ await queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });+ }+// Reset form statesetShowMobileAuthSetup(false);setTotpCode("");@@ -655,53 +707,84 @@ export const MFASection = () => {{/* Management Sections - Separate from configuration form */}{user && (<div className="mt-6 mb-6 space-y-6">- {/* Mobile Authenticator Management - Show if configured, regardless of active method */}- {totpConfiguration?.isVerified && (+ {/* Recovery Codes - account-level, shared across all MFA methods */}+ {shouldShowRecoveryCodesSection && (<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <h3 className="mb-4 text-lg font-medium text-mineshaft-100">- Mobile Authenticator Management- </h3>+ <h3 className="mb-1 text-lg font-medium text-mineshaft-100">Recovery Codes</h3><p className="mb-4 text-sm text-mineshaft-400">- Manage your mobile authenticator configuration and recovery codes.+ Use a recovery code to sign in if you lose access to your two-factor authentication+ method.</p>- <div className="space-y-4">- <div className="flex flex-wrap gap-2">- <Button- colorSchema="secondary"- variant="outline_bg"- onClick={setShouldShowRecoveryCodes.toggle}- >- {shouldShowRecoveryCodes ? "Hide recovery codes" : "Show recovery codes"}- </Button>+ {hasRecoveryCodes ? (+ <div className="space-y-4">+ <div className="flex flex-wrap gap-2">+ <Button+ colorSchema="secondary"+ variant="outline_bg"+ onClick={setShouldShowRecoveryCodes.toggle}+ >+ {shouldShowRecoveryCodes ? "Hide recovery codes" : "Show recovery codes"}+ </Button>+ <Button+ colorSchema="secondary"+ variant="outline_bg"+ onClick={() => handlePopUpOpen("regenerateRecoveryCodes")}+ >+ Regenerate recovery codes+ </Button>+ </div>++ {shouldShowRecoveryCodes && (+ <div className="w-fit rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4 pr-8">+ <div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">+ {(mfaRecoveryCodes || []).map((code, index) => (+ <div key={code} className="flex items-center text-mineshaft-200">+ <span className="w-8 text-right text-mineshaft-400">{index + 1}.</span>+ <span className="pl-2">{code}</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ ) : (+ <div>+ <p className="mb-3 text-sm text-mineshaft-400">+ You don't have any recovery codes yet. Generate a set and store them+ somewhere safe.+ </p><ButtoncolorSchema="secondary"variant="outline_bg"- onClick={handleGenerateMoreRecoveryCodes}+ onClick={() => generateAndShowRecoveryCodes(false)}+ isLoading={isRotatingRecoveryCodes}>- Generate more codes- </Button>- <Button- colorSchema="danger"- variant="outline_bg"- onClick={() => handlePopUpOpen("deleteTotpConfig")}- >- Remove Authenticator+ Generate recovery codes</Button></div>+ )}+ </div>+ )}- {shouldShowRecoveryCodes && (- <div className="w-fit rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4 pr-8">- <div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">- {totpConfiguration.recoveryCodes.map((code, index) => (- <div key={code} className="flex items-center text-mineshaft-200">- <span className="w-8 text-right text-mineshaft-400">{index + 1}.</span>- <span className="pl-2">{code}</span>- </div>- ))}- </div>- </div>- )}+ {/* Mobile Authenticator Management - Show if configured, regardless of active method */}+ {totpConfiguration?.isVerified && (+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">+ <h3 className="mb-4 text-lg font-medium text-mineshaft-100">+ Mobile Authenticator Management+ </h3>+ <p className="mb-4 text-sm text-mineshaft-400">+ Manage your mobile authenticator configuration.+ </p>++ <div className="flex flex-wrap gap-2">+ <Button+ colorSchema="danger"+ variant="outline_bg"+ onClick={() => handlePopUpOpen("deleteTotpConfig")}+ >+ Remove Authenticator+ </Button></div></div>)}@@ -819,14 +902,53 @@ export const MFASection = () => {<RecoveryCodesDownloadisOpen={popUp.downloadRecoveryCodes?.isOpen || false}- onClose={() => handlePopUpClose("downloadRecoveryCodes")}- recoveryCodes={totpRegistration?.recoveryCodes || []}- onDownloadComplete={() => handlePopUpClose("downloadRecoveryCodes")}+ onClose={() => {+ handlePopUpClose("downloadRecoveryCodes");+ setNewRecoveryCodes([]);+ }}+ recoveryCodes={+ newRecoveryCodes.length > 0 ? newRecoveryCodes : totpRegistration?.recoveryCodes || []+ }+ onDownloadComplete={() => {+ handlePopUpClose("downloadRecoveryCodes");+ setNewRecoveryCodes([]);+ }}/>{registerPasskeyModal}{renamePasskeyModal}+ {/* Regenerate (rotate) recovery codes confirmation */}+ <Modal+ isOpen={popUp.regenerateRecoveryCodes?.isOpen || false}+ onOpenChange={(isOpen) => handlePopUpToggle("regenerateRecoveryCodes", isOpen)}+ >+ <ModalContent title="Regenerate recovery codes?">+ <div className="space-y-4">+ <p className="text-sm text-mineshaft-300">+ This generates a brand-new set of recovery codes and immediately invalidates all of+ your existing ones. Make sure to save the new codes.+ </p>+ <div className="flex gap-2">+ <Button+ colorSchema="danger"+ onClick={() => generateAndShowRecoveryCodes(true)}+ isLoading={isRotatingRecoveryCodes}+ >+ Regenerate codes+ </Button>+ <Button+ variant="outline_bg"+ onClick={() => handlePopUpClose("regenerateRecoveryCodes")}+ disabled={isRotatingRecoveryCodes}+ >+ Cancel+ </Button>+ </div>+ </div>+ </ModalContent>+ </Modal>+{/* Delete Passkey Modal */}<DeleteActionModalisOpen={popUp.deleteWebAuthnCredential?.isOpen || false}