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
create short lived token for email sign up
Thiago Araujo da Silva08b4f9759e3b
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 9df284b857..7d45ce1cf9 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -110,6 +110,7 @@ export const KeyStorePrefixes = {CertActivityTrend: (projectId: string, range: string) => `cert-activity-trend:${projectId}:${range}` as const,CertPqcTrend: (projectId: string, range: string) => `cert-pqc-trend:${projectId}:${range}` as const,RefreshTokenGrace: (sessionId: string) => `refresh-token-grace:${sessionId}` as const,+ EmailSignupOtp: (hash: string) => `email-signup-otp:${hash}` as const,InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,AdminConfig: "infisical-admin-cfg",@@ -140,6 +141,7 @@ export const KeyStoreTtls = {ProjectSSEConnectionTtlSeconds: 180, // Must be > heartbeat interval (60s) * 2TelemetryIdentifyIdentityInSeconds: 86400, // 24 hoursRefreshTokenGraceInSeconds: 10,+ EmailSignupOtpInSeconds: 300, // 5 minutesInsightsCacheInSeconds: 300, // 5 minutesAdminConfigInSeconds: 60,InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation jobdiff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.tsindex d0cbfe756f..3b90a7a073 100644--- a/backend/src/services/auth-token/auth-token-service.ts+++ b/backend/src/services/auth-token/auth-token-service.ts@@ -13,7 +13,13 @@ import { TMembershipUserDALFactory } from "../membership-user/membership-user-daimport { TOrgDALFactory } from "../org/org-dal";import { TUserDALFactory } from "../user/user-dal";import { TTokenDALFactory } from "./auth-token-dal";-import { TCreateTokenForUserDTO, TIssueAuthTokenDTO, TokenType, TValidateTokenForUserDTO } from "./auth-token-types";+import {+ TCreateTokenForUserDTO,+ TEmailSignupOtpPayload,+ TIssueAuthTokenDTO,+ TokenType,+ TValidateTokenForUserDTO+} from "./auth-token-types";type TAuthTokenServiceFactoryDep = {tokenDAL: TTokenDALFactory;@@ -358,6 +364,52 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAureturn { user, tokenVersionId: token.tokenVersionId, orgId, orgName, rootOrgId, parentOrgId };};+ const createEmailSignupToken = async (email: string): Promise<string> => {+ const appCfg = getConfig();+ const token = String(crypto.randomInt(10 ** 5, 10 ** 6 - 1));+ const tokenHash = await crypto.hashing().createHash(token, appCfg.SALT_ROUNDS);+ const ttlSeconds = KeyStoreTtls.EmailSignupOtpInSeconds;+ const payload: TEmailSignupOtpPayload = {+ tokenHash,+ triesLeft: 3,+ expiresAt: Date.now() + ttlSeconds * 1000+ };+ const emailHash = crypto.nativeCrypto.createHash("sha256").update(email).digest("hex");+ await keyStore.setItemWithExpiry(KeyStorePrefixes.EmailSignupOtp(emailHash), ttlSeconds, JSON.stringify(payload));+ return token;+ };++ const validateEmailSignupToken = async (email: string, code: string): Promise<void> => {+ const emailHash = crypto.nativeCrypto.createHash("sha256").update(email).digest("hex");+ const raw = await keyStore.getItem(KeyStorePrefixes.EmailSignupOtp(emailHash));+ const parsed = raw ? (JSON.parse(raw) as TEmailSignupOtpPayload) : null;++ // Always run bcrypt comparison for constant-time behaviour regardless of token presence.+ const hashToCompare = parsed?.tokenHash ?? DUMMY_HASH;+ const isValidToken = await crypto.hashing().compareHash(code, hashToCompare);++ if (!parsed || parsed.expiresAt < Date.now()) {+ throw new Error("Invalid token");+ }++ if (!isValidToken) {+ if (parsed.triesLeft <= 1) {+ await keyStore.deleteItem(KeyStorePrefixes.EmailSignupOtp(emailHash));+ } else {+ const remainingTtlSec = Math.max(1, Math.floor((parsed.expiresAt - Date.now()) / 1000));+ const updated: TEmailSignupOtpPayload = { ...parsed, triesLeft: parsed.triesLeft - 1 };+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.EmailSignupOtp(emailHash),+ remainingTtlSec,+ JSON.stringify(updated)+ );+ }+ throw new Error("Invalid token");+ }++ await keyStore.deleteItem(KeyStorePrefixes.EmailSignupOtp(emailHash));+ };+return {createTokenForUser,validateTokenForUser,@@ -369,6 +421,8 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuvalidateRefreshToken,rotateRefreshToken,fnValidateJwtIdentity,- getUserTokenSessionById+ getUserTokenSessionById,+ createEmailSignupToken,+ validateEmailSignupToken};};diff --git a/backend/src/services/auth-token/auth-token-types.ts b/backend/src/services/auth-token/auth-token-types.tsindex fd257809ca..6f493a7cbf 100644--- a/backend/src/services/auth-token/auth-token-types.ts+++ b/backend/src/services/auth-token/auth-token-types.ts@@ -74,3 +74,9 @@ export type TTokenMetadata = {type: TokenMetadataType.InviteToProjects;payload: TTokenInviteToProjectsMetadataPayload;};++export type TEmailSignupOtpPayload = {+ tokenHash: string;+ triesLeft: number;+ expiresAt: number;+};diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.tsindex 1264c7ea62..3325cde6a0 100644--- a/backend/src/services/auth/auth-signup-service.ts+++ b/backend/src/services/auth/auth-signup-service.ts@@ -42,7 +42,7 @@ export const authSignupServiceFactory = ({orgDAL,loginService}: TAuthSignupDep) => {- // first step of signup. create user and send email+ // First step of signup to send OTP emailconst beginEmailSignupProcess = async (email: string) => {const sanitizedEmail = sanitizeEmail(email);validateEmail(sanitizedEmail);@@ -52,8 +52,8 @@ export const authSignupServiceFactory = ({}// akhilmhdh: case sensitive email resolution- let user = await userDAL.findOne({ username: sanitizedEmail });- if (user && user.isAccepted) {+ const existingUser = await userDAL.findOne({ username: sanitizedEmail });+ if (existingUser?.isAccepted) {// Send informational email for existing accounts instead of throwing error// This prevents user enumeration vulnerabilityconst appCfg = getConfig();@@ -74,20 +74,7 @@ export const authSignupServiceFactory = ({return;}- if (!user) {- user = await userDAL.create({- authMethods: [AuthMethod.EMAIL],- username: sanitizedEmail,- email: sanitizedEmail,- isGhost: false- });- }- if (!user) throw new Error("Failed to create user");-- const token = await tokenService.createTokenForUser({- type: TokenType.TOKEN_EMAIL_CONFIRMATION,- userId: user.id- });+ const token = await tokenService.createEmailSignupToken(sanitizedEmail);await smtpService.sendMail({@@ -104,31 +91,29 @@ export const authSignupServiceFactory = ({const verifyEmailSignup = async (email: string, code: string) => {const sanitizedEmail = sanitizeEmail(email);validateEmail(sanitizedEmail);- const user = await userDAL.findOne({ username: sanitizedEmail });-- // Always call validateTokenForUser so the response time includes- // the bcrypt cost regardless of whether the user exists.- // Use a dummy userId when there's no valid user.- const shouldReject = !user || user.isAccepted;-- try {- await tokenService.validateTokenForUser({- type: TokenType.TOKEN_EMAIL_CONFIRMATION,- userId: shouldReject ? DUMMY_USER_ID : user.id,- code- });- } catch {- // If we were going to reject anyway, throw the generic message.- // If the user was valid but the token failed, same generic message.- throw new Error("Invalid or expired verification request");- }- // Reject *after* the constant-time token validation work.- if (shouldReject) {+ await tokenService.validateEmailSignupToken(sanitizedEmail, code);++ // Only create (or recover) the user after the OTP has been verified.+ let user = await userDAL.findOne({ username: sanitizedEmail });+ if (!user) {+ user = await userDAL.create({+ authMethods: [AuthMethod.EMAIL],+ username: sanitizedEmail,+ email: sanitizedEmail,+ isGhost: false,+ isEmailVerified: true+ });+ } else if (!user.isAccepted) {+ // Migration path: pre-user created by the old flow before this refactor.+ await userDAL.updateById(user.id, { isEmailVerified: true });+ user = { ...user, isEmailVerified: true };+ } else {+ // isAccepted guard should have been caught in beginEmailSignupProcess, but defend here too.throw new Error("Invalid or expired verification request");}- await userDAL.updateById(user.id, { isEmailVerified: true });+ if (!user) throw new Error("Failed to create user");const appCfg = getConfig();const jwtToken = crypto.jwt().sign(