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(email): implement email dispatch guard for signup and account recovery
Victor Hugo dos Santos4961f2d38fdc
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 03863ef9c8..d1789ee7f1 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -9,6 +9,7 @@ export const mockKeyStore = (): TKeyStoreFactory => {const store: Record<string, string | number | Buffer> = {};const hashStore: Record<string, Record<string, string>> = {};const sortedSetStore: Record<string, Record<string, number>> = {};+ const distinctStore: Record<string, Set<string>> = {};const getRegex = (pattern: string) =>new RE2(`^${pattern.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&").replace(/\*/g, ".*")}$`);@@ -87,6 +88,13 @@ export const mockKeyStore = (): TKeyStoreFactory => {store[key] = String(next);return next;},+ probeDistinctMember: async (key, member) => {+ if (!distinctStore[key]) distinctStore[key] = new Set<string>();+ const members = distinctStore[key];+ if (members.has(member)) return false;+ members.add(member);+ return true;+ },incrementSeededWithExpiry: async (key, seed) => {const existing = store[key];if (existing === undefined) {diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 0b961908f4..b033ba3821 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -144,7 +144,16 @@ export const KeyStorePrefixes = {RefreshTokenGrace: (sessionId: string) => `refresh-token-grace:${sessionId}` as const,EmailSignupOtpHash: (hash: string) => `email-signup-otp:${hash}:hash` as const,EmailSignupOtpLock: (hash: string) => `email-signup-otp:${hash}:lock` as const,- EmailSignupResendCooldown: (hash: string) => `email-signup-otp:${hash}:cd` as const,+ EmailDispatchCooldown: (purpose: string, mailboxHash: string) =>+ `email-dispatch:${purpose}:${mailboxHash}:cd` as const,+ EmailDispatchMailboxSends: (purpose: string, mailboxHash: string) =>+ `email-dispatch:${purpose}:${mailboxHash}:sends` as const,+ EmailDispatchSourceSends: (purpose: string, ipHash: string) =>+ `email-dispatch:${purpose}:src:${ipHash}:sends` as const,+ EmailDispatchSourceProbe: (purpose: string, window: number) =>+ `email-dispatch-abuse:${purpose}:src:${window}` as const,+ EmailDispatchMailboxProbe: (purpose: string, window: number) =>+ `email-dispatch-abuse:${purpose}:mailbox:${window}` as const,// scopeId is a projectId for the per-project dashboard and an orgId for the org-wide aggregates. Both are// UUIDs and the endpoint segments do not overlap, so one prefix serves both without collision.InsightsCache: (scopeId: string, endpoint: string) => `insights-cache:${scopeId}:${endpoint}` as const,@@ -202,7 +211,10 @@ export const KeyStoreTtls = {TelemetryIdentifyIdentityInSeconds: 86400, // 24 hoursRefreshTokenGraceInSeconds: 10,EmailSignupOtpInSeconds: 300, // 5 minutes- EmailSignupResendCooldownInSeconds: 60, // 1 minute+ EmailDispatchCooldownInSeconds: 60, // 1 minute+ EmailDispatchMailboxWindowInSeconds: 86400, // 24 hours+ EmailDispatchSourceWindowInSeconds: 3600, // 1 hour+ EmailDispatchAbuseProbeInSeconds: 7200, // 2 hoursInsightsCacheInSeconds: 300, // 5 minutesInsightsDuplicationCacheInSeconds: 3600, // 1 hourInsightsWeeklyHistoryCacheInSeconds: 86400, // 24 hours@@ -280,6 +292,7 @@ export type TKeyStoreFactory = {incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;decrementByOrDelete: (key: string) => Promise<number>;incrementByWithExpiry: (key: string, value: number, expiryInSeconds: number) => Promise<number>;+ probeDistinctMember: (key: string, member: string, expiryInSeconds: number) => Promise<boolean>;incrementSeededWithExpiry: (key: string, seed: number, expiryInSeconds: number) => Promise<number>;getKeysByPattern: (pattern: string, limit?: number) => Promise<string[]>;// list operations@@ -505,6 +518,20 @@ export const keyStoreFactory = (return Number(result);};+ const PROBE_DISTINCT_MEMBER = `+ local isNew = redis.call('PFADD', KEYS[1], ARGV[1])+ redis.call('EXPIRE', KEYS[1], ARGV[2])+ return isNew+ `;++ // Records `member` in a HyperLogLog and reports whether it had not been seen in this key before.+ // The HLL stores a fixed ~12KB register array rather than the members themselves, so a caller can+ // count distinct values without the store ever holding one.+ const probeDistinctMember = async (key: string, member: string, expiryInSeconds: number): Promise<boolean> => {+ const result = await primaryRedis.eval(PROBE_DISTINCT_MEMBER, 1, key, member, String(expiryInSeconds));+ return Number(result) === 1;+ };+const setExpiry = async (key: string, expiryInSeconds: number) => primaryRedis.expire(key, expiryInSeconds);const ttl = async (key: string) => primaryRedis.ttl(key);@@ -732,6 +759,7 @@ export const keyStoreFactory = (incrementByAndRefreshExpiryIfUnderLimit,decrementByOrDelete,incrementByWithExpiry,+ probeDistinctMember,incrementSeededWithExpiry,acquireLock(resources: string[], duration: number, settings?: Partial<Settings>) {return redisLock.acquire(resources, duration, settings);diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex b083dca908..4c3e60a258 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -11,6 +11,8 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {const listStore: Record<string, string[]> = {};const hashStore: Record<string, Record<string, string>> = {};const sortedSetStore: Record<string, Record<string, number>> = {};+ // Exact membership rather than a HyperLogLog+ const distinctStore: Record<string, Set<string>> = {};const getRegex = (pattern: string) =>new RE2(`^${pattern.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&").replace(/\*/g, ".*")}$`);@@ -131,6 +133,13 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {store[key] = String(next);return next;},+ probeDistinctMember: async (key, member) => {+ if (!distinctStore[key]) distinctStore[key] = new Set<string>();+ const members = distinctStore[key];+ if (members.has(member)) return false;+ members.add(member);+ return true;+ },incrementSeededWithExpiry: async (key, seed) => {const existing = store[key];if (existing === undefined) {diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex a0395e5eb1..ed10ab6ed6 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -422,6 +422,41 @@ export const coreHttpErrorCounter = infisicalCoreMeter.createCounter("infisical.unit: "{error}"});+// -- Signup abuse (InfisicalCore meter) -------------------------------------------------------------++export enum SignupMailboxProvider {+ GOOGLE = "google",+ OTHER = "other"+}++export enum SignupAddressForm {+ CANONICAL = "canonical",+ ALIASED = "aliased"+}++export enum SignupOtpOutcome {+ SENT = "sent",+ EXISTING_ACCOUNT = "existing-account",+ MAILBOX_CAPPED = "mailbox-capped",+ CAPTCHA_REJECTED = "captcha-rejected"+}++export enum SignupDistinctDimension {+ SOURCE = "source",+ MAILBOX = "mailbox"+}++export const signupOtpRequestCounter = infisicalCoreMeter.createCounter("infisical.signup.otp.request.count", {+ description: "Signup verification code requests by mailbox provider, address form, and outcome.",+ unit: "{request}"+});++export const signupOtpDistinctCounter = infisicalCoreMeter.createCounter("infisical.signup.otp.distinct.count", {+ description:+ "First sighting of a source host or target mailbox within the current signup-abuse window. Compare against the request count to separate a broad campaign from a burst against a few targets.",+ unit: "{entity}"+});+// Rate limit metric. Wired in error-handler.ts on RateLimitError.export const rateLimitExceededCounter = infisicalCoreMeter.createCounter("infisical.rate_limit.exceeded.count", {description: "HTTP 429 responses (rate limit exceeded).",diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.tsindex a7f57bb6b0..c1b7354168 100644--- a/backend/src/lib/telemetry/telemetry-attributes.ts+++ b/backend/src/lib/telemetry/telemetry-attributes.ts@@ -26,6 +26,10 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = ["scim.operation","sso.provider","sso.action",+ "signup.mailbox_provider",+ "signup.address_form",+ "signup.outcome",+ "signup.dimension","db.pool.state",// Closed enums on infisical.legacy_root_key.usage; per-project attribution is in logs, not here."legacy_key.operation",diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.tsindex b36eb0131a..db8b80f9d7 100644--- a/backend/src/lib/validator/index.ts+++ b/backend/src/lib/validator/index.ts@@ -5,7 +5,14 @@ export {} from "./email-domain-matcher";export type { TValidatedHost } from "./safe-request";export { buildSsrfSafeAgent, safeRequest } from "./safe-request";-export { isDisposableEmail, isValidEmailDomain, sanitizeEmail, validateEmail } from "./validate-email";+export {+ isAliasedEmail,+ isDisposableEmail,+ isValidEmailDomain,+ normalizeEmail,+ sanitizeEmail,+ validateEmail+} from "./validate-email";export { isValidFolderName, isValidSecretPath } from "./validate-folder-name";export {containsDangerousSmbChars,diff --git a/backend/src/lib/validator/validate-email.test.ts b/backend/src/lib/validator/validate-email.test.tsnew file mode 100644index 0000000000..93bb5da50c--- /dev/null+++ b/backend/src/lib/validator/validate-email.test.ts@@ -0,0 +1,77 @@+import { isAliasedEmail, normalizeEmail } from "./validate-email";++describe("normalizeEmail", () => {+ test("strips sub-addressing on every provider", () => {+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ });++ test("keeps dots outside Google, where they are significant", () => {+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ expect(normalizeEmail("[email protected]")).not.toBe(normalizeEmail("[email protected]"));+ });++ test("strips dots and folds googlemail onto gmail", () => {+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ });++ test("lowercases and trims", () => {+ expect(normalizeEmail(" [email protected] ")).toBe("[email protected]");+ });++ // Variant shapes reproduced from the Aug 2026 signup-OTP bombing campaign: scattered dots, a random+ // hex sub-address, and gmail/googlemail alternated within one target. Addresses are invented; the+ // real recipients were third parties with no Infisical account and do not belong in the repo.+ // Each target's variants must collapse onto one bucket, or the per-mailbox cooldown and the send cap+ // are bypassed by changing a single character.+ test.each([+ [+ "[email protected]",+ [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]+ ],+ [+ "[email protected]",+ [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]+ ]+ ])("collapses every observed variant onto %s", (mailbox, variants) => {+ expect(new Set(variants.map(normalizeEmail))).toEqual(new Set([mailbox]));+ });++ test("leaves a local part of only separators alone rather than collapsing it to nothing", () => {+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ });++ test("returns malformed input untouched instead of throwing", () => {+ expect(normalizeEmail("not-an-email")).toBe("not-an-email");+ expect(normalizeEmail("@company.com")).toBe("@company.com");+ expect(normalizeEmail("user@")).toBe("user@");+ });+});++describe("isAliasedEmail", () => {+ test("flags variants but not the canonical address", () => {+ expect(isAliasedEmail("[email protected]")).toBe(true);+ expect(isAliasedEmail("[email protected]")).toBe(true);+ expect(isAliasedEmail("[email protected]")).toBe(false);+ expect(isAliasedEmail("[email protected]")).toBe(false);+ });+});diff --git a/backend/src/lib/validator/validate-email.ts b/backend/src/lib/validator/validate-email.tsindex 61f2b5245a..f42df15b60 100644--- a/backend/src/lib/validator/validate-email.ts+++ b/backend/src/lib/validator/validate-email.ts@@ -54,3 +54,33 @@ export const validateEmail = (email: string) => {if (email.toLowerCase().trim() !== email)throw new BadRequestError({ message: "Email contains uppercase characters or leading/trailing whitespace" });};++const DOTLESS_LOCAL_PART_DOMAINS = new Map([+ ["gmail.com", "gmail.com"],+ ["googlemail.com", "gmail.com"]+]);++export const normalizeEmail = (email: string) => {+ const sanitized = sanitizeEmail(email);++ // Domains never contain "@", so the last one is the separator even for a quoted local part.+ const separatorIdx = sanitized.lastIndexOf("@");+ if (separatorIdx <= 0 || separatorIdx === sanitized.length - 1) return sanitized;++ let localPart = sanitized.slice(0, separatorIdx);+ const domain = sanitized.slice(separatorIdx + 1);++ const plusIdx = localPart.indexOf("+");+ if (plusIdx !== -1) localPart = localPart.slice(0, plusIdx);++ const canonicalDomain = DOTLESS_LOCAL_PART_DOMAINS.get(domain);+ if (canonicalDomain) localPart = localPart.replaceAll(".", "");++ // A local part made only of separators would normalize to nothing and collapse every such address+ // onto a single bucket, throttling unrelated senders together. Fall back to the sanitized form.+ if (!localPart) return sanitized;++ return `${localPart}@${canonicalDomain ?? domain}`;+};++export const isAliasedEmail = (email: string) => normalizeEmail(email) !== sanitizeEmail(email);diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex bd9bebd6ae..eb3fa6490c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -249,6 +249,7 @@ import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";import { signupOnboardingResponseDALFactory } from "@app/services/auth/auth-signup-onboarding-dal";import { authSignupServiceFactory } from "@app/services/auth/auth-signup-service";+import { emailDispatchGuardFactory } from "@app/services/auth/email-dispatch-guard";import { mfaLockoutServiceFactory } from "@app/services/auth/mfa-lockout-service";import { tokenDALFactory } from "@app/services/auth-token/auth-token-dal";import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -851,6 +852,7 @@ export const registerRoutes = async (});const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL, membershipUserDAL, orgDAL, keyStore });+ const emailDispatchGuard = emailDispatchGuardFactory({ keyStore });const applicationMembershipCleanupService = applicationMembershipCleanupServiceFactory({membershipDAL,@@ -1396,7 +1398,8 @@ export const registerRoutes = async (tokenService,smtpService,userDAL,- membershipUserDAL+ membershipUserDAL,+ emailDispatchGuard});const projectBotService = projectBotServiceFactory({ permissionService, projectBotDAL, projectDAL });@@ -1470,7 +1473,8 @@ export const registerRoutes = async (orgService,loginService,emailDomainDAL,- signupOnboardingResponseDAL+ signupOnboardingResponseDAL,+ emailDispatchGuard});const microsoftTeamsService = microsoftTeamsServiceFactory({diff --git a/backend/src/server/routes/v1/account-recovery-router.ts b/backend/src/server/routes/v1/account-recovery-router.tsindex 28db274a53..02309ac559 100644--- a/backend/src/server/routes/v1/account-recovery-router.ts+++ b/backend/src/server/routes/v1/account-recovery-router.ts@@ -1,5 +1,6 @@import { z } from "zod";+import { normalizeEmail } from "@app/lib/validator";import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";import { UserEncryption } from "@app/services/user/user-types";@@ -11,13 +12,17 @@ export const registerAccountRecoveryRouter = async (server: FastifyZodProvider)url: "/send-email",config: {rateLimit: smtpRateLimit({- keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp+ keyGenerator: (req) => {+ const email = (req.body as { email?: string })?.email;+ return email ? normalizeEmail(email).substring(0, 100) : req.realIp;+ }})},schema: {operationId: "sendAccountRecoveryEmail",body: z.object({- email: z.string().email().trim()+ email: z.string().trim().email().max(255),+ captchaToken: z.string().trim().max(5000).optional()}),response: {200: z.object({@@ -26,7 +31,11 @@ export const registerAccountRecoveryRouter = async (server: FastifyZodProvider)}},handler: async (req) => {- await server.services.accountRecovery.sendRecoveryEmail(req.body.email);+ await server.services.accountRecovery.sendRecoveryEmail({+ email: req.body.email,+ ip: req.realIp,+ captchaToken: req.body.captchaToken+ });return {message: "If an account exists with this email, a recovery link has been sent"@@ -39,14 +48,17 @@ export const registerAccountRecoveryRouter = async (server: FastifyZodProvider)url: "/verify-email",config: {rateLimit: smtpRateLimit({- keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp+ keyGenerator: (req) => {+ const email = (req.body as { email?: string })?.email;+ return email ? normalizeEmail(email).substring(0, 100) : req.realIp;+ }})},schema: {operationId: "verifyAccountRecoveryEmail",body: z.object({- email: z.string().email().trim(),- code: z.string().trim()+ email: z.string().trim().email().max(255),+ code: z.string().trim().min(1).max(100)}),response: {200: z.object({diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.tsindex 54ecb4f2f2..9ee45fd0d1 100644--- a/backend/src/server/routes/v3/signup-router.ts+++ b/backend/src/server/routes/v3/signup-router.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { getConfig } from "@app/lib/config/env";import { ForbiddenRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { matchesAllowedEmailDomain } from "@app/lib/validator";+import { matchesAllowedEmailDomain, normalizeEmail } from "@app/lib/validator";import { PasswordPolicySchema } from "@app/lib/validator/password-policy";import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";@@ -23,13 +23,17 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {method: "POST",config: {rateLimit: smtpRateLimit({- keyGenerator: (req) => (req.body as { email?: string })?.email?.trim().substring(0, 100) || req.realIp+ keyGenerator: (req) => {+ const email = (req.body as { email?: string })?.email;+ return email ? normalizeEmail(email).substring(0, 100) : req.realIp;+ }})},schema: {operationId: "beginEmailSignupV3",body: z.object({- email: z.string().email().trim()+ email: z.string().trim().email().max(255),+ captchaToken: z.string().trim().max(5000).optional()}),response: {200: z.object({@@ -56,7 +60,11 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {});}}- const { cooldownSeconds } = await server.services.signup.beginEmailSignupProcess(email);+ const { cooldownSeconds } = await server.services.signup.beginEmailSignupProcess({+ email,+ ip: req.realIp,+ captchaToken: req.body.captchaToken+ });return { message: `Sent an email verification code to ${email}`, cooldownSeconds };}});@@ -66,15 +74,17 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {method: "POST",config: {rateLimit: smtpRateLimit({- keyGenerator: (req) =>- (req.body as { email?: string })?.email?.trim()?.toLowerCase().substring(0, 100) || req.realIp+ keyGenerator: (req) => {+ const email = (req.body as { email?: string })?.email;+ return email ? normalizeEmail(email).substring(0, 100) : req.realIp;+ }})},schema: {operationId: "verifyEmailSignupV3",body: z.object({- email: z.string().email().trim(),- code: z.string().trim()+ email: z.string().trim().email().max(255),+ code: z.string().trim().length(6)}),response: {200: z.object({diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.tsindex 239236aea2..84dd8b0329 100644--- a/backend/src/services/account-recovery/account-recovery-service.ts+++ b/backend/src/services/account-recovery/account-recovery-service.ts@@ -11,13 +11,15 @@ import { TMembershipUserDALFactory } from "@app/services/membership-user/membersimport { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";-import { validatePasswordResetAuthorization } from "../auth/auth-fns";+import { validatePasswordResetAuthorization, verifyPublicEmailCaptcha } from "../auth/auth-fns";+import { EmailDispatchPurpose, TEmailDispatchGuardFactory } from "../auth/email-dispatch-guard";type TAccountRecoveryServiceFactoryDep = {userDAL: TUserDALFactory;membershipUserDAL: Pick<TMembershipUserDALFactory, "find">;tokenService: TAuthTokenServiceFactory;smtpService: TSmtpService;+ emailDispatchGuard: TEmailDispatchGuardFactory;};export type TAccountRecoveryServiceFactory = ReturnType<typeof accountRecoveryServiceFactory>;@@ -27,12 +29,38 @@ export const accountRecoveryServiceFactory = ({userDAL,membershipUserDAL,tokenService,- smtpService+ smtpService,+ emailDispatchGuard}: TAccountRecoveryServiceFactoryDep) => {/** Account recovery flow via email. Step 1: send recovery email*/- const sendRecoveryEmail = async (unsanitizedUsername: string) => {+ const sendRecoveryEmail = async ({+ email: unsanitizedUsername,+ ip,+ captchaToken+ }: {+ email: string;+ ip: string;+ captchaToken?: string;+ }) => {+ await verifyPublicEmailCaptcha(captchaToken);+ await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.AccountRecovery, ip });++ const { mailboxHash } = await emailDispatchGuard.acquireMailboxCooldown({+ purpose: EmailDispatchPurpose.AccountRecovery,+ email: unsanitizedUsername+ });++ if (+ !(await emailDispatchGuard.consumeMailboxAllowance({+ purpose: EmailDispatchPurpose.AccountRecovery,+ mailboxHash+ }))+ ) {+ return;+ }+const sendEmail = async () => {const username = sanitizeEmail(unsanitizedUsername);const user = await userDAL.findOne({ username });@@ -111,6 +139,11 @@ export const accountRecoveryServiceFactory = ({throw new Error("Invalid or expired verification request");}+ await emailDispatchGuard.clearMailboxThrottle({+ purpose: EmailDispatchPurpose.AccountRecovery,+ mailboxHash: emailDispatchGuard.hashAddress(username).mailboxHash+ });+const token = crypto.jwt().sign({authTokenType: AuthTokenType.ACCOUNT_RECOVERY_TOKEN,diff --git a/backend/src/services/auth-token/auth-token-service.test.ts b/backend/src/services/auth-token/auth-token-service.test.tsindex 9dd7fcf14f..142525e64a 100644--- a/backend/src/services/auth-token/auth-token-service.test.ts+++ b/backend/src/services/auth-token/auth-token-service.test.ts@@ -4,7 +4,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, type Mockimport { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto/cryptography";-import { BadRequestError, UnauthorizedError } from "@app/lib/errors";+import { UnauthorizedError } from "@app/lib/errors";import { tokenServiceFactory } from "./auth-token-service";import { TEmailSignupOtpPayload } from "./auth-token-types";@@ -25,7 +25,6 @@ const hmac = (value: string) => createHmac("sha256", AUTH_SECRET).update(value).const emailHash = hmac(TEST_EMAIL);const otpKey = KeyStorePrefixes.EmailSignupOtpHash(emailHash);-const cooldownKey = KeyStorePrefixes.EmailSignupResendCooldown(emailHash);type KeyStoreSlice = Pick<TKeyStoreFactory,@@ -129,51 +128,6 @@ describe("tokenServiceFactory — email signup OTP", () => {vi.clearAllMocks();});- describe("acquireEmailSignupCooldown", () => {- test("returns emailHash and cooldownSeconds on first call", async () => {- const { service } = setup();-- const result = await service.acquireEmailSignupCooldown(TEST_EMAIL);-- expect(result.emailHash).toBe(emailHash);- expect(result.cooldownSeconds).toBe(KeyStoreTtls.EmailSignupResendCooldownInSeconds);- });-- test("sets cooldown key atomically via NX", async () => {- const { service, keyStore } = setup();-- await service.acquireEmailSignupCooldown(TEST_EMAIL);-- expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledWith(- cooldownKey,- KeyStoreTtls.EmailSignupResendCooldownInSeconds,- "1"- );- });-- test("throws when cooldown is active", async () => {- const { service } = setup().mockCooldown(45);-- await expectRejected(service.acquireEmailSignupCooldown(TEST_EMAIL), BadRequestError);- });-- test("reports remaining TTL in error details", async () => {- const { service } = setup().mockCooldown(30);-- const err = await expectRejected(service.acquireEmailSignupCooldown(TEST_EMAIL), BadRequestError);-- expect(err.details).toMatchObject({ cooldownSeconds: 30 });- });-- test("clamps remaining TTL to minimum 1", async () => {- const { service } = setup().mockCooldown(-1);-- const err = await expectRejected(service.acquireEmailSignupCooldown(TEST_EMAIL), BadRequestError);-- expect(err.details).toMatchObject({ cooldownSeconds: 1 });- });- });-describe("createEmailSignupToken", () => {test("returns a six-digit numeric token", async () => {const { service } = setup();@@ -230,12 +184,12 @@ describe("tokenServiceFactory — email signup OTP", () => {await expect(service.validateEmailSignupToken(TEST_EMAIL, "123456")).resolves.toBeUndefined();});- test("deletes OTP and cooldown on success", async () => {+ test("deletes the OTP on success", async () => {const { service, keyStore } = setup().mockOtp();await service.validateEmailSignupToken(TEST_EMAIL, "123456");- expect(keyStore.deleteItemsByKeyIn).toHaveBeenCalledWith(expect.arrayContaining([otpKey, cooldownKey]));+ expect(keyStore.deleteItem).toHaveBeenCalledWith(otpKey);});test("throws when OTP missing", async () => {diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.tsindex cbdd39e47e..d79e95c5c7 100644--- a/backend/src/services/auth-token/auth-token-service.ts+++ b/backend/src/services/auth-token/auth-token-service.ts@@ -30,13 +30,7 @@ type TAuthTokenServiceFactoryDep = {membershipUserDAL: Pick<TMembershipUserDALFactory, "findOne">;keyStore: Pick<TKeyStoreFactory,- | "setItemWithExpiry"- | "setItemWithExpiryNX"- | "getItem"- | "deleteItem"- | "acquireLock"- | "deleteItemsByKeyIn"- | "ttl"+ "setItemWithExpiry" | "setItemWithExpiryNX" | "getItem" | "deleteItem" | "acquireLock" | "ttl">;};@@ -443,30 +437,6 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAureturn { user, tokenVersionId: token.tokenVersionId, orgId, orgName, rootOrgId, parentOrgId };};- const acquireEmailSignupCooldown = async (email: string): Promise<{ emailHash: string; cooldownSeconds: number }> => {- const appCfg = getConfig();- const emailHash = computeHash(email, appCfg.AUTH_SECRET);- const cooldownKey = KeyStorePrefixes.EmailSignupResendCooldown(emailHash);- const cooldownSeconds = KeyStoreTtls.EmailSignupResendCooldownInSeconds;-- // SET NX is atomic: only one concurrent request can acquire the cooldown slot.- const acquired = await keyStore.setItemWithExpiryNX(cooldownKey, cooldownSeconds, "1");- if (!acquired) {- const remaining = await keyStore.ttl(cooldownKey);- throw new BadRequestError({- message: "Please wait before requesting another code",- details: {- cooldownSeconds: Math.max(1, remaining)- }- });- }-- return {- emailHash,- cooldownSeconds- };- };-const createEmailSignupToken = async (emailHash: string): Promise<string> => {const appCfg = getConfig();const token = generateSixDigitToken();@@ -539,8 +509,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu});}- const cooldownKey = KeyStorePrefixes.EmailSignupResendCooldown(emailHash);- await keyStore.deleteItemsByKeyIn([key, cooldownKey]);+ await keyStore.deleteItem(key);} finally {await lock.release();}@@ -560,7 +529,6 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAurotateRefreshToken,fnValidateJwtIdentity,getUserTokenSessionById,- acquireEmailSignupCooldown,createEmailSignupToken,validateEmailSignupToken};diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.tsindex 6edeea51c7..a8de6b6f4c 100644--- a/backend/src/services/auth/auth-fns.ts+++ b/backend/src/services/auth/auth-fns.ts@@ -145,6 +145,20 @@ export const enforceUserLockStatus = (isLocked: boolean, temporaryLockDateEnd?:}};+const assertValidCaptchaToken = async (captchaToken: string) => {+ const appCfg = getConfig();+ const response = await request.postForm<{ success: boolean }>("https://api.hcaptcha.com/siteverify", {+ response: captchaToken,+ secret: appCfg.CAPTCHA_SECRET+ });++ if (!response.data.success) {+ throw new BadRequestError({+ name: "Invalid Captcha"+ });+ }+};+export const verifyCaptcha = async (consecutiveFailedPasswordAttempts?: number | null, captchaToken?: string) => {const appCfg = getConfig();if (consecutiveFailedPasswordAttempts && consecutiveFailedPasswordAttempts >= 10 && Boolean(appCfg.CAPTCHA_SECRET)) {@@ -155,18 +169,22 @@ export const verifyCaptcha = async (consecutiveFailedPasswordAttempts?: number |});}- // validate captcha token- const response = await request.postForm<{ success: boolean }>("https://api.hcaptcha.com/siteverify", {- response: captchaToken,- secret: appCfg.CAPTCHA_SECRET- });+ await assertValidCaptchaToken(captchaToken);+ }+};- if (!response.data.success) {- throw new BadRequestError({- name: "Invalid Captcha"- });- }+export const verifyPublicEmailCaptcha = async (captchaToken?: string) => {+ const appCfg = getConfig();+ if (!appCfg.CAPTCHA_SECRET) return;++ if (!captchaToken) {+ throw new BadRequestError({+ name: "Captcha Required",+ message: "Complete the captcha to continue"+ });}++ await assertValidCaptchaToken(captchaToken);};/*diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.tsindex 7f17632b81..63a6d3929c 100644--- a/backend/src/services/auth/auth-signup-service.ts+++ b/backend/src/services/auth/auth-signup-service.ts@@ -5,7 +5,15 @@ import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, UnauthorizedError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";+import {+ SignupAddressForm,+ SignupDistinctDimension,+ SignupMailboxProvider,+ signupOtpDistinctCounter,+ SignupOtpOutcome,+ signupOtpRequestCounter+} from "@app/lib/telemetry/metrics";+import { isAliasedEmail, isDisposableEmail, normalizeEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";import { TokenType } from "../auth-token/auth-token-types";@@ -15,11 +23,12 @@ import { SmtpTemplates, throwIfSmtpError, TSmtpService } from "../smtp/smtp-servimport { TUserDALFactory } from "../user/user-dal";import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";import { TAuthDALFactory } from "./auth-dal";-import { extractBearerToken, resolveInvitingOrgId } from "./auth-fns";+import { extractBearerToken, resolveInvitingOrgId, verifyPublicEmailCaptcha } from "./auth-fns";import { TAuthLoginFactory } from "./auth-login-service";import { TSignupOnboardingResponseDALFactory } from "./auth-signup-onboarding-dal";import { CompleteAccountType, TCompleteAccountDTO, TRecordSignupOnboardingDTO } from "./auth-signup-type";import { AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType } from "./auth-type";+import { EmailDispatchPurpose, TEmailDispatchGuardFactory } from "./email-dispatch-guard";type TAuthSignupDep = {authDAL: TAuthDALFactory;@@ -32,10 +41,18 @@ type TAuthSignupDep = {loginService: Pick<TAuthLoginFactory, "generateUserTokens">;emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;signupOnboardingResponseDAL: Pick<TSignupOnboardingResponseDALFactory, "upsert">;+ emailDispatchGuard: TEmailDispatchGuardFactory;};const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";+const signupTrafficAttributes = (email: string) => ({+ "signup.mailbox_provider": normalizeEmail(email).endsWith("@gmail.com")+ ? SignupMailboxProvider.GOOGLE+ : SignupMailboxProvider.OTHER,+ "signup.address_form": isAliasedEmail(email) ? SignupAddressForm.ALIASED : SignupAddressForm.CANONICAL+});+export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>;export const authSignupServiceFactory = ({authDAL,@@ -47,20 +64,61 @@ export const authSignupServiceFactory = ({orgDAL,loginService,emailDomainDAL,- signupOnboardingResponseDAL+ signupOnboardingResponseDAL,+ emailDispatchGuard}: TAuthSignupDep) => {// First step of signup to send OTP email- const beginEmailSignupProcess = async (email: string): Promise<{ cooldownSeconds: number }> => {+ const beginEmailSignupProcess = async ({+ email,+ ip,+ captchaToken+ }: {+ email: string;+ ip: string;+ captchaToken?: string;+ }): Promise<{ cooldownSeconds: number }> => {const sanitizedEmail = sanitizeEmail(email);validateEmail(sanitizedEmail);++ const trafficAttributes = signupTrafficAttributes(sanitizedEmail);++ try {+ await verifyPublicEmailCaptcha(captchaToken);+ } catch (err) {+ signupOtpRequestCounter.add(1, {+ ...trafficAttributes,+ "signup.outcome": SignupOtpOutcome.CAPTCHA_REJECTED+ });+ throw err;+ }+const isEmailInvalid = await isDisposableEmail(sanitizedEmail);if (isEmailInvalid) {- throw new Error("Provided a disposable email");+ throw new BadRequestError({ message: "Disposable email addresses cannot be used to sign up" });}- // Acquire cooldown before any operation to avoid reliable enumeration oracle and to throttle the- // unauthenticated DB queries below (e.g. the SSO-enforced domain lookup).- const { emailHash, cooldownSeconds } = await tokenService.acquireEmailSignupCooldown(sanitizedEmail);+ await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip });++ const { emailHash, mailboxHash, cooldownSeconds } = await emailDispatchGuard.acquireMailboxCooldown({+ purpose: EmailDispatchPurpose.Signup,+ email: sanitizedEmail+ });++ const { isNewSource, isNewMailbox } = await emailDispatchGuard.probeTraffic({+ purpose: EmailDispatchPurpose.Signup,+ mailboxHash,+ ip+ });+ if (isNewSource) signupOtpDistinctCounter.add(1, { "signup.dimension": SignupDistinctDimension.SOURCE });+ if (isNewMailbox) signupOtpDistinctCounter.add(1, { "signup.dimension": SignupDistinctDimension.MAILBOX });++ if (!(await emailDispatchGuard.consumeMailboxAllowance({ purpose: EmailDispatchPurpose.Signup, mailboxHash }))) {+ signupOtpRequestCounter.add(1, {+ ...trafficAttributes,+ "signup.outcome": SignupOtpOutcome.MAILBOX_CAPPED+ });+ return { cooldownSeconds };+ }// Block email/password signup for domains owned by an org that enforces SSO. The org's verified// domain + IdP are authoritative, so allowing a competing password account would reopen an@@ -98,6 +156,10 @@ export const authSignupServiceFactory = ({.catch((err) =>logger.error(err, "Failed to send existing account email — swallowing to prevent user enumeration"));+ signupOtpRequestCounter.add(1, {+ ...trafficAttributes,+ "signup.outcome": SignupOtpOutcome.EXISTING_ACCOUNT+ });return { cooldownSeconds };}@@ -114,6 +176,8 @@ export const authSignupServiceFactory = ({}).catch((err) => throwIfSmtpError(err, "Failed to send signup verification email"));+ signupOtpRequestCounter.add(1, { ...trafficAttributes, "signup.outcome": SignupOtpOutcome.SENT });+return { cooldownSeconds };};@@ -122,6 +186,10 @@ export const authSignupServiceFactory = ({validateEmail(sanitizedEmail);await tokenService.validateEmailSignupToken(sanitizedEmail, code);+ await emailDispatchGuard.clearMailboxThrottle({+ purpose: EmailDispatchPurpose.Signup,+ mailboxHash: emailDispatchGuard.hashAddress(sanitizedEmail).mailboxHash+ });// Only create (or recover) the user after the OTP has been verified.let user = await userDAL.findOne({ username: sanitizedEmail });diff --git a/backend/src/services/auth/email-dispatch-guard.test.ts b/backend/src/services/auth/email-dispatch-guard.test.tsnew file mode 100644index 0000000000..b77db4c740--- /dev/null+++ b/backend/src/services/auth/email-dispatch-guard.test.ts@@ -0,0 +1,236 @@+import { createHmac } from "node:crypto";++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, type Mocked, test, vi } from "vitest";++import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError, RateLimitError } from "@app/lib/errors";++import { emailDispatchGuardFactory, EmailDispatchPurpose } from "./email-dispatch-guard";++const AUTH_SECRET = "test-secret-for-email-dispatch-unit-tests";+const NOW_MS = 1_700_000_000_000;++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({ AUTH_SECRET })+}));++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++const hmac = (value: string) => createHmac("sha256", AUTH_SECRET).update(value).digest("hex");++type KeyStoreSlice = Pick<+ TKeyStoreFactory,+ "setItemWithExpiryNX" | "ttl" | "incrementByWithExpiry" | "deleteItemsByKeyIn" | "probeDistinctMember"+>;++type MockedKeyStore = Mocked<KeyStoreSlice>;++const setup = () => {+ const keyStore = {+ setItemWithExpiryNX: vi.fn().mockResolvedValue("OK"),+ ttl: vi.fn().mockResolvedValue(-1),+ incrementByWithExpiry: vi.fn().mockResolvedValue(1),+ deleteItemsByKeyIn: vi.fn().mockResolvedValue(2),+ probeDistinctMember: vi.fn().mockResolvedValue(true)+ } as MockedKeyStore;++ return { keyStore, guard: emailDispatchGuardFactory({ keyStore: keyStore as never }) };+};++const expectRejected = async <T, E extends Error>(+ promise: Promise<T>,+ ErrorType: new (...args: never[]) => E+): Promise<E> => {+ try {+ await promise;+ throw new Error("Expected rejection");+ } catch (e) {+ expect(e).toBeInstanceOf(ErrorType);+ return e as E;+ }+};++describe("emailDispatchGuard", () => {+ beforeAll(async () => {+ process.env.FIPS_ENABLED = "false";+ await crypto.initialize({} as never, {} as never, {} as never);+ });++ afterAll(() => {+ delete process.env.FIPS_ENABLED;+ });++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(NOW_MS));+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ describe("hashAddress", () => {+ test("keys the code on the literal address and the throttles on the mailbox", () => {+ const { guard } = setup();++ const { emailHash, mailboxHash } = guard.hashAddress("[email protected]");++ expect(emailHash).toBe(hmac("[email protected]"));+ expect(mailboxHash).toBe(hmac("[email protected]"));+ });++ test("dots survive outside Google, where they distinguish real people", () => {+ const { guard } = setup();++ expect(guard.hashAddress("[email protected]").mailboxHash).toBe(hmac("[email protected]"));+ expect(guard.hashAddress("[email protected]").mailboxHash).not.toBe(hmac("[email protected]"));+ });+ });++ describe("acquireMailboxCooldown", () => {+ // The signup bombing campaign varied dots and +tags; account recovery was reachable by varying+ // case alone, since its lookup lowercased the address while its rate-limit key did not. Both+ // collapse onto one bucket here or the cooldown is bypassable by changing a single character.+ test.each([+ ["[email protected]", "[email protected]"],+ ["[email protected]", "[email protected]"],+ ["[email protected]", "[email protected]"],+ ["[email protected]", "[email protected]"],+ ["[email protected]", "[email protected]"]+ ])("%s shares the bucket of %s", async (variant, mailbox) => {+ const { keyStore, guard } = setup();++ await guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: variant });++ expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledWith(+ KeyStorePrefixes.EmailDispatchCooldown(EmailDispatchPurpose.Signup, hmac(mailbox)),+ KeyStoreTtls.EmailDispatchCooldownInSeconds,+ "1"+ );+ });++ test("signup and recovery do not share a bucket", async () => {+ const { keyStore, guard } = setup();++ await guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" });+ await guard.acquireMailboxCooldown({+ purpose: EmailDispatchPurpose.AccountRecovery,+ email: "[email protected]"+ });++ const keys = keyStore.setItemWithExpiryNX.mock.calls.map(([key]) => key);+ expect(new Set(keys).size).toBe(2);+ });++ test("reports remaining TTL when the cooldown is active", async () => {+ const { keyStore, guard } = setup();+ keyStore.setItemWithExpiryNX.mockResolvedValue(null);+ keyStore.ttl.mockResolvedValue(30);++ const err = await expectRejected(+ guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),+ BadRequestError+ );++ expect(err.details).toMatchObject({ cooldownSeconds: 30 });+ });++ test("clamps remaining TTL to a minimum of 1", async () => {+ const { keyStore, guard } = setup();+ keyStore.setItemWithExpiryNX.mockResolvedValue(null);+ keyStore.ttl.mockResolvedValue(-1);++ const err = await expectRejected(+ guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),+ BadRequestError+ );++ expect(err.details).toMatchObject({ cooldownSeconds: 1 });+ });+ });++ describe("consumeMailboxAllowance", () => {+ test("allows up to the cap and refuses past it", async () => {+ const { keyStore, guard } = setup();+ const args = { purpose: EmailDispatchPurpose.Signup, mailboxHash: hmac("[email protected]") };++ keyStore.incrementByWithExpiry.mockResolvedValueOnce(5);+ await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(true);++ keyStore.incrementByWithExpiry.mockResolvedValueOnce(6);+ await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(false);+ });++ test("counts refused attempts, so an active campaign keeps the window rolling forward", async () => {+ const { keyStore, guard } = setup();+ const mailboxHash = hmac("[email protected]");+ keyStore.incrementByWithExpiry.mockResolvedValue(99);++ await guard.consumeMailboxAllowance({ purpose: EmailDispatchPurpose.Signup, mailboxHash });++ expect(keyStore.incrementByWithExpiry).toHaveBeenCalledWith(+ KeyStorePrefixes.EmailDispatchMailboxSends(EmailDispatchPurpose.Signup, mailboxHash),+ 1,+ KeyStoreTtls.EmailDispatchMailboxWindowInSeconds+ );+ });+ });++ describe("consumeSourceAllowance", () => {+ test("hashes the source address before it reaches the store", async () => {+ const { keyStore, guard } = setup();++ await guard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" });++ const [key] = keyStore.incrementByWithExpiry.mock.calls[0];+ expect(key).toContain(hmac("203.0.113.7"));+ expect(key).not.toContain("203.0.113.7");+ });++ test("allows a busy shared address up to the cap, then refuses loudly", async () => {+ const { keyStore, guard } = setup();+ const args = { purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" };++ keyStore.incrementByWithExpiry.mockResolvedValueOnce(20);+ await expect(guard.consumeSourceAllowance(args)).resolves.toBeUndefined();++ keyStore.incrementByWithExpiry.mockResolvedValueOnce(21);+ await expectRejected(guard.consumeSourceAllowance(args), RateLimitError);+ });+ });++ describe("clearMailboxThrottle", () => {+ test("drops both the cooldown and the send counter for that purpose", async () => {+ const { keyStore, guard } = setup();+ const mailboxHash = hmac("[email protected]");++ await guard.clearMailboxThrottle({ purpose: EmailDispatchPurpose.AccountRecovery, mailboxHash });++ expect(keyStore.deleteItemsByKeyIn).toHaveBeenCalledWith([+ KeyStorePrefixes.EmailDispatchCooldown(EmailDispatchPurpose.AccountRecovery, mailboxHash),+ KeyStorePrefixes.EmailDispatchMailboxSends(EmailDispatchPurpose.AccountRecovery, mailboxHash)+ ]);+ });+ });++ describe("probeTraffic", () => {+ test("stores only HMACs, never the address or the IP", async () => {+ const { keyStore, guard } = setup();++ await guard.probeTraffic({+ purpose: EmailDispatchPurpose.Signup,+ mailboxHash: hmac("[email protected]"),+ ip: "203.0.113.7"+ });++ const members = keyStore.probeDistinctMember.mock.calls.map(([, member]) => member);+ expect(members).toContain(hmac("203.0.113.7"));+ expect(members).not.toContain("203.0.113.7");+ expect(members).not.toContain("[email protected]");+ });+ });+});diff --git a/backend/src/services/auth/email-dispatch-guard.ts b/backend/src/services/auth/email-dispatch-guard.tsnew file mode 100644index 0000000000..ad2c5bbd67--- /dev/null+++ b/backend/src/services/auth/email-dispatch-guard.ts@@ -0,0 +1,133 @@+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";+import { getConfig } from "@app/lib/config/env";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError, RateLimitError } from "@app/lib/errors";+import { normalizeEmail } from "@app/lib/validator";++export enum EmailDispatchPurpose {+ Signup = "signup",+ AccountRecovery = "account-recovery"+}++const MAX_UNCONFIRMED_SENDS_PER_MAILBOX = 5;+const MAX_SENDS_PER_SOURCE = 20;++const computeHash = (key: string, pepper: string): string =>+ crypto.nativeCrypto.createHmac("sha256", pepper).update(key).digest("hex");++const probeWindow = () => Math.floor(Date.now() / (KeyStoreTtls.EmailDispatchAbuseProbeInSeconds * 1000));++export type TEmailDispatchGuardFactory = ReturnType<typeof emailDispatchGuardFactory>;++export const emailDispatchGuardFactory = ({+ keyStore+}: {+ keyStore: Pick<+ TKeyStoreFactory,+ "setItemWithExpiryNX" | "ttl" | "incrementByWithExpiry" | "deleteItemsByKeyIn" | "probeDistinctMember"+ >;+}) => {+ // emailHash is the literal address (OTP verification); mailboxHash is normalized (all throttles below).+ const hashAddress = (email: string) => {+ const appCfg = getConfig();+ return {+ emailHash: computeHash(email, appCfg.AUTH_SECRET),+ mailboxHash: computeHash(normalizeEmail(email), appCfg.AUTH_SECRET)+ };+ };++ const acquireMailboxCooldown = async ({ purpose, email }: { purpose: EmailDispatchPurpose; email: string }) => {+ const { emailHash, mailboxHash } = hashAddress(email);+ const cooldownKey = KeyStorePrefixes.EmailDispatchCooldown(purpose, mailboxHash);+ const cooldownSeconds = KeyStoreTtls.EmailDispatchCooldownInSeconds;++ const acquired = await keyStore.setItemWithExpiryNX(cooldownKey, cooldownSeconds, "1");+ if (!acquired) {+ const remaining = await keyStore.ttl(cooldownKey);+ throw new BadRequestError({+ message: "Please wait before requesting another email",+ details: { cooldownSeconds: Math.max(1, remaining) }+ });+ }++ return { emailHash, mailboxHash, cooldownSeconds };+ };++ const consumeSourceAllowance = async ({ purpose, ip }: { purpose: EmailDispatchPurpose; ip: string }) => {+ const appCfg = getConfig();+ const sends = await keyStore.incrementByWithExpiry(+ KeyStorePrefixes.EmailDispatchSourceSends(purpose, computeHash(ip, appCfg.AUTH_SECRET)),+ 1,+ KeyStoreTtls.EmailDispatchSourceWindowInSeconds+ );++ if (sends > MAX_SENDS_PER_SOURCE) {+ throw new RateLimitError({+ message: "Too many requests from this network. Please try again later."+ });+ }+ };++ const consumeMailboxAllowance = async ({+ purpose,+ mailboxHash+ }: {+ purpose: EmailDispatchPurpose;+ mailboxHash: string;+ }): Promise<boolean> => {+ const sends = await keyStore.incrementByWithExpiry(+ KeyStorePrefixes.EmailDispatchMailboxSends(purpose, mailboxHash),+ 1,+ KeyStoreTtls.EmailDispatchMailboxWindowInSeconds+ );++ return sends <= MAX_UNCONFIRMED_SENDS_PER_MAILBOX;+ };++ const clearMailboxThrottle = async ({+ purpose,+ mailboxHash+ }: {+ purpose: EmailDispatchPurpose;+ mailboxHash: string;+ }) => {+ await keyStore.deleteItemsByKeyIn([+ KeyStorePrefixes.EmailDispatchCooldown(purpose, mailboxHash),+ KeyStorePrefixes.EmailDispatchMailboxSends(purpose, mailboxHash)+ ]);+ };++ const probeTraffic = async ({+ purpose,+ mailboxHash,+ ip+ }: {+ purpose: EmailDispatchPurpose;+ mailboxHash: string;+ ip: string;+ }): Promise<{ isNewSource: boolean; isNewMailbox: boolean }> => {+ const appCfg = getConfig();+ const window = probeWindow();+ const ttl = KeyStoreTtls.EmailDispatchAbuseProbeInSeconds;++ const [isNewSource, isNewMailbox] = await Promise.all([+ keyStore.probeDistinctMember(+ KeyStorePrefixes.EmailDispatchSourceProbe(purpose, window),+ computeHash(ip, appCfg.AUTH_SECRET),+ ttl+ ),+ keyStore.probeDistinctMember(KeyStorePrefixes.EmailDispatchMailboxProbe(purpose, window), mailboxHash, ttl)+ ]);++ return { isNewSource, isNewMailbox };+ };++ return {+ hashAddress,+ acquireMailboxCooldown,+ consumeSourceAllowance,+ consumeMailboxAllowance,+ clearMailboxThrottle,+ probeTraffic+ };+};diff --git a/frontend/src/components/auth/InitialSignupStep.tsx b/frontend/src/components/auth/InitialSignupStep.tsxindex 96614c75b6..0fa78a5462 100644--- a/frontend/src/components/auth/InitialSignupStep.tsx+++ b/frontend/src/components/auth/InitialSignupStep.tsx@@ -1,7 +1,8 @@-import { useState } from "react";+import { useRef, useState } from "react";import { useTranslation } from "react-i18next";import { faGithub, faGitlab, faGoogle } from "@fortawesome/free-brands-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import HCaptcha from "@hcaptcha/react-hcaptcha";import { Link } from "@tanstack/react-router";import { z } from "zod";@@ -17,6 +18,7 @@ import {FieldSeparator,Input} from "@app/components/v3";+import { envConfig } from "@app/config/env";import { useServerConfig } from "@app/context";import { preserveHubSpotUtk } from "@app/helpers/utmTracking";import { useSendVerificationEmail } from "@app/hooks/api";@@ -43,8 +45,12 @@ export default function InitialSignupStep({const { config } = useServerConfig();const { mutateAsync, isPending } = useSendVerificationEmail();const [emailError, setEmailError] = useState(false);+ const [captchaToken, setCaptchaToken] = useState("");+ const captchaRef = useRef<HCaptcha>(null);const isEmailValid = z.string().email().safeParse(email).success;+ const requiresCaptcha = Boolean(envConfig.CAPTCHA_SITE_KEY);+const shouldDisplaySignupMethod = (method: LoginMethod) =>!config.enabledLoginMethods || config.enabledLoginMethods.includes(method);@@ -70,8 +76,19 @@ export default function InitialSignupStep({return;}- const { cooldownSeconds } = await mutateAsync({ email: normalizedEmail });- incrementStep(normalizedEmail, cooldownSeconds);+ try {+ const { cooldownSeconds } = await mutateAsync({+ email: normalizedEmail,+ captchaToken: requiresCaptcha ? captchaToken : undefined+ });+ incrementStep(normalizedEmail, cooldownSeconds);+ } finally {+ // hCaptcha tokens are single-use, so a retry with a stale one is rejected server-side.+ if (requiresCaptcha) {+ captchaRef.current?.resetCaptcha();+ setCaptchaToken("");+ }+ }};const handleSocialSignup = (method: LoginMethod) => {@@ -155,13 +172,24 @@ export default function InitialSignupStep({className="h-10"isError={emailError}/>+ {envConfig.CAPTCHA_SITE_KEY && (+ <div className="flex justify-center [&>div]:!w-full">+ <HCaptcha+ theme="dark"+ sitekey={envConfig.CAPTCHA_SITE_KEY}+ onVerify={(token) => setCaptchaToken(token)}+ onExpire={() => setCaptchaToken("")}+ ref={captchaRef}+ />+ </div>+ )}<Buttontype="submit"onClick={handleEmailSignup}variant="project"size="lg"isFullWidth- isDisabled={!isEmailValid || isPending}+ isDisabled={!isEmailValid || isPending || (requiresCaptcha && !captchaToken)}isPending={isPending}>Continue with Emaildiff --git a/frontend/src/hooks/api/accountRecovery/mutation.tsx b/frontend/src/hooks/api/accountRecovery/mutation.tsxindex 647ba2db69..26937da882 100644--- a/frontend/src/hooks/api/accountRecovery/mutation.tsx+++ b/frontend/src/hooks/api/accountRecovery/mutation.tsx@@ -10,9 +10,10 @@ import {export const useSendAccountRecoveryEmail = () => {return useMutation({- mutationFn: async ({ email }: TSendAccountRecoveryEmailDTO) => {+ mutationFn: async ({ email, captchaToken }: TSendAccountRecoveryEmailDTO) => {const { data } = await apiRequest.post("/api/v1/account-recovery/send-email", {+ email,+ captchaToken});return data;diff --git a/frontend/src/hooks/api/accountRecovery/types.ts b/frontend/src/hooks/api/accountRecovery/types.tsindex 6ca37ae83d..2fa5d56139 100644--- a/frontend/src/hooks/api/accountRecovery/types.ts+++ b/frontend/src/hooks/api/accountRecovery/types.ts@@ -2,6 +2,7 @@ import { UserEncryptionVersion } from "../auth/types";export type TSendAccountRecoveryEmailDTO = {email: string;+ captchaToken?: string;};export type TVerifyAccountRecoveryEmailDTO = {diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsxindex 582e1e51b2..20a9ff545f 100644--- a/frontend/src/hooks/api/auth/queries.tsx+++ b/frontend/src/hooks/api/auth/queries.tsx@@ -210,10 +210,10 @@ export const verifySignupInvite = async (details: VerifySignupInviteDTO) => {export const useSendVerificationEmail = () => {return useMutation({- mutationFn: async ({ email }: { email: string }) => {+ mutationFn: async ({ email, captchaToken }: { email: string; captchaToken?: string }) => {const { data } = await apiRequest.post<{ message: string; cooldownSeconds: number }>("/api/v3/signup/email/signup",- { email }+ { email, captchaToken });return data;diff --git a/frontend/src/pages/auth/AccountRecoveryEmailPage/AccountRecoveryEmailPage.tsx b/frontend/src/pages/auth/AccountRecoveryEmailPage/AccountRecoveryEmailPage.tsxindex 35855938eb..396fbd981c 100644--- a/frontend/src/pages/auth/AccountRecoveryEmailPage/AccountRecoveryEmailPage.tsx+++ b/frontend/src/pages/auth/AccountRecoveryEmailPage/AccountRecoveryEmailPage.tsx@@ -1,5 +1,6 @@-import { FormEvent, useState } from "react";+import { FormEvent, useRef, useState } from "react";import { Helmet } from "react-helmet";+import HCaptcha from "@hcaptcha/react-hcaptcha";import { Link } from "@tanstack/react-router";import { MailCheck } from "lucide-react";@@ -7,6 +8,7 @@ import { AuthPageLayout } from "@app/components/auth/AuthPageLayout";import { AuthPagePanel } from "@app/components/auth/AuthPagePanel";import { EmailServiceSetupModal } from "@app/components/auth/EmailServiceSetupModal";import { Button, CardContent, CardHeader, CardTitle, Input } from "@app/components/v3";+import { envConfig } from "@app/config/env";import { usePopUp } from "@app/hooks";import { useSendAccountRecoveryEmail } from "@app/hooks/api";import { useFetchServerStatus } from "@app/hooks/api/serverDetails";@@ -19,14 +21,23 @@ export const AccountRecoveryEmailPage = () => {const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["setUpEmail"] as const);const { mutateAsync } = useSendAccountRecoveryEmail();+ const [captchaToken, setCaptchaToken] = useState("");+ const captchaRef = useRef<HCaptcha>(null);++ const requiresCaptcha = Boolean(envConfig.CAPTCHA_SITE_KEY);const sendRecoveryEmail = async () => {if (email) {try {- await mutateAsync({ email });+ await mutateAsync({ email, captchaToken: requiresCaptcha ? captchaToken : undefined });setStep(2);} catch {setLoading(false);+ } finally {+ if (requiresCaptcha) {+ captchaRef.current?.resetCaptcha();+ setCaptchaToken("");+ }}}};@@ -78,7 +89,25 @@ export const AccountRecoveryEmailPage = () => {autoComplete="username"className="h-10"/>- <Button type="submit" variant="project" size="lg" isFullWidth isPending={loading}>+ {envConfig.CAPTCHA_SITE_KEY && (+ <div className="flex justify-center [&>div]:!w-full">+ <HCaptcha+ theme="dark"+ sitekey={envConfig.CAPTCHA_SITE_KEY}+ onVerify={(token) => setCaptchaToken(token)}+ onExpire={() => setCaptchaToken("")}+ ref={captchaRef}+ />+ </div>+ )}+ <Button+ type="submit"+ variant="project"+ size="lg"+ isFullWidth+ isPending={loading}+ isDisabled={requiresCaptcha && !captchaToken}+ >Continue</Button><Link