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
feat: refactored password recovery steps to account recovery
=82b48c8927da
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 41d9b01e5d..5932356ff0 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -55,6 +55,7 @@ import { TSshHostGroupServiceFactory } from "@app/ee/services/ssh-host-group/sshimport { TSubOrgServiceFactory } from "@app/ee/services/sub-org/sub-org-service";import { TTrustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-types";import { TAuthMode } from "@app/server/plugins/auth/inject-identity";+import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";import { TApiKeyServiceFactory } from "@app/services/api-key/api-key-service";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";@@ -241,6 +242,7 @@ declare module "fastify" {services: {login: TAuthLoginFactory;password: TAuthPasswordFactory;+ accountRecovery: TAccountRecoveryServiceFactory;signup: TAuthSignupFactory;authToken: TAuthTokenServiceFactory;permission: TPermissionServiceFactory;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8f6c1a5fe6..b9b57d229d 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -192,6 +192,7 @@ import {approvalRequestStepEligibleApproversDALFactory,approvalRequestStepsDALFactory} from "@app/services/approval-policy/approval-request-dal";+import { accountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";import { authDALFactory } from "@app/services/auth/auth-dal";import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";@@ -955,7 +956,13 @@ export const registerRoutes = async (smtpService,authDAL,userDAL,- totpConfigDAL,+ totpConfigDAL+ });++ const accountRecoveryService = accountRecoveryServiceFactory({+ tokenService,+ smtpService,+ userDAL,membershipUserDAL});@@ -2677,6 +2684,7 @@ export const registerRoutes = async (server.decorate<FastifyZodProvider["services"]>("services", {login: loginService,password: passwordService,+ accountRecovery: accountRecoveryService,signup: signupService,user: userService,group: groupService,diff --git a/backend/src/server/routes/v1/account-recovery-router.ts b/backend/src/server/routes/v1/account-recovery-router.tsnew file mode 100644index 0000000000..72d7ae8f47--- /dev/null+++ b/backend/src/server/routes/v1/account-recovery-router.ts@@ -0,0 +1,64 @@+import { z } from "zod";++import { UsersSchema } from "@app/db/schemas";+import { smtpRateLimit } from "@app/server/config/rateLimiter";+import { UserEncryption } from "@app/services/user/user-types";++export const registerAccountRecoveryRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/send-email",+ config: {+ rateLimit: smtpRateLimit({+ keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp+ })+ },+ schema: {+ operationId: "sendAccountRecoveryEmail",+ body: z.object({+ email: z.string().email().trim()+ }),+ response: {+ 200: z.object({+ message: z.string()+ })+ }+ },+ handler: async (req) => {+ await server.services.accountRecovery.sendRecoveryEmail(req.body.email);++ return {+ message: "If an account exists with this email, a recovery link has been sent"+ };+ }+ });++ server.route({+ method: "POST",+ url: "/verify-email",+ config: {+ rateLimit: smtpRateLimit({+ keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp+ })+ },+ schema: {+ operationId: "verifyAccountRecoveryEmail",+ body: z.object({+ email: z.string().email().trim(),+ code: z.string().trim()+ }),+ response: {+ 200: z.object({+ user: UsersSchema,+ token: z.string(),+ userEncryptionVersion: z.nativeEnum(UserEncryption)+ })+ }+ },+ handler: async (req) => {+ const recoveryResult = await server.services.accountRecovery.verifyRecoveryEmail(req.body.email, req.body.code);++ return recoveryResult;+ }+ });+};diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex 59666f178d..d27fbd1c5c 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -6,6 +6,7 @@ import { registerCmekRouter } from "@app/server/routes/v1/cmek-router";import { registerDashboardRouter } from "@app/server/routes/v1/dashboard-router";import { registerSecretSyncRouter, SECRET_SYNC_REGISTER_ROUTER_MAP } from "@app/server/routes/v1/secret-sync-routers";+import { registerAccountRecoveryRouter } from "./account-recovery-router";import { registerAdminRouter } from "./admin-router";import { APPROVAL_POLICY_REGISTER_ROUTER_MAP } from "./approval-policy-routers";import { registerAuthRoutes } from "./auth-router";@@ -99,6 +100,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {{ prefix: "/auth" });await server.register(registerPasswordRouter, { prefix: "/password" });+ await server.register(registerAccountRecoveryRouter, { prefix: "/account-recovery" });await server.register(async (orgRouter) => {await orgRouter.register(registerOrgRouter);diff --git a/backend/src/server/routes/v1/password-router.ts b/backend/src/server/routes/v1/password-router.tsindex 671745609c..53c70ca51d 100644--- a/backend/src/server/routes/v1/password-router.ts+++ b/backend/src/server/routes/v1/password-router.ts@@ -1,71 +1,13 @@import { z } from "zod";-import { BackupPrivateKeySchema, UsersSchema } from "@app/db/schemas";+import { BackupPrivateKeySchema } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { validateSignUpAuthorization } from "@app/services/auth/auth-fns";import { ActorType, AuthMode } from "@app/services/auth/auth-type";-import { UserEncryption } from "@app/services/user/user-types";export const registerPasswordRouter = async (server: FastifyZodProvider) => {- server.route({- method: "POST",- url: "/email/password-reset",- config: {- rateLimit: smtpRateLimit({- keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp- })- },- schema: {- operationId: "sendPasswordResetEmail",- body: z.object({- email: z.string().email().trim()- }),- response: {- 200: z.object({- message: z.string()- })- }- },- handler: async (req) => {- await server.services.password.sendPasswordResetEmail(req.body.email);-- return {- message: "If an account exists with this email, a password reset link has been sent"- };- }- });-- server.route({- method: "POST",- url: "/email/password-reset-verify",- config: {- rateLimit: smtpRateLimit({- keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp- })- },- schema: {- operationId: "verifyPasswordResetEmail",- body: z.object({- email: z.string().email().trim(),- code: z.string().trim()- }),- response: {- 200: z.object({- user: UsersSchema,- token: z.string(),- userEncryptionVersion: z.nativeEnum(UserEncryption)- })- }- },- handler: async (req) => {- const passwordReset = await server.services.password.verifyPasswordResetEmail(req.body.email, req.body.code);-- return passwordReset;- }- });-server.route({method: "GET",url: "/backup-private-key",diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.tsnew file mode 100644index 0000000000..87f6331479--- /dev/null+++ b/backend/src/services/account-recovery/account-recovery-service.ts@@ -0,0 +1,132 @@+import { AccessScope } from "@app/db/schemas";+import { getConfig } from "@app/lib/config/env";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";+import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";+import { TokenType } from "@app/services/auth-token/auth-token-types";+import { TMembershipUserDALFactory } from "@app/services/membership-user/membership-user-dal";+import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";+import { TUserDALFactory } from "@app/services/user/user-dal";+import { UserEncryption } from "@app/services/user/user-types";++type TAccountRecoveryServiceFactoryDep = {+ userDAL: TUserDALFactory;+ membershipUserDAL: Pick<TMembershipUserDALFactory, "find">;+ tokenService: TAuthTokenServiceFactory;+ smtpService: TSmtpService;+};++export type TAccountRecoveryServiceFactory = ReturnType<typeof accountRecoveryServiceFactory>;++export const accountRecoveryServiceFactory = ({+ userDAL,+ membershipUserDAL,+ tokenService,+ smtpService+}: TAccountRecoveryServiceFactoryDep) => {+ /*+ * Account recovery flow via email. Step 1: send recovery email+ */+ const sendRecoveryEmail = async (email: string) => {+ const sendEmail = async () => {+ const users = await userDAL.findUserByUsername(email);+ // akhilmhdh: case sensitive email resolution+ const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];+ if (!user) throw new BadRequestError({ message: "Failed to find user data" });++ if (user && user.isAccepted) {+ const cfg = getConfig();++ const hasEmailAuth = user.authMethods?.includes(AuthMethod.EMAIL);++ if (!hasEmailAuth) {+ const orgMemberships = await membershipUserDAL.find({+ actorUserId: user.id,+ scope: AccessScope.Organization+ });+ const lastLoginMethod =+ orgMemberships+ .filter((membership) => membership.lastLoginAuthMethod)+ .sort((a, b) => (b.updatedAt || new Date(0)).getTime() - (a.updatedAt || new Date(0)).getTime())[0]+ ?.lastLoginAuthMethod || null;+ const substitutions = {+ email,+ lastLoginMethod,+ isCloud: cfg.isCloud,+ siteUrl: cfg.SITE_URL || ""+ };++ await smtpService.sendMail({+ template: SmtpTemplates.OAuthPasswordReset,+ recipients: [email],+ subjectLine: "Password reset not available",+ substitutions+ });+ } else {+ const token = await tokenService.createTokenForUser({+ type: TokenType.TOKEN_EMAIL_PASSWORD_RESET,+ userId: user.id+ });++ await smtpService.sendMail({+ template: SmtpTemplates.ResetPassword,+ recipients: [email],+ subjectLine: "Infisical password reset",+ substitutions: {+ email,+ token,+ callback_url: cfg.SITE_URL ? `${cfg.SITE_URL}/password-reset` : ""+ }+ });+ }+ }+ };++ // note(daniel): run in background to prevent timing attacks+ void sendEmail().catch((err) => logger.error(err, "Failed to send password reset email"));+ };++ /*+ * Account recovery flow via email. Step 2: verify the token and inject a temp token to reset password+ */+ const verifyRecoveryEmail = async (email: string, code: string) => {+ const cfg = getConfig();+ const users = await userDAL.findUserByUsername(email);+ // akhilmhdh: case sensitive email resolution+ const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];+ if (!user) throw new BadRequestError({ message: "Failed to find user data" });++ const userEnc = await userDAL.findUserEncKeyByUserId(user.id);++ if (!userEnc) throw new BadRequestError({ message: "Failed to find user encryption data" });++ // ignore as user is not found to avoid an outside entity to identify infisical registered accounts+ if (!user || (user && !user.isAccepted)) {+ throw new Error("Failed email verification for pass reset");+ }++ await tokenService.validateTokenForUser({+ type: TokenType.TOKEN_EMAIL_PASSWORD_RESET,+ userId: user.id,+ code+ });++ const token = crypto.jwt().sign(+ {+ authTokenType: AuthTokenType.SIGNUP_TOKEN,+ userId: user.id+ },+ cfg.AUTH_SECRET,+ { expiresIn: cfg.JWT_SIGNUP_LIFETIME }+ );++ return { token, user, userEncryptionVersion: userEnc.encryptionVersion as UserEncryption };+ };++ return {+ sendRecoveryEmail,+ verifyRecoveryEmail+ };+};diff --git a/backend/src/services/auth/auth-password-service.ts b/backend/src/services/auth/auth-password-service.tsindex 75f77d0fc7..38b74cfab0 100644--- a/backend/src/services/auth/auth-password-service.ts+++ b/backend/src/services/auth/auth-password-service.ts@@ -1,4 +1,3 @@-import { AccessScope } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError } from "@app/lib/errors";@@ -7,7 +6,6 @@ import { OrgServiceActor } from "@app/lib/types";import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";import { TokenType } from "../auth-token/auth-token-types";-import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";import { TTotpConfigDALFactory } from "../totp/totp-config-dal";import { TUserDALFactory } from "../user/user-dal";@@ -19,12 +17,11 @@ import {TResetPasswordViaBackupKeyDTO,TSetupPasswordViaBackupKeyDTO} from "./auth-password-type";-import { ActorType, AuthMethod, AuthTokenType } from "./auth-type";+import { ActorType, AuthMethod } from "./auth-type";type TAuthPasswordServiceFactoryDep = {authDAL: TAuthDALFactory;userDAL: TUserDALFactory;- membershipUserDAL: Pick<TMembershipUserDALFactory, "find">;tokenService: TAuthTokenServiceFactory;smtpService: TSmtpService;totpConfigDAL: Pick<TTotpConfigDALFactory, "delete">;@@ -34,110 +31,10 @@ export type TAuthPasswordFactory = ReturnType<typeof authPaswordServiceFactory>;export const authPaswordServiceFactory = ({authDAL,userDAL,- membershipUserDAL,tokenService,smtpService,totpConfigDAL}: TAuthPasswordServiceFactoryDep) => {- /*- * Email password reset flow via email. Step 1 send email- */- const sendPasswordResetEmail = async (email: string) => {- const sendEmail = async () => {- const users = await userDAL.findUserByUsername(email);- // akhilmhdh: case sensitive email resolution- const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];- if (!user) throw new BadRequestError({ message: "Failed to find user data" });-- if (user && user.isAccepted) {- const cfg = getConfig();-- const hasEmailAuth = user.authMethods?.includes(AuthMethod.EMAIL);-- if (!hasEmailAuth) {- const orgMemberships = await membershipUserDAL.find({- actorUserId: user.id,- scope: AccessScope.Organization- });- const lastLoginMethod =- orgMemberships- .filter((membership) => membership.lastLoginAuthMethod)- .sort((a, b) => (b.updatedAt || new Date(0)).getTime() - (a.updatedAt || new Date(0)).getTime())[0]- ?.lastLoginAuthMethod || null;- const substitutions = {- email,- lastLoginMethod,- isCloud: cfg.isCloud,- siteUrl: cfg.SITE_URL || ""- };-- await smtpService.sendMail({- template: SmtpTemplates.OAuthPasswordReset,- recipients: [email],- subjectLine: "Password reset not available",- substitutions- });- } else {- const token = await tokenService.createTokenForUser({- type: TokenType.TOKEN_EMAIL_PASSWORD_RESET,- userId: user.id- });-- await smtpService.sendMail({- template: SmtpTemplates.ResetPassword,- recipients: [email],- subjectLine: "Infisical password reset",- substitutions: {- email,- token,- callback_url: cfg.SITE_URL ? `${cfg.SITE_URL}/password-reset` : ""- }- });- }- }- };-- // note(daniel): run in background to prevent timing attacks- void sendEmail().catch((err) => logger.error(err, "Failed to send password reset email"));- };-- /*- * Step 2 of reset password. Verify the token and inject a temp token to reset password- * */- const verifyPasswordResetEmail = async (email: string, code: string) => {- const cfg = getConfig();- const users = await userDAL.findUserByUsername(email);- // akhilmhdh: case sensitive email resolution- const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];- if (!user) throw new BadRequestError({ message: "Failed to find user data" });-- const userEnc = await userDAL.findUserEncKeyByUserId(user.id);-- if (!userEnc) throw new BadRequestError({ message: "Failed to find user encryption data" });-- // ignore as user is not found to avoid an outside entity to identify infisical registered accounts- if (!user || (user && !user.isAccepted)) {- throw new Error("Failed email verification for pass reset");- }-- await tokenService.validateTokenForUser({- type: TokenType.TOKEN_EMAIL_PASSWORD_RESET,- userId: user.id,- code- });-- const token = crypto.jwt().sign(- {- authTokenType: AuthTokenType.SIGNUP_TOKEN,- userId: user.id- },- cfg.AUTH_SECRET,- { expiresIn: cfg.JWT_SIGNUP_LIFETIME }- );-- return { token, user, userEncryptionVersion: userEnc.encryptionVersion as UserEncryption };- };-const resetPasswordV2 = async ({ userId, newPassword, type, oldPassword }: TResetPasswordV2DTO) => {const cfg = getConfig();@@ -323,8 +220,6 @@ export const authPaswordServiceFactory = ({return {resetPasswordByBackupKey,- sendPasswordResetEmail,- verifyPasswordResetEmail,getBackupPrivateKeyOfUser,sendPasswordSetupEmail,setupPassword,