AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): Add captcha to login, signup and password reset pages (#9847)
Bently104928c6140b
diff --git a/autogpt_platform/backend/.env.example b/autogpt_platform/backend/.env.exampleindex 386f80a711..60d941b839 100644--- a/autogpt_platform/backend/.env.example+++ b/autogpt_platform/backend/.env.example@@ -66,6 +66,13 @@ MEDIA_GCS_BUCKET_NAME=## and tunnel it to your locally running backend.PLATFORM_BASE_URL=http://localhost:3000+## Cloudflare Turnstile (CAPTCHA) Configuration+## Get these from the Cloudflare Turnstile dashboard: https://dash.cloudflare.com/?to=/:account/turnstile+## This is the backend secret key+TURNSTILE_SECRET_KEY=+## This is the verify URL+TURNSTILE_VERIFY_URL=https://challenges.cloudflare.com/turnstile/v0/siteverify+## == INTEGRATION CREDENTIALS == ### Each set of server side credentials is required for the corresponding 3rd party# integration to work.diff --git a/autogpt_platform/backend/backend/server/rest_api.py b/autogpt_platform/backend/backend/server/rest_api.pyindex 1dabe48bd1..33ccf0f9b5 100644--- a/autogpt_platform/backend/backend/server/rest_api.py+++ b/autogpt_platform/backend/backend/server/rest_api.py@@ -27,6 +27,7 @@ import backend.server.v2.library.routesimport backend.server.v2.otto.routesimport backend.server.v2.store.modelimport backend.server.v2.store.routes+import backend.server.v2.turnstile.routesimport backend.util.serviceimport backend.util.settingsfrom backend.blocks.llm import LlmModel@@ -119,6 +120,9 @@ app.include_router(app.include_router(backend.server.v2.otto.routes.router, tags=["v2"], prefix="/api/otto")+app.include_router(+ backend.server.v2.turnstile.routes.router, tags=["v2"], prefix="/api/turnstile"+)app.include_router(backend.server.routers.postmark.postmark.router,diff --git a/autogpt_platform/backend/backend/server/v2/turnstile/__init__.py b/autogpt_platform/backend/backend/server/v2/turnstile/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/server/v2/turnstile/models.py b/autogpt_platform/backend/backend/server/v2/turnstile/models.pynew file mode 100644index 0000000000..9410b89511--- /dev/null+++ b/autogpt_platform/backend/backend/server/v2/turnstile/models.py@@ -0,0 +1,30 @@+from typing import Optional++from pydantic import BaseModel, Field+++class TurnstileVerifyRequest(BaseModel):+ """Request model for verifying a Turnstile token."""++ token: str = Field(description="The Turnstile token to verify")+ action: Optional[str] = Field(+ default=None, description="The action that the user is attempting to perform"+ )+++class TurnstileVerifyResponse(BaseModel):+ """Response model for the Turnstile verification endpoint."""++ success: bool = Field(description="Whether the token verification was successful")+ error: Optional[str] = Field(+ default=None, description="Error message if verification failed"+ )+ challenge_timestamp: Optional[str] = Field(+ default=None, description="Timestamp of the challenge (ISO format)"+ )+ hostname: Optional[str] = Field(+ default=None, description="Hostname of the site where the challenge was solved"+ )+ action: Optional[str] = Field(+ default=None, description="The action associated with this verification"+ )diff --git a/autogpt_platform/backend/backend/server/v2/turnstile/routes.py b/autogpt_platform/backend/backend/server/v2/turnstile/routes.pynew file mode 100644index 0000000000..d0b2b38163--- /dev/null+++ b/autogpt_platform/backend/backend/server/v2/turnstile/routes.py@@ -0,0 +1,108 @@+import logging++import aiohttp+from fastapi import APIRouter++from backend.util.settings import Settings++from .models import TurnstileVerifyRequest, TurnstileVerifyResponse++logger = logging.getLogger(__name__)++router = APIRouter()+settings = Settings()++[email protected]("/verify", response_model=TurnstileVerifyResponse)+async def verify_turnstile_token(+ request: TurnstileVerifyRequest,+) -> TurnstileVerifyResponse:+ """+ Verify a Cloudflare Turnstile token.+ This endpoint verifies a token returned by the Cloudflare Turnstile challenge+ on the client side. It returns whether the verification was successful.+ """+ logger.info(f"Verifying Turnstile token for action: {request.action}")+ return await verify_token(request)+++async def verify_token(request: TurnstileVerifyRequest) -> TurnstileVerifyResponse:+ """+ Verify a Cloudflare Turnstile token by making a request to the Cloudflare API.+ """+ # Get the secret key from settings+ turnstile_secret_key = settings.secrets.turnstile_secret_key+ turnstile_verify_url = settings.secrets.turnstile_verify_url++ if not turnstile_secret_key:+ logger.error("Turnstile secret key is not configured")+ return TurnstileVerifyResponse(+ success=False,+ error="CONFIGURATION_ERROR",+ challenge_timestamp=None,+ hostname=None,+ action=None,+ )++ try:+ async with aiohttp.ClientSession() as session:+ payload = {+ "secret": turnstile_secret_key,+ "response": request.token,+ }++ if request.action:+ payload["action"] = request.action++ logger.debug(f"Verifying Turnstile token with action: {request.action}")++ async with session.post(+ turnstile_verify_url,+ data=payload,+ timeout=aiohttp.ClientTimeout(total=10),+ ) as response:+ if response.status != 200:+ error_text = await response.text()+ logger.error(f"Turnstile API error: {error_text}")+ return TurnstileVerifyResponse(+ success=False,+ error=f"API_ERROR: {response.status}",+ challenge_timestamp=None,+ hostname=None,+ action=None,+ )++ data = await response.json()+ logger.debug(f"Turnstile API response: {data}")++ # Parse the response and return a structured object+ return TurnstileVerifyResponse(+ success=data.get("success", False),+ error=(+ data.get("error-codes", None)[0]+ if data.get("error-codes")+ else None+ ),+ challenge_timestamp=data.get("challenge_timestamp"),+ hostname=data.get("hostname"),+ action=data.get("action"),+ )++ except aiohttp.ClientError as e:+ logger.error(f"Connection error to Turnstile API: {str(e)}")+ return TurnstileVerifyResponse(+ success=False,+ error=f"CONNECTION_ERROR: {str(e)}",+ challenge_timestamp=None,+ hostname=None,+ action=None,+ )+ except Exception as e:+ logger.error(f"Unexpected error in Turnstile verification: {str(e)}")+ return TurnstileVerifyResponse(+ success=False,+ error=f"UNEXPECTED_ERROR: {str(e)}",+ challenge_timestamp=None,+ hostname=None,+ action=None,+ )diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex e80e21874f..31bae11fbc 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -350,6 +350,16 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):description="The secret key to use for the unsubscribe user by token",)+ # Cloudflare Turnstile credentials+ turnstile_secret_key: str = Field(+ default="",+ description="Cloudflare Turnstile backend secret key",+ )+ turnstile_verify_url: str = Field(+ default="https://challenges.cloudflare.com/turnstile/v0/siteverify",+ description="Cloudflare Turnstile verify URL",+ )+# OAuth server credentials for integrations# --8<-- [start:OAuthServerCredentialsExample]github_client_id: str = Field(default="", description="GitHub OAuth client ID")diff --git a/autogpt_platform/frontend/.env.example b/autogpt_platform/frontend/.env.exampleindex 3bf277d87b..0eb8872371 100644--- a/autogpt_platform/frontend/.env.example+++ b/autogpt_platform/frontend/.env.example@@ -25,3 +25,8 @@ GA_MEASUREMENT_ID=G-FH2XK2W4GN# When running locally, set NEXT_PUBLIC_BEHAVE_AS=CLOUD to use the a locally hosted marketplace (as is typical in development, and the cloud deployment), otherwise set it to LOCAL to have the marketplace open in a new tabNEXT_PUBLIC_BEHAVE_AS=LOCALNEXT_PUBLIC_SHOW_BILLING_PAGE=false++## Cloudflare Turnstile (CAPTCHA) Configuration+## Get these from the Cloudflare Turnstile dashboard: https://dash.cloudflare.com/?to=/:account/turnstile+## This is the frontend site key+NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY=diff --git a/autogpt_platform/frontend/src/app/(platform)/login/actions.ts b/autogpt_platform/frontend/src/app/(platform)/login/actions.tsindex 635f85fc12..cd3ca3e750 100644--- a/autogpt_platform/frontend/src/app/(platform)/login/actions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/login/actions.ts@@ -6,6 +6,7 @@ import * as Sentry from "@sentry/nextjs";import getServerSupabase from "@/lib/supabase/getServerSupabase";import BackendAPI from "@/lib/autogpt-server-api";import { loginFormSchema, LoginProvider } from "@/types/auth";+import { verifyTurnstileToken } from "@/lib/turnstile";export async function logout() {return await Sentry.withServerActionInstrumentation(@@ -39,7 +40,10 @@ async function shouldShowOnboarding() {);}-export async function login(values: z.infer<typeof loginFormSchema>) {+export async function login(+ values: z.infer<typeof loginFormSchema>,+ turnstileToken: string,+) {return await Sentry.withServerActionInstrumentation("login", {}, async () => {const supabase = getServerSupabase();const api = new BackendAPI();@@ -48,6 +52,12 @@ export async function login(values: z.infer<typeof loginFormSchema>) {redirect("/error");}+ // Verify Turnstile token if provided+ const success = await verifyTurnstileToken(turnstileToken, "login");+ if (!success) {+ return "CAPTCHA verification failed. Please try again.";+ }+// We are sure that the values are of the correct type because zod validates the formconst { data, error } = await supabase.auth.signInWithPassword(values);diff --git a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx b/autogpt_platform/frontend/src/app/(platform)/login/page.tsxindex 629854c4d5..6027c26b6d 100644--- a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/login/page.tsx@@ -24,9 +24,11 @@ import {AuthFeedback,AuthBottomText,PasswordInput,+ Turnstile,} from "@/components/auth";import { loginFormSchema } from "@/types/auth";import { getBehaveAs } from "@/lib/utils";+import { useTurnstile } from "@/hooks/useTurnstile";export default function LoginPage() {const { supabase, user, isUserLoading } = useSupabase();@@ -34,6 +36,12 @@ export default function LoginPage() {const router = useRouter();const [isLoading, setIsLoading] = useState(false);+ const turnstile = useTurnstile({+ action: "login",+ autoVerify: false,+ resetOnError: true,+ });+const form = useForm<z.infer<typeof loginFormSchema>>({resolver: zodResolver(loginFormSchema),defaultValues: {@@ -65,15 +73,23 @@ export default function LoginPage() {return;}- const error = await login(data);+ if (!turnstile.verified) {+ setFeedback("Please complete the CAPTCHA challenge.");+ setIsLoading(false);+ return;+ }++ const error = await login(data, turnstile.token as string);setIsLoading(false);if (error) {setFeedback(error);+ // Always reset the turnstile on any error+ turnstile.reset();return;}setFeedback(null);},- [form],+ [form, turnstile],);if (user) {@@ -140,6 +156,17 @@ export default function LoginPage() {</FormItem>)}/>++ {/* Turnstile CAPTCHA Component */}+ <Turnstile+ siteKey={turnstile.siteKey}+ onVerify={turnstile.handleVerify}+ onExpire={turnstile.handleExpire}+ onError={turnstile.handleError}+ action="login"+ shouldRender={turnstile.shouldRender}+ />+<AuthButtononClick={() => onLogin(form.getValues())}isLoading={isLoading}diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts b/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.tsindex 496667035a..2fd1ac1567 100644--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts@@ -3,8 +3,9 @@ import getServerSupabase from "@/lib/supabase/getServerSupabase";import { redirect } from "next/navigation";import * as Sentry from "@sentry/nextjs";import { headers } from "next/headers";+import { verifyTurnstileToken } from "@/lib/turnstile";-export async function sendResetEmail(email: string) {+export async function sendResetEmail(email: string, turnstileToken: string) {return await Sentry.withServerActionInstrumentation("sendResetEmail",{},@@ -20,6 +21,15 @@ export async function sendResetEmail(email: string) {redirect("/error");}+ // Verify Turnstile token if provided+ const success = await verifyTurnstileToken(+ turnstileToken,+ "reset_password",+ );+ if (!success) {+ return "CAPTCHA verification failed. Please try again.";+ }+const { error } = await supabase.auth.resetPasswordForEmail(email, {redirectTo: `${origin}/reset_password`,});@@ -34,7 +44,7 @@ export async function sendResetEmail(email: string) {);}-export async function changePassword(password: string) {+export async function changePassword(password: string, turnstileToken: string) {return await Sentry.withServerActionInstrumentation("changePassword",{},@@ -45,6 +55,15 @@ export async function changePassword(password: string) {redirect("/error");}+ // Verify Turnstile token if provided+ const success = await verifyTurnstileToken(+ turnstileToken,+ "change_password",+ );+ if (!success) {+ return "CAPTCHA verification failed. Please try again.";+ }+const { error } = await supabase.auth.updateUser({ password });if (error) {diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx b/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsxindex 3c78718a72..4b3d33208e 100644--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx@@ -5,6 +5,7 @@ import {AuthButton,AuthFeedback,PasswordInput,+ Turnstile,} from "@/components/auth";import {Form,@@ -25,6 +26,7 @@ import { z } from "zod";import { changePassword, sendResetEmail } from "./actions";import Spinner from "@/components/Spinner";import { getBehaveAs } from "@/lib/utils";+import { useTurnstile } from "@/hooks/useTurnstile";export default function ResetPasswordPage() {const { supabase, user, isUserLoading } = useSupabase();@@ -33,6 +35,18 @@ export default function ResetPasswordPage() {const [isError, setIsError] = useState(false);const [disabled, setDisabled] = useState(false);+ const sendEmailTurnstile = useTurnstile({+ action: "reset_password",+ autoVerify: false,+ resetOnError: true,+ });++ const changePasswordTurnstile = useTurnstile({+ action: "change_password",+ autoVerify: false,+ resetOnError: true,+ });+const sendEmailForm = useForm<z.infer<typeof sendEmailFormSchema>>({resolver: zodResolver(sendEmailFormSchema),defaultValues: {@@ -58,11 +72,22 @@ export default function ResetPasswordPage() {return;}- const error = await sendResetEmail(data.email);+ if (!sendEmailTurnstile.verified) {+ setFeedback("Please complete the CAPTCHA challenge.");+ setIsError(true);+ setIsLoading(false);+ return;+ }++ const error = await sendResetEmail(+ data.email,+ sendEmailTurnstile.token as string,+ );setIsLoading(false);if (error) {setFeedback(error);setIsError(true);+ sendEmailTurnstile.reset();return;}setDisabled(true);@@ -71,7 +96,7 @@ export default function ResetPasswordPage() {);setIsError(false);},- [sendEmailForm],+ [sendEmailForm, sendEmailTurnstile],);const onChangePassword = useCallback(@@ -84,17 +109,28 @@ export default function ResetPasswordPage() {return;}- const error = await changePassword(data.password);+ if (!changePasswordTurnstile.verified) {+ setFeedback("Please complete the CAPTCHA challenge.");+ setIsError(true);+ setIsLoading(false);+ return;+ }++ const error = await changePassword(+ data.password,+ changePasswordTurnstile.token as string,+ );setIsLoading(false);if (error) {setFeedback(error);setIsError(true);+ changePasswordTurnstile.reset();return;}setFeedback("Password changed successfully. Redirecting to login.");setIsError(false);},- [changePasswordForm],+ [changePasswordForm, changePasswordTurnstile],);if (isUserLoading) {@@ -145,6 +181,17 @@ export default function ResetPasswordPage() {</FormItem>)}/>++ {/* Turnstile CAPTCHA Component for password change */}+ <Turnstile+ siteKey={changePasswordTurnstile.siteKey}+ onVerify={changePasswordTurnstile.handleVerify}+ onExpire={changePasswordTurnstile.handleExpire}+ onError={changePasswordTurnstile.handleError}+ action="change_password"+ shouldRender={changePasswordTurnstile.shouldRender}+ />+<AuthButtononClick={() => onChangePassword(changePasswordForm.getValues())}isLoading={isLoading}@@ -175,6 +222,17 @@ export default function ResetPasswordPage() {</FormItem>)}/>++ {/* Turnstile CAPTCHA Component for reset email */}+ <Turnstile+ siteKey={sendEmailTurnstile.siteKey}+ onVerify={sendEmailTurnstile.handleVerify}+ onExpire={sendEmailTurnstile.handleExpire}+ onError={sendEmailTurnstile.handleError}+ action="reset_password"+ shouldRender={sendEmailTurnstile.shouldRender}+ />+<AuthButtononClick={() => onSendEmail(sendEmailForm.getValues())}isLoading={isLoading}diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts b/autogpt_platform/frontend/src/app/(platform)/signup/actions.tsindex cdf1974772..9d9ac98947 100644--- a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts@@ -6,8 +6,12 @@ import * as Sentry from "@sentry/nextjs";import getServerSupabase from "@/lib/supabase/getServerSupabase";import { signupFormSchema } from "@/types/auth";import BackendAPI from "@/lib/autogpt-server-api";+import { verifyTurnstileToken } from "@/lib/turnstile";-export async function signup(values: z.infer<typeof signupFormSchema>) {+export async function signup(+ values: z.infer<typeof signupFormSchema>,+ turnstileToken: string,+) {"use server";return await Sentry.withServerActionInstrumentation("signup",@@ -19,6 +23,12 @@ export async function signup(values: z.infer<typeof signupFormSchema>) {redirect("/error");}+ // Verify Turnstile token if provided+ const success = await verifyTurnstileToken(turnstileToken, "signup");+ if (!success) {+ return "CAPTCHA verification failed. Please try again.";+ }+// We are sure that the values are of the correct type because zod validates the formconst { data, error } = await supabase.auth.signUp(values);diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx b/autogpt_platform/frontend/src/app/(platform)/signup/page.tsxindex 10b59b5c9f..02fe8d684f 100644--- a/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx@@ -25,10 +25,12 @@ import {AuthButton,AuthBottomText,PasswordInput,+ Turnstile,} from "@/components/auth";import AuthFeedback from "@/components/auth/AuthFeedback";import { signupFormSchema } from "@/types/auth";import { getBehaveAs } from "@/lib/utils";+import { useTurnstile } from "@/hooks/useTurnstile";export default function SignupPage() {const { supabase, user, isUserLoading } = useSupabase();@@ -37,6 +39,12 @@ export default function SignupPage() {const [isLoading, setIsLoading] = useState(false);//TODO: Remove after closed beta+ const turnstile = useTurnstile({+ action: "signup",+ autoVerify: false,+ resetOnError: true,+ });+const form = useForm<z.infer<typeof signupFormSchema>>({resolver: zodResolver(signupFormSchema),defaultValues: {@@ -56,20 +64,28 @@ export default function SignupPage() {return;}- const error = await signup(data);+ if (!turnstile.verified) {+ setFeedback("Please complete the CAPTCHA challenge.");+ setIsLoading(false);+ return;+ }++ const error = await signup(data, turnstile.token as string);setIsLoading(false);if (error) {if (error === "user_already_exists") {setFeedback("User with this email already exists");+ turnstile.reset();return;} else {setFeedback(error);+ turnstile.reset();}return;}setFeedback(null);},- [form],+ [form, turnstile],);if (user) {@@ -141,6 +157,17 @@ export default function SignupPage() {</FormItem>)}/>++ {/* Turnstile CAPTCHA Component */}+ <Turnstile+ siteKey={turnstile.siteKey}+ onVerify={turnstile.handleVerify}+ onExpire={turnstile.handleExpire}+ onError={turnstile.handleError}+ action="signup"+ shouldRender={turnstile.shouldRender}+ />+<AuthButtononClick={() => onSignup(form.getValues())}isLoading={isLoading}diff --git a/autogpt_platform/frontend/src/components/auth/Turnstile.tsx b/autogpt_platform/frontend/src/components/auth/Turnstile.tsxnew file mode 100644index 0000000000..018406a7f6--- /dev/null+++ b/autogpt_platform/frontend/src/components/auth/Turnstile.tsx@@ -0,0 +1,140 @@+"use client";+import { useCallback, useEffect, useRef, useState } from "react";+import { cn } from "@/lib/utils";++export interface TurnstileProps {+ siteKey: string;+ onVerify: (token: string) => void;+ onExpire?: () => void;+ onError?: (error: Error) => void;+ action?: string;+ className?: string;+ id?: string;+ shouldRender?: boolean;+}++export function Turnstile({+ siteKey,+ onVerify,+ onExpire,+ onError,+ action,+ className,+ id = "cf-turnstile",+ shouldRender = true,+}: TurnstileProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const widgetIdRef = useRef<string | null>(null);+ const [loaded, setLoaded] = useState(false);++ // Load the Turnstile script+ useEffect(() => {+ if (typeof window === "undefined" || !shouldRender) return;++ // Skip if already loaded+ if (window.turnstile) {+ setLoaded(true);+ return;+ }++ // Create script element+ const script = document.createElement("script");+ script.src =+ "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";+ script.async = true;+ script.defer = true;++ script.onload = () => {+ setLoaded(true);+ };++ script.onerror = () => {+ onError?.(new Error("Failed to load Turnstile script"));+ };++ document.head.appendChild(script);++ return () => {+ if (document.head.contains(script)) {+ document.head.removeChild(script);+ }+ };+ }, [onError, shouldRender]);++ // Initialize and render the widget when script is loaded+ useEffect(() => {+ if (!loaded || !containerRef.current || !window.turnstile || !shouldRender)+ return;++ // Reset any existing widget+ if (widgetIdRef.current && window.turnstile) {+ window.turnstile.reset(widgetIdRef.current);+ }++ // Render a new widget+ if (window.turnstile) {+ widgetIdRef.current = window.turnstile.render(containerRef.current, {+ sitekey: siteKey,+ callback: (token: string) => {+ onVerify(token);+ },+ "expired-callback": () => {+ onExpire?.();+ },+ "error-callback": () => {+ onError?.(new Error("Turnstile widget encountered an error"));+ },+ action,+ });+ }++ return () => {+ if (widgetIdRef.current && window.turnstile) {+ window.turnstile.remove(widgetIdRef.current);+ widgetIdRef.current = null;+ }+ };+ }, [loaded, siteKey, onVerify, onExpire, onError, action, shouldRender]);++ // Method to reset the widget manually+ const reset = useCallback(() => {+ if (loaded && widgetIdRef.current && window.turnstile && shouldRender) {+ window.turnstile.reset(widgetIdRef.current);+ }+ }, [loaded, shouldRender]);++ // If shouldRender is false, don't render anything+ if (!shouldRender) {+ return null;+ }++ return (+ <div+ id={id}+ ref={containerRef}+ className={cn("my-4 flex items-center justify-center", className)}+ />+ );+}++// Add TypeScript interface to Window to include turnstile property+declare global {+ interface Window {+ turnstile?: {+ render: (+ container: HTMLElement,+ options: {+ sitekey: string;+ callback: (token: string) => void;+ "expired-callback"?: () => void;+ "error-callback"?: () => void;+ action?: string;+ },+ ) => string;+ reset: (widgetId: string) => void;+ remove: (widgetId: string) => void;+ };+ }+}++export default Turnstile;diff --git a/autogpt_platform/frontend/src/components/auth/index.ts b/autogpt_platform/frontend/src/components/auth/index.tsindex 348b6997ff..e4d3dc2b96 100644--- a/autogpt_platform/frontend/src/components/auth/index.ts+++ b/autogpt_platform/frontend/src/components/auth/index.ts@@ -4,6 +4,7 @@ import AuthCard from "./AuthCard";import AuthFeedback from "./AuthFeedback";import AuthHeader from "./AuthHeader";import { PasswordInput } from "./PasswordInput";+import Turnstile from "./Turnstile";export {AuthBottomText,@@ -12,4 +13,5 @@ export {AuthFeedback,AuthHeader,PasswordInput,+ Turnstile,};diff --git a/autogpt_platform/frontend/src/hooks/useTurnstile.ts b/autogpt_platform/frontend/src/hooks/useTurnstile.tsnew file mode 100644index 0000000000..29f93fbf8e--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useTurnstile.ts@@ -0,0 +1,169 @@+import { useState, useCallback, useEffect } from "react";+import { verifyTurnstileToken } from "@/lib/turnstile";+import { BehaveAs, getBehaveAs } from "@/lib/utils";++interface UseTurnstileOptions {+ action?: string;+ autoVerify?: boolean;+ onSuccess?: () => void;+ onError?: (error: Error) => void;+ resetOnError?: boolean;+}++interface UseTurnstileResult {+ token: string | null;+ verifying: boolean;+ verified: boolean;+ error: Error | null;+ handleVerify: (token: string) => Promise<boolean>;+ handleExpire: () => void;+ handleError: (error: Error) => void;+ reset: () => void;+ siteKey: string;+ shouldRender: boolean;+}++const TURNSTILE_SITE_KEY =+ process.env.NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY || "";++/**+ * Custom hook for managing Turnstile state in forms+ */+export function useTurnstile({+ action,+ autoVerify = true,+ onSuccess,+ onError,+ resetOnError = false,+}: UseTurnstileOptions = {}): UseTurnstileResult {+ const [token, setToken] = useState<string | null>(null);+ const [verifying, setVerifying] = useState(false);+ const [verified, setVerified] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [shouldRender, setShouldRender] = useState(false);+ const [widgetId, setWidgetId] = useState<string | null>(null);++ useEffect(() => {+ const behaveAs = getBehaveAs();+ const hasTurnstileKey = !!TURNSTILE_SITE_KEY;++ setShouldRender(behaveAs === BehaveAs.CLOUD && hasTurnstileKey);++ if (behaveAs !== BehaveAs.CLOUD || !hasTurnstileKey) {+ setVerified(true);+ }+ }, []);++ useEffect(() => {+ if (token && !autoVerify && shouldRender) {+ setVerified(true);+ }+ }, [token, autoVerify, shouldRender]);++ useEffect(() => {+ if (typeof window !== "undefined" && window.turnstile) {+ const originalRender = window.turnstile.render;+ window.turnstile.render = (container, options) => {+ const id = originalRender(container, options);+ setWidgetId(id);+ return id;+ };+ }+ }, []);++ const reset = useCallback(() => {+ if (shouldRender && window.turnstile && widgetId) {+ window.turnstile.reset(widgetId);++ // Always reset the state when reset is called+ setToken(null);+ setVerified(false);+ setVerifying(false);+ setError(null);+ }+ }, [shouldRender, widgetId]);++ const handleVerify = useCallback(+ async (newToken: string) => {+ if (!shouldRender) {+ return true;+ }++ setToken(newToken);+ setError(null);++ if (autoVerify) {+ setVerifying(true);++ try {+ const success = await verifyTurnstileToken(newToken, action);+ setVerified(success);++ if (success && onSuccess) {+ onSuccess();+ } else if (!success) {+ const newError = new Error("Turnstile verification failed");+ setError(newError);+ if (onError) onError(newError);+ if (resetOnError) {+ setVerified(false);+ }+ }++ setVerifying(false);+ return success;+ } catch (err) {+ const newError =+ err instanceof Error+ ? err+ : new Error("Unknown error during verification");+ setError(newError);+ if (resetOnError) {+ setVerified(false);+ }+ setVerifying(false);+ if (onError) onError(newError);+ return false;+ }+ } else {+ setVerified(true);+ }++ return true;+ },+ [action, autoVerify, onSuccess, onError, resetOnError, shouldRender],+ );++ const handleExpire = useCallback(() => {+ if (shouldRender) {+ setToken(null);+ setVerified(false);+ }+ }, [shouldRender]);++ const handleError = useCallback(+ (err: Error) => {+ if (shouldRender) {+ setError(err);+ if (resetOnError) {+ setVerified(false);+ }+ if (onError) onError(err);+ }+ },+ [onError, shouldRender, resetOnError],+ );++ return {+ token,+ verifying,+ verified,+ error,+ handleVerify,+ handleExpire,+ handleError,+ reset,+ siteKey: TURNSTILE_SITE_KEY,+ shouldRender,+ };+}diff --git a/autogpt_platform/frontend/src/lib/turnstile.ts b/autogpt_platform/frontend/src/lib/turnstile.tsnew file mode 100644index 0000000000..0301df7d9b--- /dev/null+++ b/autogpt_platform/frontend/src/lib/turnstile.ts@@ -0,0 +1,42 @@+/**+ * Utility functions for working with Cloudflare Turnstile+ */+import { BehaveAs, getBehaveAs } from "@/lib/utils";++export async function verifyTurnstileToken(+ token: string,+ action?: string,+): Promise<boolean> {+ // Skip verification in local development+ const behaveAs = getBehaveAs();+ if (behaveAs !== BehaveAs.CLOUD) {+ return true;+ }++ try {+ const response = await fetch(+ `${process.env.NEXT_PUBLIC_AGPT_SERVER_URL}/turnstile/verify`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ token,+ action,+ }),+ },+ );++ if (!response.ok) {+ console.error("Turnstile verification failed:", await response.text());+ return false;+ }++ const data = await response.json();+ return data.success === true;+ } catch (error) {+ console.error("Error verifying Turnstile token:", error);+ return false;+ }+}