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(captcha): enhance captcha handling in email verification process
Victor Hugo dos Santosebec79b3ae3d
diff --git a/backend/src/services/auth/captcha-fns.test.ts b/backend/src/services/auth/captcha-fns.test.tsindex 8e03bc58b9..adc01537cf 100644--- a/backend/src/services/auth/captcha-fns.test.ts+++ b/backend/src/services/auth/captcha-fns.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import { BadRequestError } from "@app/lib/errors";-const getConfig = vi.fn<() => { CAPTCHA_SECRET?: string }>();+const getConfig = vi.fn<() => { CAPTCHA_SECRET?: string; CAPTCHA_SITE_KEY?: string }>();const postForm = vi.fn<(url: string, body: Record<string, unknown>) => Promise<{ data: { success: boolean } }>>();vi.mock("@app/lib/config/env", () => ({ getConfig: () => getConfig() }));@@ -14,6 +14,7 @@ vi.mock("@app/lib/config/request", () => ({import { verifyPublicEmailCaptcha } from "./captcha-fns";const SECRET = "test-captcha-secret";+const SITE_KEY = "test-captcha-site-key";const TOKEN = "10000000-aaaa-bbbb-cccc-000000000001";describe("verifyPublicEmailCaptcha", () => {@@ -22,17 +23,24 @@ describe("verifyPublicEmailCaptcha", () => {postForm.mockReset();});- // Self-hosted instances mostly never set a captcha secret. The gate has to disappear entirely+ // Self-hosted instances mostly never configure captcha. The gate has to disappear entirely// there rather than locking everyone out of signup and password reset.test.each([undefined, ""])("is inert when no secret is configured (%s)", async (secret) => {- getConfig.mockReturnValue({ CAPTCHA_SECRET: secret });+ getConfig.mockReturnValue({ CAPTCHA_SECRET: secret, CAPTCHA_SITE_KEY: SITE_KEY });await expect(verifyPublicEmailCaptcha(undefined)).resolves.toBeUndefined();expect(postForm).not.toHaveBeenCalled();});- test("demands a token on every attempt once a secret is configured", async () => {- getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET });+ test.each([undefined, ""])("is inert when no site key is configured (%s)", async (siteKey) => {+ getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET, CAPTCHA_SITE_KEY: siteKey });++ await expect(verifyPublicEmailCaptcha(undefined)).resolves.toBeUndefined();+ expect(postForm).not.toHaveBeenCalled();+ });++ test("demands a token on every attempt once captcha is configured", async () => {+ getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET, CAPTCHA_SITE_KEY: SITE_KEY });await expect(verifyPublicEmailCaptcha(undefined)).rejects.toBeInstanceOf(BadRequestError);// No token means no work and, critically, no email: the check must short-circuit.@@ -40,14 +48,14 @@ describe("verifyPublicEmailCaptcha", () => {});test("rejects a token the provider does not accept", async () => {- getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET });+ getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET, CAPTCHA_SITE_KEY: SITE_KEY });postForm.mockResolvedValue({ data: { success: false } });await expect(verifyPublicEmailCaptcha("forged-token")).rejects.toBeInstanceOf(BadRequestError);});test("accepts a token the provider verifies, and sends the secret with it", async () => {- getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET });+ getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET, CAPTCHA_SITE_KEY: SITE_KEY });postForm.mockResolvedValue({ data: { success: true } });await expect(verifyPublicEmailCaptcha(TOKEN)).resolves.toBeUndefined();@@ -59,7 +67,7 @@ describe("verifyPublicEmailCaptcha", () => {// A provider outage must not silently admit the request; failing closed is the whole point.test("does not admit the request when the provider call throws", async () => {- getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET });+ getConfig.mockReturnValue({ CAPTCHA_SECRET: SECRET, CAPTCHA_SITE_KEY: SITE_KEY });postForm.mockRejectedValue(new Error("hcaptcha unreachable"));await expect(verifyPublicEmailCaptcha(TOKEN)).rejects.toThrow();diff --git a/backend/src/services/auth/captcha-fns.ts b/backend/src/services/auth/captcha-fns.tsindex 636ac41983..1811eeed86 100644--- a/backend/src/services/auth/captcha-fns.ts+++ b/backend/src/services/auth/captcha-fns.ts@@ -32,7 +32,7 @@ export const verifyCaptcha = async (consecutiveFailedPasswordAttempts?: number |export const verifyPublicEmailCaptcha = async (captchaToken?: string) => {const appCfg = getConfig();- if (!appCfg.CAPTCHA_SECRET) return;+ if (!appCfg.CAPTCHA_SECRET || !appCfg.CAPTCHA_SITE_KEY) return;if (!captchaToken) {throw new BadRequestError({diff --git a/frontend/src/components/auth/CodeInputStep.tsx b/frontend/src/components/auth/CodeInputStep.tsxindex 7287babca1..736d9e56a5 100644--- a/frontend/src/components/auth/CodeInputStep.tsx+++ b/frontend/src/components/auth/CodeInputStep.tsx@@ -1,5 +1,6 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import HCaptcha from "@hcaptcha/react-hcaptcha";import axios from "axios";import {@@ -9,6 +10,7 @@ import {VerificationCodeHeader,VerificationCodeResend} from "@app/components/v3";+import { envConfig } from "@app/config/env";import { useSendVerificationEmail, useVerifySignupEmailVerificationCode } from "@app/hooks/api";import SecurityClient from "../utilities/SecurityClient";@@ -45,6 +47,10 @@ export default function CodeInputStep({const [isCompletingVerification, setIsCompletingVerification] = useState(false);const [verificationError, setVerificationError] = useState<unknown>();const [triesLeft, setTriesLeft] = useState(MAX_SIGNUP_VERIFICATION_ATTEMPTS);+ const [isCaptchaVisible, setIsCaptchaVisible] = useState(false);++ const captchaRef = useRef<HCaptcha>(null);+ const requiresCaptcha = Boolean(envConfig.CAPTCHA_SITE_KEY);const [, forceRender] = useState(0);@@ -90,13 +96,9 @@ export default function CodeInputStep({}};- const handleResend = async () => {- setVerificationError(undefined);- setTriesLeft(MAX_SIGNUP_VERIFICATION_ATTEMPTS);- resetVerificationCode();-+ const sendCode = async (captchaToken?: string) => {try {- const { cooldownSeconds } = await resendEmail({ email });+ const { cooldownSeconds } = await resendEmail({ email, captchaToken });onResendCooldownChange(Date.now() + cooldownSeconds * 1000);} catch (err) {if (axios.isAxiosError(err)) {@@ -105,7 +107,27 @@ export default function CodeInputStep({onResendCooldownChange(Date.now() + remaining * 1000);}}+ } finally {+ if (requiresCaptcha) {+ captchaRef.current?.resetCaptcha();+ setIsCaptchaVisible(false);+ }+ }+ };++ const handleResend = async () => {+ setVerificationError(undefined);+ setTriesLeft(MAX_SIGNUP_VERIFICATION_ATTEMPTS);+ resetVerificationCode();++ // The send only fires once hCaptcha hands back a token, so the widget is revealed here+ // rather than occupying the code screen for everyone who never resends.+ if (requiresCaptcha) {+ setIsCaptchaVisible(true);+ return;}++ await sendCode();};return (@@ -134,7 +156,21 @@ export default function CodeInputStep({isPending={isVerifying || isCompletingVerification}error={verificationError ? verificationErrorMessage : undefined}>+ {isCaptchaVisible && envConfig.CAPTCHA_SITE_KEY && (+ <div className="flex flex-col gap-2">+ <p className="text-sm text-label">Complete the captcha to resend your code.</p>+ <div className="flex justify-center [&>div]:!w-full">+ <HCaptcha+ theme="dark"+ sitekey={envConfig.CAPTCHA_SITE_KEY}+ onVerify={(token) => sendCode(token)}+ ref={captchaRef}+ />+ </div>+ </div>+ )}<VerificationCodeResend+ isDisabled={isCaptchaVisible}isResending={isResending}remainingSeconds={remainingCooldown}onResend={handleResend}diff --git a/frontend/src/components/auth/EnterEmailStep.tsx b/frontend/src/components/auth/EnterEmailStep.tsxdeleted file mode 100644index 9735e116f9..0000000000--- a/frontend/src/components/auth/EnterEmailStep.tsx+++ /dev/null@@ -1,100 +0,0 @@-import { useState } from "react";-import { useTranslation } from "react-i18next";-import { Link } from "@tanstack/react-router";-import { z } from "zod";--import { Button, CardContent, CardHeader, CardTitle, FieldError, Input } from "@app/components/v3";-import { useSendVerificationEmail } from "@app/hooks/api";--import { AuthPagePanel } from "./AuthPagePanel";--interface DownloadBackupPDFStepProps {- incrementStep: () => void;- email: string;- setEmail: (value: string) => void;-}--/**- * This is the first step of the sign up process - users need to enter their email- * @param {object} obj- * @param {string} obj.email - email of a user signing up- * @param {function} obj.setEmail - funciton that manages the state of the email variable- * @param {function} obj.incrementStep - function to go to the next step of the signup flow- * @returns- */-export default function EnterEmailStep({- email,- setEmail,- incrementStep-}: DownloadBackupPDFStepProps): JSX.Element {- const { mutateAsync, isPending } = useSendVerificationEmail();- const [emailError, setEmailError] = useState(false);- const { t } = useTranslation();-- /**- * Verifies if the entered email "looks" correct- */- const emailCheck = async () => {- const isValid = z.string().email().safeParse(email);-- let emailCheckBool = false;- if (!isValid.success) {- setEmailError(true);- emailCheckBool = true;- } else {- setEmailError(false);- }-- // If everything is correct, go to the next step- if (!emailCheckBool) {- await mutateAsync({ email: email.toLowerCase() });- setEmail(email.toLowerCase());- incrementStep();- }- };-- return (- <div className="mx-auto flex w-full flex-col items-center justify-center">- <AuthPagePanel>- <CardHeader className="mb-4 gap-4">- <CardTitle className="ml-0.5 bg-linear-to-b from-white to-bunker-200 bg-clip-text text-[1.65rem] font-medium text-transparent">- {t("signup.step1-start")}- </CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="flex w-full flex-col gap-2">- <Input- variant="outlined"- placeholder="Enter your email address..."- onChange={(e) => setEmail(e.target.value)}- value={email}- required- autoComplete="username"- className="h-10"- isError={emailError}- />- {emailError && <FieldError>Please enter a valid email.</FieldError>}- </div>- <Button- type="submit"- onClick={emailCheck}- variant="project"- size="lg"- isFullWidth- isDisabled={isPending}- isPending={isPending}- >- {String(t("signup.step1-submit"))}- </Button>- <div className="flex w-full justify-center text-xs text-label">- <Link to="/login">- <span className="cursor-pointer duration-200 hover:text-foreground hover:underline hover:decoration-project/45 hover:underline-offset-2">- {t("signup.already-have-account")}- </span>- </Link>- </div>- </CardContent>- </AuthPagePanel>- </div>- );-}