🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(web): restore optional Cloudflare Turnstile captcha on credential auth (#18580)
Max Deichmanncb2cebae9f8e
diff --git a/.env.dev.example b/.env.dev.exampleindex 6a2306eb95..c61f321cd0 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -128,6 +128,13 @@ EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.CLOUD_CRM_EMAIL="" # Optional BCC address for usage threshold emails (e.g., for CRM integration like HubSpot)+# Cloudflare Turnstile (optional). Use a widget that has localhost registered.+# Cloudflare's test keys do not work here: their siteverify result reports+# hostname example.com and no action, which the server check rejects.+# NEXT_PUBLIC_TURNSTILE_SITE_KEY=+# TURNSTILE_SECRET=+# TURNSTILE_HOSTNAMES=localhost+# S3 Batch ExportsLANGFUSE_S3_BATCH_EXPORT_ENABLED=trueLANGFUSE_S3_BATCH_EXPORT_BUCKET=langfusediff --git a/.env.prod.example b/.env.prod.exampleindex 4a0e66de6e..08307c9900 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -442,6 +442,14 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# SENTRY_CSP_REPORT_URI=+# Cloudflare Turnstile captcha on credentials sign-in and email sign-up.+# Setting TURNSTILE_SECRET enables the check; TURNSTILE_HOSTNAMES lists the+# frontend hostnames siteverify must report (comma-separated, no localhost in+# production). NEXT_PUBLIC_TURNSTILE_SITE_KEY is baked in at build time.+# NEXT_PUBLIC_TURNSTILE_SITE_KEY=+# TURNSTILE_SECRET=+# TURNSTILE_HOSTNAMES=+# Demo project that users can use to try the platform# NEXT_PUBLIC_DEMO_ORG_ID=# NEXT_PUBLIC_DEMO_PROJECT_ID=diff --git a/.github/workflows/_deploy_ecs_service.yml b/.github/workflows/_deploy_ecs_service.ymlindex 55ad829026..f4255cce13 100644--- a/.github/workflows/_deploy_ecs_service.yml+++ b/.github/workflows/_deploy_ecs_service.yml@@ -94,6 +94,7 @@ jobs:VARS_NEXT_PUBLIC_POSTHOG_KEY: ${{ vars.NEXT_PUBLIC_POSTHOG_KEY }}VARS_NEXT_PUBLIC_POSTHOG_HOST: ${{ vars.NEXT_PUBLIC_POSTHOG_HOST }}VARS_NEXT_PUBLIC_PLAIN_APP_ID: ${{ vars.NEXT_PUBLIC_PLAIN_APP_ID }}+ VARS_NEXT_PUBLIC_TURNSTILE_SITE_KEY: ${{ vars.NEXT_PUBLIC_TURNSTILE_SITE_KEY }}VARS_SENTRY_ORG: ${{ vars.SENTRY_ORG }}VARS_SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}VARS_NEXT_PUBLIC_LANGFUSE_TRACING_SAMPLE_RATE: ${{ vars.NEXT_PUBLIC_LANGFUSE_TRACING_SAMPLE_RATE }}@@ -115,6 +116,7 @@ jobs:--build-arg NEXT_PUBLIC_POSTHOG_KEY=${VARS_NEXT_PUBLIC_POSTHOG_KEY} \--build-arg NEXT_PUBLIC_POSTHOG_HOST=${VARS_NEXT_PUBLIC_POSTHOG_HOST} \--build-arg NEXT_PUBLIC_PLAIN_APP_ID=${VARS_NEXT_PUBLIC_PLAIN_APP_ID} \+ --build-arg NEXT_PUBLIC_TURNSTILE_SITE_KEY=${VARS_NEXT_PUBLIC_TURNSTILE_SITE_KEY} \--build-arg SENTRY_AUTH_TOKEN=${SECRETS_SENTRY_AUTH_TOKEN} \--build-arg SENTRY_ORG=${VARS_SENTRY_ORG} \--build-arg SENTRY_PROJECT=${VARS_SENTRY_PROJECT} \diff --git a/web/Dockerfile b/web/Dockerfileindex 5eaa232d18..652cd5269b 100644--- a/web/Dockerfile+++ b/web/Dockerfile@@ -169,6 +169,8 @@ ARG NEXT_PUBLIC_DEMO_PROJECT_IDENV NEXT_PUBLIC_DEMO_PROJECT_ID=$NEXT_PUBLIC_DEMO_PROJECT_IDARG NEXT_PUBLIC_SIGN_UP_DISABLEDENV NEXT_PUBLIC_SIGN_UP_DISABLED=$NEXT_PUBLIC_SIGN_UP_DISABLED+ARG NEXT_PUBLIC_TURNSTILE_SITE_KEY+ENV NEXT_PUBLIC_TURNSTILE_SITE_KEY=$NEXT_PUBLIC_TURNSTILE_SITE_KEYARG NEXT_PUBLIC_PREVIEW_PR_URLENV NEXT_PUBLIC_PREVIEW_PR_URL=$NEXT_PUBLIC_PREVIEW_PR_URLARG NEXT_PUBLIC_PREVIEW_PR_AUTHORdiff --git a/web/src/__tests__/server/unit/verifyTurnstile.servertest.ts b/web/src/__tests__/server/unit/verifyTurnstile.servertest.tsnew file mode 100644index 0000000000..46eb9997a9--- /dev/null+++ b/web/src/__tests__/server/unit/verifyTurnstile.servertest.ts@@ -0,0 +1,139 @@+const { env } = vi.hoisted(() => ({+ env: {+ TURNSTILE_SECRET: undefined as string | undefined,+ TURNSTILE_HOSTNAMES: undefined as string | undefined,+ NEXT_PUBLIC_TURNSTILE_SITE_KEY: undefined as string | undefined,+ },+}));++vi.mock("@/src/env.mjs", () => ({ env }));++vi.mock("@langfuse/shared/src/server", () => ({+ redis: null,+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ ClickHouseClientManager: {+ getInstance: () => ({+ closeAllConnections: vi.fn(async () => undefined),+ }),+ },+}));++import { TURNSTILE_ACTIONS } from "@/src/features/auth/constants";+import {+ getTurnstileRemoteIp,+ verifyTurnstileToken,+} from "@/src/features/auth/server/verifyTurnstile";++const fetchMock = vi.fn();++function siteverifyReturns(body: Record<string, unknown>, status = 200) {+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify(body), { status }),+ );+}++const verifyLogin = (token: unknown) =>+ verifyTurnstileToken({+ token,+ action: TURNSTILE_ACTIONS.login,+ remoteIp: "203.0.113.7",+ });++describe("verifyTurnstileToken", () => {+ beforeEach(() => {+ env.TURNSTILE_SECRET = "test-secret";+ env.TURNSTILE_HOSTNAMES = "cloud.langfuse.com, us.cloud.langfuse.com";+ env.NEXT_PUBLIC_TURNSTILE_SITE_KEY = "site-key";+ fetchMock.mockReset();+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("skips the check when no secret is configured", async () => {+ env.TURNSTILE_SECRET = undefined;++ await expect(verifyLogin(undefined)).resolves.toBe(true);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("accepts a token with the expected action and an allowed hostname", async () => {+ siteverifyReturns({+ success: true,+ action: "login",+ hostname: "us.cloud.langfuse.com",+ });++ await expect(verifyLogin("token-from-widget")).resolves.toBe(true);++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",+ );+ const body = init.body as URLSearchParams;+ expect(body.get("secret")).toBe("test-secret");+ expect(body.get("response")).toBe("token-from-widget");+ expect(body.get("remoteip")).toBe("203.0.113.7");+ });++ it.each([+ [+ "siteverify rejects the token",+ { success: false, action: "login", hostname: "cloud.langfuse.com" },+ ],+ [+ "the action belongs to another surface",+ { success: true, action: "signup", hostname: "cloud.langfuse.com" },+ ],+ [+ "the hostname is not allowlisted",+ { success: true, action: "login", hostname: "evil.example.com" },+ ],+ ["the hostname is missing", { success: true, action: "login" }],+ ])("rejects when %s", async (_case, response) => {+ siteverifyReturns(response);++ await expect(verifyLogin("token-from-widget")).resolves.toBe(false);+ });++ it("rejects without calling siteverify when the token is missing or too long", async () => {+ await expect(verifyLogin(undefined)).resolves.toBe(false);+ await expect(verifyLogin("")).resolves.toBe(false);+ await expect(verifyLogin("x".repeat(2049))).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("rejects when the secret is set but the site key was not baked in", async () => {+ env.NEXT_PUBLIC_TURNSTILE_SITE_KEY = undefined;++ await expect(verifyLogin("token-from-widget")).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("rejects when the hostname allowlist is empty", async () => {+ env.TURNSTILE_HOSTNAMES = " , ";++ await expect(verifyLogin("token-from-widget")).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("rejects when siteverify is unreachable or errors", async () => {+ fetchMock.mockRejectedValueOnce(new Error("network down"));+ await expect(verifyLogin("token-from-widget")).resolves.toBe(false);++ siteverifyReturns({ success: true }, 500);+ await expect(verifyLogin("token-from-widget")).resolves.toBe(false);+ });+});++describe("getTurnstileRemoteIp", () => {+ it("uses the first x-forwarded-for hop", () => {+ expect(+ getTurnstileRemoteIp({ "x-forwarded-for": "203.0.113.7, 10.0.0.1" }),+ ).toBe("203.0.113.7");+ expect(getTurnstileRemoteIp({})).toBeUndefined();+ expect(getTurnstileRemoteIp(undefined)).toBeUndefined();+ });+});diff --git a/web/src/env.mjs b/web/src/env.mjsindex 9d9ca3332c..d993262049 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -307,6 +307,11 @@ export const env = createEnv({EMAIL_FROM_ADDRESS: z.string().optional(),SMTP_CONNECTION_URL: z.string().optional(),+ // Cloudflare Turnstile. When the secret is set, credentials sign-in and+ // email sign-up require a valid token whose hostname is in+ // TURNSTILE_HOSTNAMES (comma-separated frontend hostnames).+ TURNSTILE_SECRET: z.string().optional(),+ TURNSTILE_HOSTNAMES: z.string().optional(),// OtelOTEL_EXPORTER_OTLP_ENDPOINT: z.string().default("http://localhost:4318"),@@ -729,6 +734,7 @@ export const env = createEnv({NEXT_PUBLIC_DEMO_PROJECT_ID: z.string().optional(),NEXT_PUBLIC_DEMO_ORG_ID: z.string().optional(),NEXT_PUBLIC_SIGN_UP_DISABLED: z.enum(["true", "false"]).default("false"),+ NEXT_PUBLIC_TURNSTILE_SITE_KEY: z.string().optional(),// PR preview deployments only (.github/workflows/preview-build.yml):// identify the environment with a top-of-page strip linking back to the PR.NEXT_PUBLIC_PREVIEW_PR_URL: z.url().optional(),@@ -788,6 +794,7 @@ export const env = createEnv({NEXT_PUBLIC_LANGFUSE_ANALYTICS_EXPORTER_CUTOFF:process.env.NEXT_PUBLIC_LANGFUSE_ANALYTICS_EXPORTER_CUTOFF,NEXT_PUBLIC_SIGN_UP_DISABLED: process.env.NEXT_PUBLIC_SIGN_UP_DISABLED,+ NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,NEXT_PUBLIC_PREVIEW_PR_URL: process.env.NEXT_PUBLIC_PREVIEW_PR_URL,NEXT_PUBLIC_PREVIEW_PR_AUTHOR: process.env.NEXT_PUBLIC_PREVIEW_PR_AUTHOR,NEXT_PUBLIC_PREVIEW_LAST_UPDATED:@@ -1006,6 +1013,8 @@ export const env = createEnv({EMAIL_FROM_ADDRESS: process.env.EMAIL_FROM_ADDRESS,SMTP_CONNECTION_URL: process.env.SMTP_CONNECTION_URL,+ TURNSTILE_SECRET: process.env.TURNSTILE_SECRET,+ TURNSTILE_HOSTNAMES: process.env.TURNSTILE_HOSTNAMES,// OtelOTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsxindex 05a5bb911f..091674b25e 100644--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import * as z from "zod";@@ -28,6 +28,12 @@ import { passwordSchema } from "@/src/features/auth";import { useLangfuseCloudRegion } from "@/src/features/organizations";import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials/lib/credentialsUtils";import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";+import { env } from "@/src/env.mjs";+import { TURNSTILE_ACTIONS } from "@/src/features/auth/constants";+import {+ TurnstileWidget,+ type TurnstileWidgetHandle,+} from "@/src/features/auth/components/TurnstileWidget";const resetPasswordSchema = z.object({@@ -75,6 +81,9 @@ export function ResetPasswordPage({const mutResetPassword = api.credentials.resetPassword.useMutation();const effectiveEmail = session.data?.user?.email ?? email;+ const turnstileSiteKey = env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+ const [turnstileToken, setTurnstileToken] = useState<string>();+ const turnstileRef = useRef<TurnstileWidgetHandle>(null);const form = useForm({resolver: zodResolver(resetPasswordSchema),@@ -132,7 +141,9 @@ export function ResetPasswordPage({email: effectiveEmail,password: values.password,redirect: false,+ ...(turnstileToken ? { turnstileToken } : {}),});+ turnstileRef.current?.reset();if (!signInResult?.ok) {target = "/auth/sign-in";}@@ -283,11 +294,22 @@ export function ResetPasswordPage({</FormItem>)}/>+ {turnstileSiteKey ? (+ <TurnstileWidget+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ action={TURNSTILE_ACTIONS.login}+ onTokenChange={setTurnstileToken}+ />+ ) : null}<div className="pt-4"><Buttontype="submit"className="w-full"- disabled={mutResetPassword.isPending}+ disabled={+ mutResetPassword.isPending ||+ (Boolean(turnstileSiteKey) && !turnstileToken)+ }loading={mutResetPassword.isPending}>{submitLabel}diff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.tsindex cf4f176000..51482164ea 100644--- a/web/src/features/auth-credentials/server/signupApiHandler.ts+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts@@ -1,6 +1,14 @@import { env } from "@/src/env.mjs";import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";-import { ENTERPRISE_SSO_REQUIRED_MESSAGE } from "@/src/features/auth/constants";+import {+ ENTERPRISE_SSO_REQUIRED_MESSAGE,+ TURNSTILE_ACTIONS,+ TURNSTILE_FAILED_MESSAGE,+} from "@/src/features/auth/constants";+import {+ getTurnstileRemoteIp,+ verifyTurnstileToken,+} from "@/src/features/auth/server/verifyTurnstile";import { getAdClickIdsFromRequest } from "@/src/features/auth/lib/signupAttribution";import { signupSchema } from "@/src/features/auth/lib/signupSchema";import { getSsoAuthProviderIdForDomain } from "@/src/ee/features/multi-tenant-sso/server";@@ -83,6 +91,16 @@ export async function signupApiHandler(const body = validBody.data;+ const turnstileValid = await verifyTurnstileToken({+ token: req.body?.turnstileToken,+ action: TURNSTILE_ACTIONS.signup,+ remoteIp: getTurnstileRemoteIp(req.headers),+ });+ if (!turnstileValid) {+ res.status(403).json({ message: TURNSTILE_FAILED_MESSAGE });+ return;+ }+const eligibilityError = await validateSignupEligibility({email: body.email,});diff --git a/web/src/features/auth/SignInPage.tsx b/web/src/features/auth/SignInPage.tsxindex d42ae64e38..1b22f9e343 100644--- a/web/src/features/auth/SignInPage.tsx+++ b/web/src/features/auth/SignInPage.tsx@@ -49,6 +49,11 @@ import { cn } from "@/src/utils/tailwind";import { useLangfuseCloudRegion } from "@/src/features/organizations";import { getSafeRedirectPath } from "@/src/utils/redirect";import { Spinner } from "@/src/components/layouts/spinner";+import {+ TurnstileWidget,+ type TurnstileWidgetHandle,+} from "@/src/features/auth/components/TurnstileWidget";+import { TURNSTILE_ACTIONS } from "@/src/features/auth/constants";// The shared, intentionally-public demo identity created by the seed script// (packages/shared/scripts/seeder/seed-postgres.ts) and posted in every@@ -546,6 +551,9 @@ export default function SignInPage({!authProviders.sso,);const [continueLoading, setContinueLoading] = useState<boolean>(false);+ const turnstileSiteKey = env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+ const [turnstileToken, setTurnstileToken] = useState<string>();+ const turnstileRef = useRef<TurnstileWidgetHandle>(null);const [lastUsedAuthMethod, setLastUsedAuthMethod] =useLocalStorage<NextAuthProvider | null>("langfuse_last_used_auth_method",@@ -626,6 +634,7 @@ export default function SignInPage({password: values.password,callbackUrl: targetPath ?? "/",redirect: false,+ turnstileToken,});if (result === undefined) {// next-auth's signIn() returns undefined when its providers fetch@@ -664,6 +673,9 @@ export default function SignInPage({captureUnknownError("auth.signIn.credentials", error);}setCredentialsFormError("An unexpected error occurred.");+ } finally {+ // The token was redeemed (or rejected) by this attempt either way.+ turnstileRef.current?.reset();}}@@ -681,7 +693,10 @@ export default function SignInPage({env.NEXT_PUBLIC_PREVIEW_DEMO_AUTO_SIGN_IN === "true" &&authProviders.credentials &&!autoSignInOptedOut &&- !nextAuthError;+ !nextAuthError &&+ // Auto sign-in has no captcha. When the site key is baked in, the form+ // below collects a login token instead of failing this request.+ !env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;const [previewAutoSignInPending, setPreviewAutoSignInPending] = useState(previewAutoSignInEnabled,);@@ -911,6 +926,15 @@ export default function SignInPage({/>)}+ {showPasswordStep && turnstileSiteKey && (+ <TurnstileWidget+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ action={TURNSTILE_ACTIONS.login}+ onTokenChange={setTurnstileToken}+ />+ )}+{/* Primary action button */}<Buttontype="submit"@@ -921,6 +945,9 @@ export default function SignInPage({: continueLoading}disabled={+ (showPasswordStep &&+ Boolean(turnstileSiteKey) &&+ !turnstileToken) ||credentialsForm.watch("email") === "" ||(showPasswordStep &&credentialsForm.watch("password") === "")diff --git a/web/src/features/auth/SignUpPage.tsx b/web/src/features/auth/SignUpPage.tsxindex d1c523aa6d..b1195476da 100644--- a/web/src/features/auth/SignUpPage.tsx+++ b/web/src/features/auth/SignUpPage.tsx@@ -15,7 +15,7 @@ import Link from "next/link";import { useForm } from "react-hook-form";import * as z from "zod";import { env } from "@/src/env.mjs";-import { useState } from "react";+import { useRef, useState } from "react";import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/LangfuseIcon";import { CloudPrivacyNotice } from "@/src/features/auth/components/AuthCloudPrivacyNotice";import { CloudRegionSwitch } from "@/src/features/auth/components/AuthCloudRegionSwitch";@@ -36,9 +36,37 @@ import useLocalStorage from "@/src/components/useLocalStorage";import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials";import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";+import {+ TurnstileWidget,+ type TurnstileWidgetHandle,+} from "@/src/features/auth/components/TurnstileWidget";+import { TURNSTILE_ACTIONS } from "@/src/features/auth/constants";type NextAuthProvider = NonNullable<Parameters<typeof signIn>[0]>;+const LOGIN_CAPTCHA_WAIT_MS = 20_000;+const ACCOUNT_CREATED_MESSAGE =+ "Your account was created. Complete the captcha, then sign in.";++function waitForLoginToken(+ pending: Promise<string | undefined> | undefined,+): Promise<string | undefined> {+ if (!pending) return Promise.resolve(undefined);+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve(undefined), LOGIN_CAPTCHA_WAIT_MS);+ pending.then(+ (token) => {+ clearTimeout(timer);+ resolve(token);+ },+ () => {+ clearTimeout(timer);+ resolve(undefined);+ },+ );+ });+}+// Schema for the verified signup flow (email + name only, no password)const signupVerifyFormSchema = z.object({name: StringNoHTMLNonEmpty.refine((value) => noUrlCheck(value), {@@ -97,6 +125,16 @@ function StandardSignupFlow({!authProviders.sso,);const [continueLoading, setContinueLoading] = useState<boolean>(false);+ const turnstileSiteKey = env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+ const [turnstileToken, setTurnstileToken] = useState<string>();+ // Account creation and the follow-up sign-in are separate siteverify checks+ // with different actions, so the widget switches to `login` once the+ // account exists.+ const [turnstileAction, setTurnstileAction] = useState<+ typeof TURNSTILE_ACTIONS.signup | typeof TURNSTILE_ACTIONS.login+ >(TURNSTILE_ACTIONS.signup);+ const [accountCreated, setAccountCreated] = useState(false);+ const turnstileRef = useRef<TurnstileWidgetHandle>(null);const [lastUsedAuthMethod, setLastUsedAuthMethod] =useLocalStorage<NextAuthProvider | null>("langfuse_last_used_auth_method",@@ -195,44 +233,86 @@ function StandardSignupFlow({}}+ async function signInAfterSignup(+ values: z.infer<typeof signupSchema>,+ loginTurnstileToken: string | undefined,+ ) {+ let callbackUrl =+ targetPath ??+ (isLangfuseCloud+ ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`+ : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`);+ const demoTargetPath = getDemoTargetPath(targetPath);+ if (isLangfuseCloud && demoTargetPath) {+ callbackUrl = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding?targetPath=${encodeURIComponent(demoTargetPath)}`;+ }++ await signIn<"credentials">("credentials", {+ email: values.email,+ password: values.password,+ callbackUrl,+ turnstileToken: loginTurnstileToken,+ });+ }+async function onSubmit(values: z.infer<typeof signupSchema>) {+ // Once the account exists, later submits must not call signup again.+ // The widget is on the login action, so a signup retry would send a+ // token the signup endpoint rejects.+ let created = accountCreated;try {setFormError(null);+ if (created) {+ await signInAfterSignup(values, turnstileToken);+ return;+ }+const res = await fetch(`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth/signup`,{method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify(values),+ body: JSON.stringify({ ...values, turnstileToken }),},);if (!res.ok) {+ turnstileRef.current?.reset();const payload = (await res.json()) as { message: string };setFormError(payload.message);return;}- let callbackUrl =- targetPath ??- (isLangfuseCloud- ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`- : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`);- const demoTargetPath = getDemoTargetPath(targetPath);- if (isLangfuseCloud && demoTargetPath) {- callbackUrl = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding?targetPath=${encodeURIComponent(demoTargetPath)}`;+ created = true;+ setAccountCreated(true);++ // The sign-up request redeemed its token; signing in needs a fresh+ // token issued for the `login` action.+ let loginTurnstileToken: string | undefined;+ if (turnstileSiteKey) {+ const nextToken = turnstileRef.current?.nextToken();+ setTurnstileToken(undefined);+ setTurnstileAction(TURNSTILE_ACTIONS.login);+ loginTurnstileToken = await waitForLoginToken(nextToken);+ }+ if (turnstileSiteKey && !loginTurnstileToken) {+ setFormError(ACCOUNT_CREATED_MESSAGE);+ return;}- await signIn<"credentials">("credentials", {- email: values.email,- password: values.password,- callbackUrl,- });+ await signInAfterSignup(values, loginTurnstileToken);} catch {- setFormError("An error occurred. Please try again.");+ turnstileRef.current?.reset();+ setFormError(+ created+ ? ACCOUNT_CREATED_MESSAGE+ : "An error occurred. Please try again.",+ );}}+ const passwordSubmitLabel = accountCreated ? "Sign in" : "Sign up";+return (<SignupPageShell><Form {...form}>@@ -295,16 +375,28 @@ function StandardSignupFlow({)}/>)}+ {showPasswordStep && turnstileSiteKey && (+ <TurnstileWidget+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ action={turnstileAction}+ onTokenChange={setTurnstileToken}+ />+ )}<Buttontype="submit"className="w-full"loading={showPasswordStep ? form.formState.isSubmitting : continueLoading}- disabled={showPasswordStep ? false : form.watch("email") === ""}+ disabled={+ showPasswordStep+ ? Boolean(turnstileSiteKey) && !turnstileToken+ : form.watch("email") === ""+ }data-testid="submit-email-password-sign-up-form">- {showPasswordStep ? "Sign up" : "Continue"}+ {showPasswordStep ? passwordSubmitLabel : "Continue"}</Button>{formError ? (<div className="text-destructive text-center text-sm font-bold">@@ -341,6 +433,9 @@ function VerifiedSignupFlow({: "/auth/setup-password";const [formError, setFormError] = useState<string | null>(null);+ const turnstileSiteKey = env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;+ const [turnstileToken, setTurnstileToken] = useState<string>();+ const turnstileRef = useRef<TurnstileWidgetHandle>(null);const [lastUsedAuthMethod, setLastUsedAuthMethod] =useLocalStorage<NextAuthProvider | null>("langfuse_last_used_auth_method",@@ -367,9 +462,14 @@ function VerifiedSignupFlow({{method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email: values.email, name: values.name }),+ body: JSON.stringify({+ email: values.email,+ name: values.name,+ turnstileToken,+ }),},);+ turnstileRef.current?.reset();if (!res.ok) {const payload = (await res.json()) as { message: string };@@ -400,6 +500,7 @@ function VerifiedSignupFlow({);await router.push(setupPasswordPath);} catch {+ turnstileRef.current?.reset();setFormError("An error occurred. Please try again.");}}@@ -442,10 +543,19 @@ function VerifiedSignupFlow({</FormItem>)}/>+ {turnstileSiteKey && (+ <TurnstileWidget+ ref={turnstileRef}+ siteKey={turnstileSiteKey}+ action={TURNSTILE_ACTIONS.signupVerify}+ onTokenChange={setTurnstileToken}+ />+ )}<Buttontype="submit"className="w-full"loading={form.formState.isSubmitting}+ disabled={Boolean(turnstileSiteKey) && !turnstileToken}data-testid="submit-email-password-sign-up-form">Continuediff --git a/web/src/features/auth/components/TurnstileWidget.tsx b/web/src/features/auth/components/TurnstileWidget.tsxnew file mode 100644index 0000000000..fdc1d1b76d--- /dev/null+++ b/web/src/features/auth/components/TurnstileWidget.tsx@@ -0,0 +1,207 @@+import {+ useEffect,+ useEffectEvent,+ useImperativeHandle,+ useRef,+ useState,+ type Ref,+} from "react";+import { Button } from "@/src/components/ui/button";+import type { TurnstileAction } from "@/src/features/auth/constants";+import { useTheme } from "next-themes";++const SCRIPT_SRC =+ "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";++type TurnstileRenderOptions = {+ sitekey: string;+ action: string;+ theme?: "auto" | "light" | "dark";+ size?: "normal" | "compact" | "flexible";+ callback: (token: string) => void;+ "expired-callback": () => void;+ "error-callback": () => void;+};++function turnstileTheme(+ resolvedTheme: string | undefined,+): "light" | "dark" | undefined {+ if (resolvedTheme === "dark") return "dark";+ if (resolvedTheme === "light") return "light";+ return undefined;+}++type TurnstileApi = {+ render: (container: HTMLElement, options: TurnstileRenderOptions) => string;+ reset: (widgetId: string) => void;+ remove: (widgetId: string) => void;+};++declare global {+ interface Window {+ turnstile?: TurnstileApi;+ }+}++let scriptPromise: Promise<TurnstileApi> | null = null;++function loadTurnstile(): Promise<TurnstileApi> {+ if (window.turnstile) return Promise.resolve(window.turnstile);+ if (scriptPromise) return scriptPromise;+ scriptPromise = new Promise<TurnstileApi>((resolve, reject) => {+ const script = document.createElement("script");+ script.src = SCRIPT_SRC;+ script.async = true;+ script.defer = true;+ script.onload = () => {+ if (window.turnstile) {+ resolve(window.turnstile);+ return;+ }+ scriptPromise = null;+ script.remove();+ reject(new Error("Turnstile script loaded without its API"));+ };+ script.onerror = () => {+ scriptPromise = null;+ script.remove();+ reject(new Error("Failed to load the Turnstile script"));+ };+ document.head.appendChild(script);+ });+ return scriptPromise;+}++type PendingToken = ((token: string | undefined) => void) | null;++function settlePending(+ pending: { current: PendingToken },+ token: string | undefined,+) {+ pending.current?.(token);+ pending.current = null;+}++export type TurnstileWidgetHandle = {+ /** Discards the current token (tokens are single-use) and re-runs the challenge. */+ reset: () => void;+ /**+ * Resolves with the next token the widget issues, including after the+ * widget re-renders for a new `action`. Resolves `undefined` if the+ * challenge fails or another caller starts waiting first.+ */+ nextToken: () => Promise<string | undefined>;+};++/**+ * Cloudflare Turnstile widget, rendered explicitly so it can be reset after+ * every submit on pages that stay mounted. Changing `action` re-renders the+ * widget so the next token carries the new action. `onTokenChange` receives+ * `undefined` whenever the current token is no longer usable.+ */+type TurnstileWidgetProps = {+ siteKey: string;+ action: TurnstileAction;+ onTokenChange: (token: string | undefined) => void;+ ref?: Ref<TurnstileWidgetHandle>;+};++export function TurnstileWidget({+ siteKey,+ action,+ onTokenChange,+ ref,+}: TurnstileWidgetProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const widgetIdRef = useRef<string | null>(null);+ const pendingTokenRef = useRef<PendingToken>(null);+ const [scriptFailed, setScriptFailed] = useState(false);+ const [loadAttempt, setLoadAttempt] = useState(0);+ const { resolvedTheme } = useTheme();+ const theme = turnstileTheme(resolvedTheme);++ const handleToken = useEffectEvent((token: string | undefined) => {+ onTokenChange(token);+ if (token) settlePending(pendingTokenRef, token);+ });++ const handleError = useEffectEvent(() => {+ onTokenChange(undefined);+ settlePending(pendingTokenRef, undefined);+ });++ // Turnstile is an imperative third-party widget: render it into the+ // container on mount and remove it on unmount.+ useEffect(() => {+ if (!theme) return;+ let cancelled = false;+ setScriptFailed(false);+ // A new render issues a new token. Drop the previous one so the submit+ // button stays disabled until this widget shows its checkmark.+ handleToken(undefined);+ loadTurnstile()+ .then((turnstile) => {+ if (cancelled || !containerRef.current) return;+ widgetIdRef.current = turnstile.render(containerRef.current, {+ sitekey: siteKey,+ action,+ theme,+ size: "flexible",+ callback: (token) => handleToken(token),+ "expired-callback": () => handleToken(undefined),+ "error-callback": () => handleError(),+ });+ })+ .catch(() => {+ if (cancelled) return;+ setScriptFailed(true);+ handleError();+ });++ return () => {+ cancelled = true;+ if (widgetIdRef.current) {+ window.turnstile?.remove(widgetIdRef.current);+ widgetIdRef.current = null;+ }+ };+ }, [siteKey, action, loadAttempt, theme]);++ useImperativeHandle(+ ref,+ () => ({+ reset: () => {+ onTokenChange(undefined);+ if (widgetIdRef.current) {+ window.turnstile?.reset(widgetIdRef.current);+ }+ },+ nextToken: () => {+ settlePending(pendingTokenRef, undefined);+ return new Promise<string | undefined>((resolve) => {+ pendingTokenRef.current = resolve;+ });+ },+ }),+ [onTokenChange],+ );++ return (+ <div className="flex w-full flex-col gap-2">+ <div ref={containerRef} className="min-h-[65px] w-full" />+ {scriptFailed ? (+ <Button+ type="button"+ variant="link"+ className="h-auto justify-start px-0"+ onClick={() => {+ scriptPromise = null;+ setLoadAttempt((attempt) => attempt + 1);+ }}+ >+ Captcha failed to load. Try again+ </Button>+ ) : null}+ </div>+ );+}diff --git a/web/src/features/auth/constants.ts b/web/src/features/auth/constants.tsindex 1f247c04d3..48da98af2e 100644--- a/web/src/features/auth/constants.ts+++ b/web/src/features/auth/constants.ts@@ -12,3 +12,18 @@ export const MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE =// stored password is a bcrypt hash, which FIPS mode does not verify.export const PASSWORD_RESET_REQUIRED_MESSAGE ='This instance runs in FIPS mode and your password must be reset. Use "forgot password?" to set a new one, or contact your administrator.';++// Each protected surface sends its own Turnstile action; siteverify must+// return the same value. Cloudflare limits actions to 32 characters of+// letters, digits, underscores, and hyphens.+export const TURNSTILE_ACTIONS = {+ login: "login",+ signup: "signup",+ signupVerify: "signup_verify",+} as const;++export type TurnstileAction =+ (typeof TURNSTILE_ACTIONS)[keyof typeof TURNSTILE_ACTIONS];++export const TURNSTILE_FAILED_MESSAGE =+ "Captcha verification failed. Please complete the captcha and try again.";diff --git a/web/src/features/auth/server/verifyTurnstile.ts b/web/src/features/auth/server/verifyTurnstile.tsnew file mode 100644index 0000000000..3db6ebdb1b--- /dev/null+++ b/web/src/features/auth/server/verifyTurnstile.ts@@ -0,0 +1,119 @@+import { env } from "@/src/env.mjs";+import type { TurnstileAction } from "@/src/features/auth/constants";+import { logger } from "@langfuse/shared/src/server";++const SITEVERIFY_URL =+ "https://challenges.cloudflare.com/turnstile/v0/siteverify";+const MAX_TOKEN_LENGTH = 2048;++type SiteverifyResponse = {+ success?: boolean;+ action?: string;+ hostname?: string;+ "error-codes"?: string[];+};++function getExpectedHostnames(): Set<string> {+ return new Set(+ (env.TURNSTILE_HOSTNAMES ?? "")+ .split(",")+ .map((hostname) => hostname.trim().toLowerCase())+ .filter(Boolean),+ );+}++/**+ * First `x-forwarded-for` hop, passed to siteverify as an optional signal.+ * Cloudflare does not reject on a mismatch, so a spoofed header cannot bypass+ * the check.+ */+export function getTurnstileRemoteIp(+ headers: Record<string, unknown> | undefined,+): string | undefined {+ const forwarded = headers?.["x-forwarded-for"];+ const value = Array.isArray(forwarded) ? forwarded[0] : forwarded;+ if (typeof value !== "string") return undefined;+ return value.split(",")[0]?.trim() || undefined;+}++/**+ * Returns true when Turnstile is disabled (no secret configured) or the token+ * passes siteverify with the expected action and an allowed hostname.+ * Any other outcome, including network errors, returns false.+ */+export async function verifyTurnstileToken({+ token,+ action,+ remoteIp,+}: {+ token: unknown;+ action: TurnstileAction;+ remoteIp?: string;+}): Promise<boolean> {+ const secret = env.TURNSTILE_SECRET;+ if (!secret) return true;++ // The site key is baked into the client at build time. A secret without it+ // rejects every password sign-in while the page shows no captcha.+ if (!env.NEXT_PUBLIC_TURNSTILE_SITE_KEY) {+ logger.error(+ "Turnstile: TURNSTILE_SECRET is set but NEXT_PUBLIC_TURNSTILE_SITE_KEY is missing from this build; rejecting",+ );+ return false;+ }++ const expectedHostnames = getExpectedHostnames();+ if (expectedHostnames.size === 0) {+ logger.error(+ "Turnstile: TURNSTILE_SECRET is set but TURNSTILE_HOSTNAMES is empty; rejecting",+ );+ return false;+ }++ if (+ typeof token !== "string" ||+ token.length === 0 ||+ token.length > MAX_TOKEN_LENGTH+ ) {+ logger.warn("Turnstile: missing or malformed token", { action });+ return false;+ }++ const body = new URLSearchParams({ secret, response: token });+ if (remoteIp) body.set("remoteip", remoteIp);++ let result: SiteverifyResponse;+ try {+ const res = await fetch(SITEVERIFY_URL, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body,+ signal: AbortSignal.timeout(10_000),+ });+ if (!res.ok) throw new Error(`siteverify returned ${res.status}`);+ result = (await res.json()) as SiteverifyResponse;+ } catch (error) {+ logger.warn("Turnstile: siteverify request failed", {+ action,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }++ if (+ result.success !== true ||+ result.action !== action ||+ !result.hostname ||+ !expectedHostnames.has(result.hostname.toLowerCase())+ ) {+ logger.warn("Turnstile: token rejected", {+ expectedAction: action,+ action: result.action,+ hostname: result.hostname,+ errorCodes: result["error-codes"],+ });+ return false;+ }++ return true;+}diff --git a/web/src/pages/api/auth/signup-verify.ts b/web/src/pages/api/auth/signup-verify.tsindex 5bfe192d7a..74450d53ac 100644--- a/web/src/pages/api/auth/signup-verify.ts+++ b/web/src/pages/api/auth/signup-verify.ts@@ -3,6 +3,14 @@ import { isEmailVerificationRequired } from "@/src/features/auth-credentials";import { validateSignupEligibility } from "@/src/features/auth-credentials/server/signupApiHandler";import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";import { getAdClickIdsFromRequest } from "@/src/features/auth/lib/signupAttribution";+import {+ TURNSTILE_ACTIONS,+ TURNSTILE_FAILED_MESSAGE,+} from "@/src/features/auth/constants";+import {+ getTurnstileRemoteIp,+ verifyTurnstileToken,+} from "@/src/features/auth/server/verifyTurnstile";import { prisma } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";import type { NextApiRequest, NextApiResponse } from "next";@@ -46,6 +54,16 @@ export default async function handler(const { email, name } = parsed.data;const normalizedEmail = email.toLowerCase();+ const turnstileValid = await verifyTurnstileToken({+ token: req.body?.turnstileToken,+ action: TURNSTILE_ACTIONS.signupVerify,+ remoteIp: getTurnstileRemoteIp(req.headers),+ });+ if (!turnstileValid) {+ res.status(403).json({ message: TURNSTILE_FAILED_MESSAGE });+ return;+ }+// Run eligibility checks (signup disabled, SSO enforcement, etc.)const eligibilityError = await validateSignupEligibility({email: normalizedEmail,diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex e866007e25..880bceab41 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -60,7 +60,13 @@ import {ENTERPRISE_SSO_REQUIRED_MESSAGE,MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE,PASSWORD_RESET_REQUIRED_MESSAGE,+ TURNSTILE_ACTIONS,+ TURNSTILE_FAILED_MESSAGE,} from "@/src/features/auth/constants";+import {+ getTurnstileRemoteIp,+ verifyTurnstileToken,+} from "@/src/features/auth/server/verifyTurnstile";import { z } from "zod";import { CloudConfigSchema, projectRoleAccessRights } from "@langfuse/shared";import {@@ -96,14 +102,22 @@ const staticProviders: Provider[] = [placeholder: "[email protected]",},password: { label: "Password", type: "password" },+ turnstileToken: { label: "Turnstile token", type: "text" },},- async authorize(credentials, _req) {+ async authorize(credentials, req) {if (!credentials) throw new Error("No credentials");if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true")throw new Error("Sign in with email and password is disabled for this instance. Please use SSO.",);+ const turnstileValid = await verifyTurnstileToken({+ token: credentials.turnstileToken,+ action: TURNSTILE_ACTIONS.login,+ remoteIp: getTurnstileRemoteIp(req.headers),+ });+ if (!turnstileValid) throw new Error(TURNSTILE_FAILED_MESSAGE);+const blockedDomains = getSSOBlockedDomains();const domain = credentials.email.split("@")[1]?.toLowerCase();if (domain && blockedDomains.includes(domain)) {