Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Turnstile (#643)

Bill Yangfb369433982d
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index c5e4368c4..ef29a404c 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -9,7 +9,9 @@
"Bash(npm run lint)",
"WebFetch(domain:www.mintlify.com)",
"WebSearch",
- "WebFetch(domain:github.com)"
+ "WebFetch(domain:github.com)",
+ "Bash(npm install @marsidev/react-turnstile)",
+ "Bash(npm install @marsidev/react-turnstile --legacy-peer-deps)"
],
"deny": [],
"ask": []
diff --git a/.env.example b/.env.example
index a1d429dbd..8e97c3c0b 100644
--- a/.env.example
+++ b/.env.example
@@ -25,3 +25,6 @@ POSTGRES_USER=frog
POSTGRES_PASSWORD=frog
RESEND_API_KEY=rs_XXXXXXX
+
+# External Service Tokens (optional)
+MAPBOX_TOKEN=
diff --git a/client/Dockerfile b/client/Dockerfile
index bd5907b89..057f844fa 100644
--- a/client/Dockerfile
+++ b/client/Dockerfile
@@ -29,10 +29,12 @@ ARG NEXT_PUBLIC_BACKEND_URL
ARG NEXT_PUBLIC_DISABLE_SIGNUP
ARG NEXT_PUBLIC_CLOUD
ARG NEXT_PUBLIC_MAPBOX_TOKEN
+ARG NEXT_PUBLIC_TURNSTILE_SITE_KEY
ENV NEXT_PUBLIC_BACKEND_URL=${NEXT_PUBLIC_BACKEND_URL}
ENV NEXT_PUBLIC_DISABLE_SIGNUP=${NEXT_PUBLIC_DISABLE_SIGNUP}
ENV NEXT_PUBLIC_CLOUD=${NEXT_PUBLIC_CLOUD}
ENV NEXT_PUBLIC_MAPBOX_TOKEN=${NEXT_PUBLIC_MAPBOX_TOKEN}
+ENV NEXT_PUBLIC_TURNSTILE_SITE_KEY=${NEXT_PUBLIC_TURNSTILE_SITE_KEY}
WORKDIR /app/client
RUN npm run build
diff --git a/client/package-lock.json b/client/package-lock.json
index 1624ad5d1..9985d3463 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -1,15 +1,16 @@
{
"name": "client",
- "version": "1.6.1",
+ "version": "2.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "client",
- "version": "1.6.1",
+ "version": "2.0.1",
"dependencies": {
"@hookform/resolvers": "5.0.1",
"@icons-pack/react-simple-icons": "^13.6.0",
+ "@marsidev/react-turnstile": "^1.3.1",
"@nivo/bar": "0.96.0",
"@nivo/calendar": "0.96.0",
"@nivo/line": "0.96.0",
@@ -1591,6 +1592,16 @@
"node": ">=6.0.0"
}
},
+ "node_modules/@marsidev/react-turnstile": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@marsidev/react-turnstile/-/react-turnstile-1.3.1.tgz",
+ "integrity": "sha512-h2THG/75k4Y049hgjSGPIcajxXnh+IZAiXVbryQyVmagkboN7pJtBgR16g8akjwUBSfRrg6jw6KvPDjscQflog==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^17.0.2 || ^18.0.0 || ^19.0",
+ "react-dom": "^17.0.2 || ^18.0.0 || ^19.0"
+ }
+ },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.11.tgz",
diff --git a/client/package.json b/client/package.json
index 7126a1286..db4f5f4ec 100644
--- a/client/package.json
+++ b/client/package.json
@@ -14,6 +14,7 @@
"dependencies": {
"@hookform/resolvers": "5.0.1",
"@icons-pack/react-simple-icons": "^13.6.0",
+ "@marsidev/react-turnstile": "^1.3.1",
"@nivo/bar": "0.96.0",
"@nivo/calendar": "0.96.0",
"@nivo/line": "0.96.0",
diff --git a/client/src/app/invitation/components/signup.tsx b/client/src/app/invitation/components/signup.tsx
index 08dca5521..c5eb4b0b9 100644
--- a/client/src/app/invitation/components/signup.tsx
+++ b/client/src/app/invitation/components/signup.tsx
@@ -3,10 +3,12 @@
import { useState } from "react";
import { authClient } from "../../../lib/auth";
import { userStore } from "../../../lib/userStore";
+import { IS_CLOUD } from "../../../lib/const";
import { AuthInput } from "@/components/auth/AuthInput";
import { AuthButton } from "@/components/auth/AuthButton";
import { AuthError } from "@/components/auth/AuthError";
import { SocialButtons } from "@/components/auth/SocialButtons";
+import { Turnstile } from "@/components/auth/Turnstile";
interface SignupProps {
inviterEmail?: string | null;
@@ -18,6 +20,7 @@ export function Signup({ inviterEmail, organization }: SignupProps) {
const [error, setError] = useState<string>("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
+ const [turnstileToken, setTurnstileToken] = useState<string>("");
const handleSignup = async (e: React.FormEvent) => {
e.preventDefault();
@@ -25,11 +28,27 @@ export function Signup({ inviterEmail, organization }: SignupProps) {
setError("");
try {
- const { data, error } = await authClient.signUp.email({
- email,
- name: email.split("@")[0], // Use email prefix as default name
- password,
- });
+ // Validate Turnstile token if in cloud mode
+ if (IS_CLOUD && !turnstileToken) {
+ setError("Please complete the captcha verification");
+ setIsLoading(false);
+ return;
+ }
+
+ const { data, error } = await authClient.signUp.email(
+ {
+ email,
+ name: email.split("@")[0], // Use email prefix as default name
+ password,
+ },
+ {
+ onRequest: context => {
+ if (IS_CLOUD && turnstileToken) {
+ context.headers.set("x-captcha-response", turnstileToken);
+ }
+ },
+ }
+ );
if (data?.user) {
userStore.setState({
@@ -72,7 +91,20 @@ export function Signup({ inviterEmail, organization }: SignupProps) {
onChange={e => setPassword(e.target.value)}
/>
- <AuthButton isLoading={isLoading} loadingText="Creating account...">
+ {IS_CLOUD && (
+ <Turnstile
+ onSuccess={token => setTurnstileToken(token)}
+ onError={() => setTurnstileToken("")}
+ onExpire={() => setTurnstileToken("")}
+ className="flex justify-center"
+ />
+ )}
+
+ <AuthButton
+ isLoading={isLoading}
+ loadingText="Creating account..."
+ disabled={IS_CLOUD ? !turnstileToken || isLoading : isLoading}
+ >
Sign Up to Accept Invitation
</AuthButton>
diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsx
index 715facd80..10a00bbaf 100644
--- a/client/src/app/signup/page.tsx
+++ b/client/src/app/signup/page.tsx
@@ -4,6 +4,7 @@ import { AuthButton } from "@/components/auth/AuthButton";
import { AuthError } from "@/components/auth/AuthError";
import { AuthInput } from "@/components/auth/AuthInput";
import { SocialButtons } from "@/components/auth/SocialButtons";
+import { Turnstile } from "@/components/auth/Turnstile";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
@@ -54,6 +55,7 @@ export default function SignupPage() {
// Step 1: Account creation
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
+ const [turnstileToken, setTurnstileToken] = useState<string>("");
// Step 2: Organization creation
const [orgName, setOrgName] = useState("");
@@ -81,11 +83,27 @@ export default function SignupPage() {
setError("");
try {
- const { data, error } = await authClient.signUp.email({
- email,
- name: email.split("@")[0], // Use email prefix as default name
- password,
- });
+ // Validate Turnstile token if in cloud mode
+ if (IS_CLOUD && !turnstileToken) {
+ setError("Please complete the captcha verification");
+ setIsLoading(false);
+ return;
+ }
+
+ const { data, error } = await authClient.signUp.email(
+ {
+ email,
+ name: email.split("@")[0], // Use email prefix as default name
+ password,
+ },
+ {
+ onRequest: context => {
+ if (IS_CLOUD && turnstileToken) {
+ context.headers.set("x-captcha-response", turnstileToken);
+ }
+ },
+ }
+ );
if (data?.user) {
userStore.setState({
@@ -195,12 +213,22 @@ export default function SignupPage() {
onChange={e => setPassword(e.target.value)}
/>
+ {IS_CLOUD && (
+ <Turnstile
+ onSuccess={token => setTurnstileToken(token)}
+ onError={() => setTurnstileToken("")}
+ onExpire={() => setTurnstileToken("")}
+ className="flex justify-center"
+ />
+ )}
+
<AuthButton
isLoading={isLoading}
loadingText="Creating account..."
onClick={handleAccountSubmit}
type="button"
className="mt-6 transition-all duration-300 h-11"
+ disabled={IS_CLOUD ? !turnstileToken || isLoading : isLoading}
>
Continue
<ArrowRight className="ml-2 h-4 w-4" />
diff --git a/client/src/components/auth/AuthButton.tsx b/client/src/components/auth/AuthButton.tsx
index 397b730eb..9bde81bc1 100644
--- a/client/src/components/auth/AuthButton.tsx
+++ b/client/src/components/auth/AuthButton.tsx
@@ -11,6 +11,7 @@ interface AuthButtonProps {
onClick?: () => void;
type?: "button" | "submit" | "reset";
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link" | "success";
+ disabled?: boolean;
}
export function AuthButton({
@@ -21,9 +22,10 @@ export function AuthButton({
onClick,
type = "submit",
variant = "success",
+ disabled = false,
}: AuthButtonProps) {
return (
- <Button type={type} className={`w-full ${className}`} disabled={isLoading} variant={variant} onClick={onClick}>
+ <Button type={type} className={`w-full ${className}`} disabled={disabled || isLoading} variant={variant} onClick={onClick}>
{isLoading ? loadingText : children}
</Button>
);
diff --git a/client/src/components/auth/Turnstile.tsx b/client/src/components/auth/Turnstile.tsx
new file mode 100644
index 000000000..51824240a
--- /dev/null
+++ b/client/src/components/auth/Turnstile.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { Turnstile as CloudflareTurnstile, TurnstileInstance } from "@marsidev/react-turnstile";
+import { useRef } from "react";
+
+interface TurnstileProps {
+ onSuccess: (token: string) => void;
+ onError?: () => void;
+ onExpire?: () => void;
+ className?: string;
+}
+
+export function Turnstile({ onSuccess, onError, onExpire, className = "" }: TurnstileProps) {
+ const turnstileRef = useRef<TurnstileInstance>(null);
+ const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
+
+ if (!siteKey) {
+ console.error("NEXT_PUBLIC_TURNSTILE_SITE_KEY is not defined");
+ return null;
+ }
+
+ return (
+ <div className={className}>
+ <CloudflareTurnstile
+ ref={turnstileRef}
+ siteKey={siteKey}
+ onSuccess={onSuccess}
+ onError={() => {
+ console.error("Turnstile error");
+ onError?.();
+ }}
+ onExpire={() => {
+ console.warn("Turnstile token expired");
+ onExpire?.();
+ }}
+ options={{
+ theme: "dark",
+ size: "normal",
+ }}
+ />
+ </div>
+ );
+}
diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml
index c806b6923..1e9e0c5b2 100644
--- a/docker-compose.cloud.yml
+++ b/docker-compose.cloud.yml
@@ -117,6 +117,7 @@ services:
- AXIOM_DATASET=${AXIOM_DATASET}
- AXIOM_TOKEN=${AXIOM_TOKEN}
- MAPBOX_TOKEN=${MAPBOX_TOKEN}
+ - TURNSTILE_SECRET_KEY=${TURNSTILE_SECRET_KEY}
depends_on:
clickhouse:
condition: service_healthy
@@ -138,12 +139,14 @@ services:
NEXT_PUBLIC_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
NEXT_PUBLIC_CLOUD: ${CLOUD}
NEXT_PUBLIC_MAPBOX_TOKEN: ${MAPBOX_TOKEN}
+ NEXT_PUBLIC_TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY}
environment:
- NODE_ENV=production
- NEXT_PUBLIC_BACKEND_URL=${BASE_URL}
- NEXT_PUBLIC_DISABLE_SIGNUP=${DISABLE_SIGNUP}
- NEXT_PUBLIC_CLOUD=${CLOUD}
- NEXT_PUBLIC_MAPBOX_TOKEN=${MAPBOX_TOKEN}
+ - NEXT_PUBLIC_TURNSTILE_SITE_KEY=${TURNSTILE_SITE_KEY}
depends_on:
- backend
restart: unless-stopped
diff --git a/server/src/index.ts b/server/src/index.ts
index 0ba6fd275..3f1304448 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -150,7 +150,7 @@ server.register(cors, {
callback(null, true);
},
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
- allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
+ allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "x-captcha-response"],
credentials: true,
});
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index 3dbe22c40..dd50f8afd 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -1,6 +1,6 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
-import { admin, emailOTP, organization } from "better-auth/plugins";
+import { admin, emailOTP, organization, captcha } from "better-auth/plugins";
import dotenv from "dotenv";
import { asc, eq } from "drizzle-orm";
import pg from "pg";
@@ -8,7 +8,7 @@ import pg from "pg";
import { db } from "../db/postgres/postgres.js";
import * as schema from "../db/postgres/schema.js";
import { user } from "../db/postgres/schema.js";
-import { DISABLE_SIGNUP } from "./const.js";
+import { DISABLE_SIGNUP, IS_CLOUD } from "./const.js";
import { sendEmail, sendInvitationEmail } from "./email/email.js";
dotenv.config();
@@ -82,6 +82,15 @@ const pluginList = [
}
},
}),
+ // Add Cloudflare Turnstile captcha (cloud only)
+ ...(IS_CLOUD && process.env.TURNSTILE_SECRET_KEY
+ ? [
+ captcha({
+ provider: "cloudflare-turnstile",
+ secretKey: process.env.TURNSTILE_SECRET_KEY,
+ }),
+ ]
+ : []),
];
export let auth: AuthType | null = betterAuth({