Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(auth): unify Turnstile handling across app logins (#1605)

Sidfd36363b6bc5
diff --git a/.env.example b/.env.example
index e4e7a56ed5..5f85fb123b 100644
--- a/.env.example
+++ b/.env.example
@@ -43,6 +43,10 @@ RESEND_DOMAIN="carbon.ms"
# Cloudflare
CLOUDFLARE_TURNSTILE_SITE_KEY="1x00000000000000000000AA"
CLOUDFLARE_TURNSTILE_SECRET_KEY="********************"
+# Set to true once Supabase Auth captcha (Attack Protection -> Turnstile) is
+# enabled for the project — login actions then forward the Turnstile token to
+# GoTrue on the magic-link call instead of verifying it in-app.
+# SUPABASE_AUTH_CAPTCHA_ENABLED="false"
# Slack
SLACK_BOT_TOKEN="***********************"
diff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsx
index e85dcc08fd..9390f647b7 100644
--- a/apps/academy/app/routes/_auth+/login.tsx
+++ b/apps/academy/app/routes/_auth+/login.tsx
@@ -7,7 +7,13 @@ import {
SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID,
SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID
} from "@carbon/auth";
-import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
+import {
+ getMagicLinkErrorMessage,
+ sendMagicLink,
+ turnstileSiteKey,
+ verifyAuthSession,
+ verifyLoginCaptcha
+} from "@carbon/auth/auth.server";
import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
@@ -19,9 +25,11 @@ import {
Button,
Heading,
Separator,
+ TurnstileChallenge,
toast,
VStack
} from "@carbon/react";
+import { useState } from "react";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
@@ -50,7 +58,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
return {
hasOutlookAuth: !!SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID,
- hasGoogleAuth: !!SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID
+ hasGoogleAuth: !!SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID,
+ turnstileSiteKey
};
}
@@ -79,16 +88,26 @@ export async function action({ request }: ActionFunctionArgs) {
return error(validation.error, "Invalid email address");
}
- const { email } = validation.data;
+ const { email, turnstileToken } = validation.data;
+
+ const captchaError = await verifyLoginCaptcha(turnstileToken, ip);
+ if (captchaError) {
+ return data(
+ error(null, captchaError),
+ await flash(request, error(null, captchaError))
+ );
+ }
+
const user = await getUserByEmail(email);
if (user.data && user.data.active) {
- const magicLink = await sendMagicLink(email);
+ const magicLink = await sendMagicLink(email, turnstileToken);
- if (!magicLink) {
+ if (magicLink.error) {
+ const message = getMagicLinkErrorMessage(magicLink.error);
return data(
- error(magicLink, "Failed to send magic link"),
- await flash(request, error(magicLink, "Failed to send magic link"))
+ error(magicLink, message),
+ await flash(request, error(magicLink, message))
);
}
} else {
@@ -102,13 +121,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function LoginRoute() {
- const { hasOutlookAuth, hasGoogleAuth } = useLoaderData<typeof loader>();
+ const {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ turnstileSiteKey: siteKey
+ } = useLoaderData<typeof loader>();
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
const fetcher = useFetcher<
{ success: true } | { success: false; message: string }
>();
+ const [turnstileToken, setTurnstileToken] = useState<string>("");
const onSignInWithGoogle = async () => {
const { error } = await carbonClient.auth.signInWithOAuth({
@@ -164,6 +188,7 @@ export default function LoginRoute() {
method="post"
>
<Hidden name="redirectTo" value={redirectTo} type="hidden" />
+ <Hidden name="turnstileToken" value={turnstileToken} />
<VStack spacing={2}>
{fetcher.data?.success === false && fetcher.data?.message && (
<Alert variant="destructive">
@@ -209,7 +234,9 @@ export default function LoginRoute() {
<Input name="email" label="" placeholder="Email Address" />
<Submit
- isDisabled={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" || (!!siteKey && !turnstileToken)
+ }
isLoading={fetcher.state === "submitting"}
size="lg"
className="w-full"
@@ -218,6 +245,10 @@ export default function LoginRoute() {
>
Sign in with Email
</Submit>
+ <TurnstileChallenge
+ siteKey={siteKey ?? undefined}
+ onToken={setTurnstileToken}
+ />
</VStack>
</ValidatedForm>
)}
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index 8fb587f054..792dbf156b 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -1,8 +1,6 @@
import {
assertIsPost,
CarbonEdition,
- CLOUDFLARE_TURNSTILE_SECRET_KEY,
- CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
carbonClient,
error,
@@ -11,10 +9,13 @@ import {
RATE_LIMIT
} from "@carbon/auth";
import {
+ getMagicLinkErrorMessage,
logAuthEvent,
sendMagicLink,
signInWithBypassEmail,
- verifyAuthSession
+ turnstileSiteKey,
+ verifyAuthSession,
+ verifyLoginCaptcha
} from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
@@ -36,14 +37,13 @@ import {
Heading,
ItarLoginDisclaimer,
Separator,
+ TurnstileChallenge,
toast,
- useMode,
useMount,
VStack
} from "@carbon/react";
import { Edition } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { Turnstile } from "@marsidev/react-turnstile";
import {
browserSupportsWebAuthn,
startAuthentication
@@ -82,7 +82,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const cookieHeaders = await clearAuthCookies(request);
return data(
- { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth, hasSsoAuth },
+ {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ hasPasskeyAuth,
+ hasSsoAuth,
+ turnstileSiteKey
+ },
{ headers: cookieHeaders }
);
}
@@ -91,7 +97,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
hasOutlookAuth,
hasGoogleAuth,
hasPasskeyAuth,
- hasSsoAuth
+ hasSsoAuth,
+ turnstileSiteKey
};
}
@@ -146,35 +153,12 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- if (
- CarbonEdition === Edition.Cloud &&
- CLOUDFLARE_TURNSTILE_SITE_KEY !== "1x00000000000000000000AA"
- ) {
- const verifyResponse = await fetch(
- "https://challenges.cloudflare.com/turnstile/v0/siteverify",
- {
- method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- body: new URLSearchParams({
- secret: CLOUDFLARE_TURNSTILE_SECRET_KEY ?? "",
- response: turnstileToken ?? "",
- remoteip: ip
- })
- }
+ const captchaError = await verifyLoginCaptcha(turnstileToken, ip);
+ if (captchaError) {
+ return data(
+ error(null, captchaError),
+ await flash(request, error(null, captchaError))
);
-
- const verifyData = await verifyResponse.json();
- if (!verifyData.success) {
- return data(
- error(null, "Bot verification failed. Please try again."),
- await flash(
- request,
- error(null, "Bot verification failed. Please try again.")
- )
- );
- }
}
// Count this attempt against the account. If it tips the account past the
@@ -233,7 +217,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (user.data && user.data.active) {
- const magicLink = await sendMagicLink(email);
+ const magicLink = await sendMagicLink(email, turnstileToken);
if (magicLink.error) {
logAuthEvent("login_failed", {
@@ -241,9 +225,10 @@ export async function action({ request }: ActionFunctionArgs) {
ip,
reason: "magic link send failed"
});
+ const message = getMagicLinkErrorMessage(magicLink.error);
return data(
- error(magicLink, "Failed to send magic link"),
- await flash(request, error(magicLink, "Failed to send magic link"))
+ error(magicLink, message),
+ await flash(request, error(magicLink, message))
);
}
logAuthEvent("magic_link_sent", { actor: email, ip });
@@ -259,6 +244,19 @@ export async function action({ request }: ActionFunctionArgs) {
await flash(request, error(null, "Failed to sign in"))
);
} else {
+ // Signup verification codes go out via Resend, never GoTrue.
+ const signupCaptchaError = await verifyLoginCaptcha(
+ turnstileToken,
+ ip,
+ "app"
+ );
+ if (signupCaptchaError) {
+ return data(
+ error(null, signupCaptchaError),
+ await flash(request, error(null, signupCaptchaError))
+ );
+ }
+
// User doesn't exist, send verification code for signup
const verificationSent = await sendVerificationCode(email);
@@ -275,8 +273,13 @@ export async function action({ request }: ActionFunctionArgs) {
export default function LoginRoute() {
const { t } = useLingui();
- const { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth, hasSsoAuth } =
- useLoaderData<typeof loader>();
+ const {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ hasPasskeyAuth,
+ hasSsoAuth,
+ turnstileSiteKey: siteKey
+ } = useLoaderData<typeof loader>();
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
@@ -291,7 +294,6 @@ export default function LoginRoute() {
const conditionalAbortRef = useRef<AbortController | null>(null);
const fetcher = useFetcher<Result & { mode?: string; email?: string }>();
- const theme = useMode();
useEffect(() => {
if (fetcher.data?.success && fetcher.data.mode) {
@@ -650,7 +652,7 @@ export default function LoginRoute() {
isDisabled={
fetcher.state !== "idle" ||
ssoLoading ||
- (!!CLOUDFLARE_TURNSTILE_SITE_KEY && !turnstileToken)
+ (!!siteKey && !turnstileToken)
}
isLoading={fetcher.state === "submitting" || ssoLoading}
hideShortcutKey
@@ -661,19 +663,10 @@ export default function LoginRoute() {
>
<Trans>Continue</Trans>
</Submit>
- {!!CLOUDFLARE_TURNSTILE_SITE_KEY && (
- <div className="w-full flex justify-center">
- <Turnstile
- siteKey={CLOUDFLARE_TURNSTILE_SITE_KEY}
- onSuccess={(token) => setTurnstileToken(token)}
- onError={() => setTurnstileToken("")}
- onExpire={() => setTurnstileToken("")}
- options={{
- theme: theme === "dark" ? "dark" : "light"
- }}
- />
- </div>
- )}
+ <TurnstileChallenge
+ siteKey={siteKey ?? undefined}
+ onToken={setTurnstileToken}
+ />
</VStack>
</ValidatedForm>
)}
diff --git a/apps/erp/package.json b/apps/erp/package.json
index ab7046b157..4288a4f26d 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -43,7 +43,6 @@
"@internationalized/date": "catalog:",
"@lingui/core": "catalog:",
"@lingui/react": "catalog:",
- "@marsidev/react-turnstile": "1.5.0",
"@modelcontextprotocol/sdk": "1.29.0",
"@monaco-editor/react": "4.7.0",
"@nanostores/react": "catalog:",
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index 50e1dca3c3..110ee33fdf 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -9,9 +9,12 @@ import {
RATE_LIMIT
} from "@carbon/auth";
import {
+ getMagicLinkErrorMessage,
logAuthEvent,
sendMagicLink,
- verifyAuthSession
+ turnstileSiteKey,
+ verifyAuthSession,
+ verifyLoginCaptcha
} from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
@@ -31,6 +34,7 @@ import {
Heading,
ItarLoginDisclaimer,
Separator,
+ TurnstileChallenge,
toast,
useMount,
VStack
@@ -75,12 +79,24 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
const cookieHeaders = await clearAuthCookies(request);
return data(
- { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth, hasSsoAuth },
+ {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ hasPasskeyAuth,
+ hasSsoAuth,
+ turnstileSiteKey
+ },
{ headers: cookieHeaders }
);
}
- return { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth, hasSsoAuth };
+ return {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ hasPasskeyAuth,
+ hasSsoAuth,
+ turnstileSiteKey
+ };
}
export async function action({ request }: ActionFunctionArgs) {
@@ -108,7 +124,15 @@ export async function action({ request }: ActionFunctionArgs) {
return error(validation.error, "Invalid email address");
}
- const { email } = validation.data;
+ const { email, turnstileToken } = validation.data;
+
+ const captchaError = await verifyLoginCaptcha(turnstileToken, ip);
+ if (captchaError) {
+ return data(
+ error(null, captchaError),
+ await flash(request, error(null, captchaError))
+ );
+ }
// Per-account lockout (NIST 800-171 3.1.8) — layered ON TOP of the IP limit
// above, keyed by the normalized email. Rejects with a GENERIC message that
@@ -164,14 +188,21 @@ export async function action({ request }: ActionFunctionArgs) {
const user = await getUserByEmail(email);
if (user.data && user.data.active) {
- const magicLink = await sendMagicLink(email);
+ const magicLink = await sendMagicLink(email, turnstileToken);
- if (!magicLink) {
+ if (magicLink.error) {
+ logAuthEvent("login_failed", {
+ actor: email,
+ ip,
+ reason: "magic link send failed"
+ });
+ const message = getMagicLinkErrorMessage(magicLink.error);
return data(
- error(magicLink, "Failed to send magic link"),
- await flash(request, error(magicLink, "Failed to send magic link"))
+ error(magicLink, message),
+ await flash(request, error(magicLink, message))
);
}
+ logAuthEvent("magic_link_sent", { actor: email, ip });
} else {
return data(
{ success: false, message: "Invalid email/password combination" },
@@ -184,8 +215,13 @@ export async function action({ request }: ActionFunctionArgs) {
export default function LoginRoute() {
const { t } = useLingui();
- const { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth, hasSsoAuth } =
- useLoaderData<typeof loader>();
+ const {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ hasPasskeyAuth,
+ hasSsoAuth,
+ turnstileSiteKey: siteKey
+ } = useLoaderData<typeof loader>();
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
@@ -195,6 +231,7 @@ export default function LoginRoute() {
{ success: true } | { success: false; message: string }
>();
+ const [turnstileToken, setTurnstileToken] = useState<string>("");
const [passkeySupported, setPasskeySupported] = useState(false);
const [passkeyLoading, setPasskeyLoading] = useState(false);
const [ssoLoading, setSsoLoading] = useState(false);
@@ -439,6 +476,7 @@ export default function LoginRoute() {
onSubmit={onSubmitEmail}
>
<Hidden name="redirectTo" value={redirectTo} type="hidden" />
+ <Hidden name="turnstileToken" value={turnstileToken} />
<VStack spacing={2}>
{((fetcher.data?.success === false && fetcher.data?.message) ||
ssoError) && (
@@ -513,7 +551,11 @@ export default function LoginRoute() {
/>
<Submit
- isDisabled={fetcher.state !== "idle" || ssoLoading}
+ isDisabled={
+ fetcher.state !== "idle" ||
+ ssoLoading ||
+ (!!siteKey && !turnstileToken)
+ }
isLoading={fetcher.state === "submitting" || ssoLoading}
hideShortcutKey
size="lg"
@@ -523,6 +565,10 @@ export default function LoginRoute() {
>
<Trans>Continue</Trans>
</Submit>
+ <TurnstileChallenge
+ siteKey={siteKey ?? undefined}
+ onToken={setTurnstileToken}
+ />
</VStack>
</ValidatedForm>
)}
diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsx
index c67b488683..22553a8425 100644
--- a/apps/starter/app/routes/_public+/login.tsx
+++ b/apps/starter/app/routes/_public+/login.tsx
@@ -7,7 +7,13 @@ import {
SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID,
SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID
} from "@carbon/auth";
-import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
+import {
+ getMagicLinkErrorMessage,
+ sendMagicLink,
+ turnstileSiteKey,
+ verifyAuthSession,
+ verifyLoginCaptcha
+} from "@carbon/auth/auth.server";
import { flash, getAuthSession } from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";
@@ -19,9 +25,11 @@ import {
Button,
Heading,
Separator,
+ TurnstileChallenge,
toast,
VStack
} from "@carbon/react";
+import { useState } from "react";
import { LuCircleAlert } from "react-icons/lu";
import type {
ActionFunctionArgs,
@@ -50,7 +58,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
return {
hasOutlookAuth: !!SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID,
- hasGoogleAuth: !!SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID
+ hasGoogleAuth: !!SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID,
+ turnstileSiteKey
};
}
@@ -79,16 +88,26 @@ export async function action({ request }: ActionFunctionArgs) {
return error(validation.error, "Invalid email address");
}
- const { email } = validation.data;
+ const { email, turnstileToken } = validation.data;
+
+ const captchaError = await verifyLoginCaptcha(turnstileToken, ip);
+ if (captchaError) {
+ return data(
+ error(null, captchaError),
+ await flash(request, error(null, captchaError))
+ );
+ }
+
const user = await getUserByEmail(email);
if (user.data && user.data.active) {
- const magicLink = await sendMagicLink(email);
+ const magicLink = await sendMagicLink(email, turnstileToken);
- if (!magicLink) {
+ if (magicLink.error) {
+ const message = getMagicLinkErrorMessage(magicLink.error);
return data(
- error(magicLink, "Failed to send magic link"),
- await flash(request, error(magicLink, "Failed to send magic link"))
+ error(magicLink, message),
+ await flash(request, error(magicLink, message))
);
}
} else {
@@ -102,13 +121,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function LoginRoute() {
- const { hasOutlookAuth, hasGoogleAuth } = useLoaderData<typeof loader>();
+ const {
+ hasOutlookAuth,
+ hasGoogleAuth,
+ turnstileSiteKey: siteKey
+ } = useLoaderData<typeof loader>();
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get("redirectTo") ?? undefined;
const fetcher = useFetcher<
{ success: true } | { success: false; message: string }
>();
+ const [turnstileToken, setTurnstileToken] = useState<string>("");
const onSignInWithGoogle = async () => {
const { error } = await carbonClient.auth.signInWithOAuth({
@@ -173,6 +197,7 @@ export default function LoginRoute() {
method="post"
>
<Hidden name="redirectTo" value={redirectTo} type="hidden" />
+ <Hidden name="turnstileToken" value={turnstileToken} />
<VStack spacing={2}>
{fetcher.data?.success === false && fetcher.data?.message && (
<Alert variant="destructive">
@@ -218,7 +243,9 @@ export default function LoginRoute() {
<Input name="email" label="" placeholder="Email Address" />
<Submit
- isDisabled={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" || (!!siteKey && !turnstileToken)
+ }
isLoading={fetcher.state === "submitting"}
size="lg"
className="w-full"
@@ -227,6 +254,10 @@ export default function LoginRoute() {
>
Sign in with Email
</Submit>
+ <TurnstileChallenge
+ siteKey={siteKey ?? undefined}
+ onToken={setTurnstileToken}
+ />
</VStack>
</ValidatedForm>
)}
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index c51b750a45..9838272d96 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -15,10 +15,13 @@ import { createHash } from "crypto";
import { redirect } from "react-router";
import {
CarbonEdition,
+ CLOUDFLARE_TURNSTILE_SECRET_KEY,
+ CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
REFRESH_ACCESS_TOKEN_THRESHOLD,
SESSION_IDLE_LOCK_MS,
STRIPE_BYPASS_COMPANY_IDS,
+ SUPABASE_AUTH_CAPTCHA_ENABLED,
VERCEL_URL
} from "../config/env";
import { getCarbon } from "../lib/supabase";
@@ -455,15 +458,95 @@ export async function sendInviteByEmail(
});
}
-export async function sendMagicLink(email: string) {
+const TURNSTILE_TEST_SITE_KEY = "1x00000000000000000000AA";
+const CAPTCHA_FAILED_MESSAGE = "Bot verification failed. Please try again.";
+
+// Cloud with a real site key requires a Turnstile token on login.
+export const requiresTurnstile =
+ CarbonEdition === Edition.Cloud &&
+ Boolean(CLOUDFLARE_TURNSTILE_SITE_KEY) &&
+ CLOUDFLARE_TURNSTILE_SITE_KEY !== TURNSTILE_TEST_SITE_KEY;
+
+// For login loaders: render the widget whenever a key is configured — the
+// test key gives previews an auto-passing widget. Enforcement (requiresTurnstile)
+// is deliberately narrower, so a widget without enforcement is possible but
+// enforcement without a widget is not.
+export const turnstileSiteKey = CLOUDFLARE_TURNSTILE_SITE_KEY ?? null;
+
+export async function sendMagicLink(email: string, turnstileToken?: string) {
return getCarbonServiceRole().auth.signInWithOtp({
email,
options: {
- emailRedirectTo: `${VERCEL_URL}/callback`
+ emailRedirectTo: `${VERCEL_URL}/callback`,
+ // GoTrue verifies the token itself when Supabase Auth captcha is on
+ ...(SUPABASE_AUTH_CAPTCHA_ENABLED && turnstileToken
+ ? { captchaToken: turnstileToken }
+ : {})
}
});
}
+// Turnstile tokens are single-use, so exactly one side verifies: "gotrue"
+// sends verify in-app only when GoTrue won't; "app" sends (Resend, which
+// GoTrue never sees) only when the earlier "gotrue" gate stood down.
+// Returns a user-facing message on failure, null when the gate passes.
+export async function verifyLoginCaptcha(
+ turnstileToken: string | undefined,
+ ip: string,
+ send: "gotrue" | "app" = "gotrue"
+): Promise<string | null> {
+ if (!requiresTurnstile) return null;
+ const appVerifies =
+ send === "gotrue"
+ ? !SUPABASE_AUTH_CAPTCHA_ENABLED
+ : SUPABASE_AUTH_CAPTCHA_ENABLED;
+ if (!appVerifies) return null;
+ return (await verifyTurnstileToken(turnstileToken, ip))
+ ? null
+ : CAPTCHA_FAILED_MESSAGE;
+}
+
+export function getMagicLinkErrorMessage(error: { code?: string }): string {
+ switch (error.code) {
+ case "captcha_failed":
+ return CAPTCHA_FAILED_MESSAGE;
+ case "over_email_send_rate_limit":
+ case "over_request_rate_limit":
+ return "Too many sign-in attempts. Please try again later.";
+ default:
+ return "Failed to send magic link";
+ }
+}
+
+async function verifyTurnstileToken(
+ token: string | undefined,
+ remoteip: string
+): Promise<boolean> {
+ try {
+ const response = await fetch(
+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",
+ {
+ method: "POST",
+ signal: AbortSignal.timeout(5000),
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ body: new URLSearchParams({
+ secret: CLOUDFLARE_TURNSTILE_SECRET_KEY ?? "",
+ response: token ?? "",
+ // the client address, not the full x-forwarded-for proxy chain
+ remoteip: remoteip.split(",")[0]?.trim() ?? ""
+ })
+ }
+ );
+ const result = await response.json();
+ return Boolean(result.success);
+ } catch (e) {
+ log.error("Turnstile siteverify request failed", { error: e });
+ return false;
+ }
+}
+
export async function signInWithBypassEmail(
email: string
): Promise<AuthSession | null> {
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index e2027c75f1..3dd047b615 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -343,6 +343,15 @@ export const SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID = getEnv(
isSecret: true
}
);
+// True once Supabase Auth captcha (Attack Protection) is enabled — login
+// actions then forward Turnstile tokens to GoTrue instead of verifying in-app.
+export const SUPABASE_AUTH_CAPTCHA_ENABLED = parseBoolean(
+ getEnv("SUPABASE_AUTH_CAPTCHA_ENABLED", {
+ isRequired: false,
+ isSecret: false
+ }),
+ false
+);
export const SESSION_SECRET = getEnv("SESSION_SECRET");
export const SESSION_KEY = "auth";
export const SESSION_ERROR_KEY = "error";
diff --git a/packages/react/package.json b/packages/react/package.json
index 97b0bf1e84..3e144dfb84 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -121,6 +121,7 @@
"peerDependencies": {
"@internationalized/date": "catalog:",
"@lingui/react": "catalog:",
+ "@marsidev/react-turnstile": "catalog:",
"framer-motion": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
diff --git a/packages/react/src/Turnstile.tsx b/packages/react/src/Turnstile.tsx
new file mode 100644
index 0000000000..55f54278b3
--- /dev/null
+++ b/packages/react/src/Turnstile.tsx
@@ -0,0 +1,31 @@
+import { Turnstile } from "@marsidev/react-turnstile";
+import { useMode } from "./hooks/useMode";
+
+type TurnstileChallengeProps = {
+ siteKey?: string;
+ onToken: (token: string) => void;
+};
+
+// Clears the token on error/expiry so callers can gate submission on it.
+export function TurnstileChallenge({
+ siteKey,
+ onToken
+}: TurnstileChallengeProps) {
+ const mode = useMode();
+
+ if (!siteKey) return null;
+
+ return (
+ <div className="w-full flex justify-center">
+ <Turnstile
+ siteKey={siteKey}
+ onSuccess={onToken}
+ onError={() => onToken("")}
+ onExpire={() => onToken("")}
+ options={{
+ theme: mode === "dark" ? "dark" : "light"
+ }}
+ />
+ </div>
+ );
+}
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index dc6b8af53a..c4ff246a6c 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -348,6 +348,7 @@ import {
usePickOrderOptions
} from "./TrackedEntityPicker";
import { TruncatedTooltipText } from "./TruncatedTooltipText";
+import { TurnstileChallenge } from "./Turnstile";
import { TVColorBars } from "./TVColorBars";
import { cn } from "./utils/cn";
import { hasOpenDialog, isInsideTopmostDialog } from "./utils/dialog";
@@ -633,6 +634,7 @@ export {
TimePicker,
Toaster,
Toggle,
+ TurnstileChallenge,
ToggleGroup,
ToggleGroupItem,
TrackedEntityPicker,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b793b501ac..002d352238 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -51,6 +51,9 @@ catalogs:
'@logtape/testing':
specifier: 2.2.3
version: 2.2.3
+ '@marsidev/react-turnstile':
+ specifier: 1.5.0
+ version: 1.5.0
'@nanostores/react':
specifier: 0.7.3
version: 0.7.3
@@ -359,7 +362,7 @@ importers:
version: 1.40.0
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
cookie:
specifier: 'catalog:'
version: 1.1.1
@@ -396,7 +399,7 @@ importers:
'@react-router/dev':
specifier: 'catalog:'
'@types/aws-lambda':
specifier: 8.10.152
version: 8.10.152
@@ -447,10 +450,10 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
zod:
specifier: 'catalog:'
version: 4.5.4
@@ -735,9 +738,6 @@ importers:
'@lingui/react':
specifier: 'catalog:'
- '@marsidev/react-turnstile':
- specifier: 1.5.0
'@modelcontextprotocol/sdk':
specifier: 1.29.0
version: 1.29.0([email protected])
@@ -767,7 +767,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -812,7 +812,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -1044,16 +1044,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -1113,13 +1113,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -3066,6 +3066,9 @@ importers:
'@lingui/react':
specifier: 'catalog:'
+ '@marsidev/react-turnstile':
+ specifier: 'catalog:'
'@nanostores/react':
specifier: 'catalog:'
@@ -17250,7 +17253,7 @@ snapshots:
'@babel/traverse': 7.29.0
'@babel/types': 7.29.0
convert-source-map: 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 7.7.4
@@ -17270,7 +17273,7 @@ snapshots:
'@babel/types': 7.29.0
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 7.7.4
@@ -17440,7 +17443,7 @@ snapshots:
'@babel/parser': 7.29.2
'@babel/template': 7.28.6
'@babel/types': 7.29.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
globals: 11.12.0
transitivePeerDependencies:
- supports-color
@@ -17453,7 +17456,7 @@ snapshots:
'@babel/parser': 7.29.2
'@babel/template': 7.28.6
'@babel/types': 7.29.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -18472,6 +18475,16 @@ snapshots:
- supports-color
- typescript
+ dependencies:
+ '@lingui/cli': 5.9.4([email protected])([email protected])
+ '@lingui/conf': 5.9.4([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - typescript
+
dependencies:
'@lingui/cli': 5.9.4([email protected])([email protected])
@@ -18833,7 +18846,7 @@ snapshots:
dependencies:
'@oclif/core': 4.11.7
ansis: 3.17.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
npm: 11.17.0
npm-package-arg: 11.0.3
npm-run-path: 5.3.0
@@ -22346,7 +22359,7 @@ snapshots:
'@react-pdf/primitives': 4.2.0
'@react-pdf/stylesheet': 6.1.4
dependencies:
'@babel/core': 7.29.0
'@babel/generator': 7.29.1
@@ -22376,7 +22389,7 @@ snapshots:
semver: 7.7.4
tinyglobby: 0.2.17
valibot: 1.3.1([email protected])
optionalDependencies:
@@ -22446,6 +22459,56 @@ snapshots:
- tsx
- yaml
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/generator': 7.29.1
+ '@babel/parser': 7.29.2
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/preset-typescript': 7.28.5(@babel/[email protected])
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ '@remix-run/node-fetch-server': 0.13.1
+ arg: 5.0.2
+ babel-dead-code-elimination: 1.0.12
+ chokidar: 4.0.3
+ dedent: 1.7.2([email protected])
+ es-module-lexer: 1.7.0
+ exit-hook: 2.2.1
+ isbot: 5.1.37
+ jsesc: 3.0.2
+ lodash: 4.18.1
+ p-map: 7.0.4
+ pathe: 1.1.2
+ picocolors: 1.1.1
+ pkg-types: 2.3.0
+ prettier: 3.8.1
+ react-refresh: 0.14.2
+ semver: 7.7.4
+ tinyglobby: 0.2.17
+ valibot: 1.3.1([email protected])
+ optionalDependencies:
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - jiti
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@babel/core': 7.29.0
@@ -22518,9 +22581,15 @@ snapshots:
optionalDependencies:
typescript: 5.8.3
dependencies:
+ optionalDependencies:
+ typescript: 5.8.3
+
+ dependencies:
optionalDependencies:
typescript: 5.8.3
@@ -23809,6 +23878,13 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.3.0
+ dependencies:
+ '@tailwindcss/node': 4.3.0
+ '@tailwindcss/oxide': 4.3.0
+ tailwindcss: 4.3.0
+
dependencies:
'@tailwindcss/node': 4.3.0
@@ -24588,7 +24664,7 @@ snapshots:
dependencies:
'@types/node': 22.19.7
tapable: 2.3.3
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
@@ -24686,6 +24762,16 @@ snapshots:
react-dom: 18.3.1([email protected])
ts-morph: 12.0.0
+ dependencies:
+ '@vercel/static-config': 3.2.0
+ isbot: 5.1.37
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ ts-morph: 12.0.0
+
dependencies:
@@ -24832,6 +24918,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 4.1.6
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 4.1.6
@@ -25291,7 +25385,7 @@ snapshots:
dependencies:
bytes: 3.1.2
content-type: 1.0.5
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
http-errors: 2.0.1
iconv-lite: 0.7.2
on-finished: 2.4.1
@@ -26158,7 +26252,7 @@ snapshots:
dependencies:
'@socket.io/component-emitter': 3.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io-parser: 5.2.3
ws: 8.21.0
xmlhttprequest-ssl: 2.1.2
@@ -26178,7 +26272,7 @@ snapshots:
base64id: 2.0.0
cookie: 0.7.2
cors: 2.8.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io-parser: 5.2.3
ws: 8.21.0
transitivePeerDependencies:
@@ -26593,7 +26687,7 @@ snapshots:
content-type: 1.0.5
cookie: 0.7.2
cookie-signature: 1.2.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
depd: 2.0.0
encodeurl: 2.0.0
escape-html: 1.0.3
@@ -26722,7 +26816,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
encodeurl: 2.0.0
escape-html: 1.0.3
on-finished: 2.4.1
@@ -27287,14 +27381,14 @@ snapshots:
dependencies:
agent-base: 7.1.4
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
agent-base: 9.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -27407,7 +27501,7 @@ snapshots:
canonicalize: 1.0.8
chalk: 4.1.2
cross-fetch: 4.1.0([email protected])
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
hash.js: 1.1.7
json-stringify-safe: 5.0.1
ms: 2.1.3
@@ -27445,7 +27539,7 @@ snapshots:
canonicalize: 1.0.8
chalk: 4.1.2
cross-fetch: 4.1.0([email protected])
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
hash.js: 1.1.7
json-stringify-safe: 5.0.1
ms: 2.1.3
@@ -27507,7 +27601,7 @@ snapshots:
dependencies:
'@ioredis/commands': 1.5.1
cluster-key-slot: 1.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
denque: 2.1.0
lodash.defaults: 4.2.0
lodash.isarguments: 3.1.0
@@ -28636,7 +28730,7 @@ snapshots:
dependencies:
'@types/debug': 4.1.13
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
decode-named-character-reference: 1.3.0
devlop: 1.1.0
micromark-core-commonmark: 2.0.3
@@ -28700,15 +28794,15 @@ snapshots:
dependencies:
'@jridgewell/trace-mapping': 0.3.31
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.48.0
optionalDependencies:
- esbuild: 0.25.0
+ esbuild: 0.28.0
lightningcss: 1.32.0
postcss: 8.5.18
@@ -30239,7 +30333,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
module-details-from-path: 1.0.4
resolve: 1.22.11
transitivePeerDependencies:
@@ -30247,7 +30341,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
module-details-from-path: 1.0.4
transitivePeerDependencies:
- supports-color
@@ -30366,7 +30460,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
depd: 2.0.0
is-promise: 4.0.0
parseurl: 1.3.3
@@ -30474,7 +30568,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
encodeurl: 2.0.0
escape-html: 1.0.3
etag: 1.8.1
@@ -30654,7 +30748,7 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
ws: 8.21.0
transitivePeerDependencies:
- bufferutil
@@ -30675,7 +30769,7 @@ snapshots:
dependencies:
'@socket.io/component-emitter': 3.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -30684,7 +30778,7 @@ snapshots:
accepts: 1.3.8
base64id: 2.0.0
cors: 2.8.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
engine.io: 6.6.9
socket.io-adapter: 2.5.8
socket.io-parser: 4.2.7
@@ -31143,7 +31237,7 @@ snapshots:
dependencies:
callsites: 3.1.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
is-observable: 2.1.0
observable-fns: 0.6.1
optionalDependencies:
@@ -31284,7 +31378,7 @@ snapshots:
cac: 6.7.14
chokidar: 4.0.3
consola: 3.4.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
esbuild: 0.27.7
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
@@ -31312,7 +31406,7 @@ snapshots:
cac: 6.7.14
chokidar: 4.0.3
consola: 3.4.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
esbuild: 0.27.7
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
@@ -31618,7 +31712,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -31639,7 +31733,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -31668,14 +31762,25 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
'@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
'@types/babel__core': 7.20.5
babel-plugin-macros: 3.1.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
+ '@types/babel__core': 7.20.5
+ babel-plugin-macros: 3.1.0
transitivePeerDependencies:
- supports-color
@@ -31775,7 +31880,7 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -31784,6 +31889,22 @@ snapshots:
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 24.12.2
+ esbuild: 0.28.0
+ fsevents: 2.3.3
+ jiti: 2.7.0
+ terser: 5.48.0
+ tsx: 4.21.0
+ yaml: 2.8.3
+
+ dependencies:
+ lightningcss: 1.32.0
+ picomatch: 4.0.4
+ postcss: 8.5.18
+ rolldown: 1.0.3
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ '@types/node': 26.1.0
esbuild: 0.27.7
fsevents: 2.3.3
jiti: 2.7.0
@@ -31947,6 +32068,34 @@ snapshots:
transitivePeerDependencies:
- msw
+ dependencies:
+ '@vitest/expect': 4.1.6
+ '@vitest/pretty-format': 4.1.6
+ '@vitest/runner': 4.1.6
+ '@vitest/snapshot': 4.1.6
+ '@vitest/spy': 4.1.6
+ '@vitest/utils': 4.1.6
+ es-module-lexer: 2.3.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 4.0.0
+ tinybench: 2.9.0
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
+ tinyrainbow: 3.1.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ '@types/node': 26.1.0
+ transitivePeerDependencies:
+ - msw
+
dependencies:
'@vitest/expect': 4.1.6
@@ -32013,7 +32162,7 @@ snapshots:
dependencies:
'@types/estree': 1.0.8
'@types/json-schema': 7.0.15
@@ -32031,7 +32180,7 @@ snapshots:
graceful-fs: 4.2.11
loader-runner: 4.3.2
mime-db: 1.54.0
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.3
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index d79a4aa1a0..526684a095 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -65,6 +65,7 @@ catalog:
'@lingui/macro': 5.9.4
'@lingui/react': 5.9.4
'@lingui/vite-plugin': 5.9.4
+ '@marsidev/react-turnstile': 1.5.0
'@logtape/logtape': 2.2.3
'@logtape/redaction': 2.2.3
'@logtape/testing': 2.2.3