Skip to content

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

cooldown source of truth in backend

Thiago Araujo da Silva5e9f0fb76491
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index f5c2a3d8c4..ea7ceb3bfa 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -18,6 +18,7 @@ export const mockKeyStore = (): TKeyStoreFactory => {
return "OK";
},
setExpiry: async () => 0,
+ ttl: async () => -1,
setItemWithExpiry: async (key, value) => {
store[key] = value;
return "OK";
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 9d662d8fa7..dc90dbd809 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -110,8 +110,9 @@ 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}:hash` as const,
- EmailSignupOtpLock: (hash: string) => `email-signup-otp-lock:${hash}:lock` 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,
InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,
AdminConfig: "infisical-admin-cfg",
@@ -143,6 +144,7 @@ export const KeyStoreTtls = {
TelemetryIdentifyIdentityInSeconds: 86400, // 24 hours
RefreshTokenGraceInSeconds: 10,
EmailSignupOtpInSeconds: 300, // 5 minutes
+ EmailSignupResendCooldownInSeconds: 60, // 1 minute
InsightsCacheInSeconds: 300, // 5 minutes
AdminConfigInSeconds: 60,
InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation job
@@ -182,6 +184,7 @@ export type TKeyStoreFactory = {
getItem: (key: string, prefix?: string) => Promise<string | null>;
getItems: (keys: string[], prefix?: string) => Promise<(string | null)[]>;
setExpiry: (key: string, expiryInSeconds: number) => Promise<number>;
+ ttl: (key: string) => Promise<number>;
setItemWithExpiry: (
key: string,
expiryInSeconds: number | string,
@@ -324,6 +327,8 @@ export const keyStoreFactory = (
const setExpiry = async (key: string, expiryInSeconds: number) => primaryRedis.expire(key, expiryInSeconds);
+ const ttl = async (key: string) => primaryRedis.ttl(key);
+
const getKeysByPattern = async (pattern: string, limit?: number) => {
let cursor = "0";
const allKeys: string[] = [];
@@ -443,6 +448,7 @@ export const keyStoreFactory = (
setItem,
getItem,
setExpiry,
+ ttl,
setItemWithExpiry,
setItemWithExpiryNX,
deleteItem,
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index 55a09997c1..5b4458f613 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -19,6 +19,7 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
return "OK";
},
setExpiry: async () => 0,
+ ttl: async () => -1,
setItemWithExpiry: async (key, value) => {
store[key] = value;
return "OK";
diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.ts
index 21f5badc42..f2b3e3dd5e 100644
--- a/backend/src/server/routes/v3/signup-router.ts
+++ b/backend/src/server/routes/v3/signup-router.ts
@@ -27,7 +27,8 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- message: z.string()
+ message: z.string(),
+ cooldownSeconds: z.number()
})
}
},
@@ -50,8 +51,8 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
});
}
}
- await server.services.signup.beginEmailSignupProcess(email);
- return { message: `Sent an email verification code to ${email}` };
+ const { cooldownSeconds } = await server.services.signup.beginEmailSignupProcess(email);
+ return { message: `Sent an email verification code to ${email}`, cooldownSeconds };
}
});
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index b993b9b801..e343542707 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -26,7 +26,10 @@ type TAuthTokenServiceFactoryDep = {
userDAL: Pick<TUserDALFactory, "findById" | "transaction">;
orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership">;
membershipUserDAL: Pick<TMembershipUserDALFactory, "findOne">;
- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem" | "acquireLock">;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "setItemWithExpiry" | "getItem" | "deleteItem" | "acquireLock" | "deleteItemsByKeyIn" | "ttl"
+ >;
};
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
@@ -358,8 +361,20 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
return { user, tokenVersionId: token.tokenVersionId, orgId, orgName, rootOrgId, parentOrgId };
};
- const createEmailSignupToken = async (email: string): Promise<string> => {
+ const createEmailSignupToken = async (email: string): Promise<{ token: string; cooldownSeconds: number }> => {
const appCfg = getConfig();
+ const emailHash = computeHash(email, appCfg.AUTH_SECRET);
+
+ const cooldownKey = KeyStorePrefixes.EmailSignupResendCooldown(emailHash);
+ const hasCooldown = await keyStore.getItem(cooldownKey);
+ if (hasCooldown) {
+ const remaining = await keyStore.ttl(cooldownKey);
+ throw new BadRequestError({
+ message: "Please wait before requesting another code",
+ details: { cooldownSeconds: Math.max(1, remaining) }
+ });
+ }
+
const token = generateSixDigitToken();
const tokenHash = computeHash(token, appCfg.AUTH_SECRET);
const ttlSeconds = KeyStoreTtls.EmailSignupOtpInSeconds;
@@ -369,16 +384,20 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
expiresAt: Date.now() + ttlSeconds * 1000
};
- const emailHash = computeHash(email, appCfg.AUTH_SECRET);
- await keyStore.setItemWithExpiry(KeyStorePrefixes.EmailSignupOtp(emailHash), ttlSeconds, JSON.stringify(payload));
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.EmailSignupOtpHash(emailHash),
+ ttlSeconds,
+ JSON.stringify(payload)
+ );
+ await keyStore.setItemWithExpiry(cooldownKey, KeyStoreTtls.EmailSignupResendCooldownInSeconds, "1");
- return token;
+ return { token, cooldownSeconds: KeyStoreTtls.EmailSignupResendCooldownInSeconds };
};
const validateEmailSignupToken = async (email: string, code: string): Promise<void> => {
const appCfg = getConfig();
const emailHash = computeHash(email, appCfg.AUTH_SECRET);
- const key = KeyStorePrefixes.EmailSignupOtp(emailHash);
+ const key = KeyStorePrefixes.EmailSignupOtpHash(emailHash);
// Acquire a short-lived lock to make the tries-decrement / delete atomic.
const lock = await keyStore.acquireLock([KeyStorePrefixes.EmailSignupOtpLock(emailHash)], 5000);
@@ -395,12 +414,18 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
);
if (!parsed) {
- throw new Error("Invalid token");
+ throw new UnauthorizedError({
+ message: "Invalid token",
+ name: "InvalidToken"
+ });
}
if (Date.now() > parsed.expiresAt) {
await keyStore.deleteItem(key);
- throw new Error("Invalid token");
+ throw new UnauthorizedError({
+ message: "Invalid token",
+ name: "InvalidToken"
+ });
}
if (!isValidToken) {
@@ -415,10 +440,14 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
JSON.stringify({ ...parsed, triesLeft: remainingTries })
);
}
- throw new Error("Invalid token");
+ throw new UnauthorizedError({
+ message: "Invalid token",
+ name: "InvalidToken"
+ });
}
- await keyStore.deleteItem(key);
+ const cooldownKey = KeyStorePrefixes.EmailSignupResendCooldown(emailHash);
+ await keyStore.deleteItemsByKeyIn([key, cooldownKey]);
} finally {
await lock.release();
}
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index 63e2687b19..ee8a1c427b 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -1,4 +1,5 @@
import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";
+import { KeyStoreTtls } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
@@ -43,7 +44,7 @@ export const authSignupServiceFactory = ({
loginService
}: TAuthSignupDep) => {
// First step of signup to send OTP email
- const beginEmailSignupProcess = async (email: string) => {
+ const beginEmailSignupProcess = async (email: string): Promise<{ cooldownSeconds: number }> => {
const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
const isEmailInvalid = await isDisposableEmail(sanitizedEmail);
@@ -71,10 +72,10 @@ export const authSignupServiceFactory = ({
.catch((err) =>
logger.error(err, "Failed to send existing account email — swallowing to prevent user enumeration")
);
- return;
+ return { cooldownSeconds: KeyStoreTtls.EmailSignupResendCooldownInSeconds };
}
- const token = await tokenService.createEmailSignupToken(sanitizedEmail);
+ const { token, cooldownSeconds } = await tokenService.createEmailSignupToken(sanitizedEmail);
await smtpService
.sendMail({
@@ -86,6 +87,8 @@ export const authSignupServiceFactory = ({
}
})
.catch((err) => throwIfSmtpError(err, "Failed to send signup verification email"));
+
+ return { cooldownSeconds };
};
const verifyEmailSignup = async (email: string, code: string) => {
diff --git a/frontend/src/components/auth/CodeInputStep.tsx b/frontend/src/components/auth/CodeInputStep.tsx
index 5352e2bc24..5b04f9ba4c 100644
--- a/frontend/src/components/auth/CodeInputStep.tsx
+++ b/frontend/src/components/auth/CodeInputStep.tsx
@@ -1,8 +1,9 @@
/* eslint-disable react/jsx-props-no-spreading */
-import { useState } from "react";
+import { useEffect, useState } from "react";
import ReactCodeInput from "react-code-input";
import { useTranslation } from "react-i18next";
import { Link } from "@tanstack/react-router";
+import axios from "axios";
import { Button, Card, CardContent, CardHeader, CardTitle, FieldError } from "@app/components/v3";
import { useSendVerificationEmail, useVerifySignupEmailVerificationCode } from "@app/hooks/api";
@@ -50,9 +51,14 @@ const codeInputStylePhone = {
interface CodeInputStepProps {
email: string;
onComplete: () => void;
+ initialCooldown: number;
}
-export default function CodeInputStep({ email, onComplete }: CodeInputStepProps): JSX.Element {
+export default function CodeInputStep({
+ email,
+ onComplete,
+ initialCooldown
+}: CodeInputStepProps): JSX.Element {
const { mutateAsync: resendEmail, isPending: isResending } = useSendVerificationEmail();
const {
mutateAsync: verifyCode,
@@ -60,14 +66,39 @@ export default function CodeInputStep({ email, onComplete }: CodeInputStepProps)
isError: isCodeError
} = useVerifySignupEmailVerificationCode();
const [code, setCode] = useState("");
+ const [cooldown, setCooldown] = useState(initialCooldown);
const { t } = useTranslation();
+ useEffect(() => {
+ if (cooldown <= 0) return undefined;
+ const timer = setInterval(() => setCooldown((s) => s - 1), 1000);
+ return () => clearInterval(timer);
+ }, [cooldown]);
+
const handleVerify = async () => {
const { token } = await verifyCode({ email, code });
SecurityClient.setSignupToken(token);
onComplete();
};
+ const handleResend = async () => {
+ try {
+ const { cooldownSeconds } = await resendEmail({ email });
+ setCooldown(cooldownSeconds);
+ } catch (err) {
+ if (axios.isAxiosError(err)) {
+ const remaining = err.response?.data?.details?.cooldownSeconds;
+ if (typeof remaining === "number") {
+ setCooldown(remaining);
+ }
+ }
+ }
+ };
+
+ let resendLabel = t("signup.step2-resend-submit");
+ if (isResending) resendLabel = t("signup.step2-resend-progress");
+ else if (cooldown > 0) resendLabel = `${t("signup.step2-resend-submit")} (${cooldown}s)`;
+
return (
<div className="mx-auto flex w-full flex-col items-center justify-center">
<Card className="mx-auto w-full max-w-md items-stretch gap-0 p-6">
@@ -116,12 +147,15 @@ export default function CodeInputStep({ email, onComplete }: CodeInputStepProps)
</div>
<div className="mt-6 flex flex-col items-center gap-2 text-xs text-label">
<div className="flex flex-row items-baseline gap-1">
- <button disabled={isResending} onClick={() => resendEmail({ email })} type="button">
- <span className="cursor-pointer duration-200 hover:text-foreground hover:underline hover:decoration-project/45 hover:underline-offset-2">
- {t("signup.step2-resend-alert")}{" "}
- {isResending
- ? t("signup.step2-resend-progress")
- : t("signup.step2-resend-submit")}
+ <button disabled={isResending || cooldown > 0} onClick={handleResend} type="button">
+ <span
+ className={
+ cooldown > 0
+ ? "text-label/60"
+ : "cursor-pointer duration-200 hover:text-foreground hover:underline hover:decoration-project/45 hover:underline-offset-2"
+ }
+ >
+ {t("signup.step2-resend-alert")} {resendLabel}
</span>
</button>
</div>
diff --git a/frontend/src/components/auth/InitialSignupStep.tsx b/frontend/src/components/auth/InitialSignupStep.tsx
index f2b7c3375a..39ed6a0ec1 100644
--- a/frontend/src/components/auth/InitialSignupStep.tsx
+++ b/frontend/src/components/auth/InitialSignupStep.tsx
@@ -29,7 +29,7 @@ interface InitialSignupStepProps {
email: string;
setEmail: (value: string) => void;
- incrementStep: () => void;
+ incrementStep: (cooldownSeconds: number) => void;
}
export default function InitialSignupStep({
@@ -54,9 +54,9 @@ export default function InitialSignupStep({
}
setEmailError(false);
- await mutateAsync({ email: email.toLowerCase() });
+ const { cooldownSeconds } = await mutateAsync({ email: email.toLowerCase() });
setEmail(email.toLowerCase());
- incrementStep();
+ incrementStep(cooldownSeconds);
};
const handleSocialSignup = (method: LoginMethod) => {
diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsx
index 3e906f0e35..95e1ab5646 100644
--- a/frontend/src/hooks/api/auth/queries.tsx
+++ b/frontend/src/hooks/api/auth/queries.tsx
@@ -202,9 +202,10 @@ export const verifySignupInvite = async (details: VerifySignupInviteDTO) => {
export const useSendVerificationEmail = () => {
return useMutation({
mutationFn: async ({ email }: { email: string }) => {
- const { data } = await apiRequest.post("/api/v3/signup/email/signup", {
- email
- });
+ const { data } = await apiRequest.post<{ message: string; cooldownSeconds: number }>(
+ "/api/v3/signup/email/signup",
+ { email }
+ );
return data;
}
diff --git a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
index 12176ffc01..d48b280daf 100644
--- a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
+++ b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
@@ -33,6 +33,7 @@ export interface SignUpPageProps {
export const SignUpPage = ({ invite }: SignUpPageProps) => {
const isInvite = Boolean(invite);
const [email, setEmail] = useState(invite?.email ?? "");
+ const [resendCooldownSeconds, setResendCooldownSeconds] = useState(0);
const [section, setSection] = useState<SignupSection>(
isInvite ? SignupSection.UserInfo : SignupSection.Email
);
@@ -51,7 +52,8 @@ export const SignUpPage = ({ invite }: SignUpPageProps) => {
}
}, [config.allowSignUp]);
- const handleEmailComplete = () => {
+ const handleEmailComplete = (cooldownSeconds: number) => {
+ setResendCooldownSeconds(cooldownSeconds);
if (serverDetails?.emailConfigured) {
setSection(SignupSection.VerifyCode);
} else {
@@ -95,7 +97,13 @@ export const SignUpPage = ({ invite }: SignUpPageProps) => {
/>
);
case SignupSection.VerifyCode:
- return <CodeInputStep email={email} onComplete={handleCodeVerified} />;
+ return (
+ <CodeInputStep
+ email={email}
+ onComplete={handleCodeVerified}
+ initialCooldown={resendCooldownSeconds}
+ />
+ );
case SignupSection.UserInfo:
return (
<UserInfoStep onComplete={handleUserInfoComplete} email={email} isInvite={isInvite} />