Skip to Content

Captcha

Captcha plugin

The Captcha Plugin integrates bot protection into your Entro Auth system by adding captcha verification for key endpoints. This plugin ensures that only human users can perform actions like signing up, signing in, or resetting passwords. The following providers are currently supported:

The default endpoints cover Email & Password authentication. Other authentication methods need an explicit endpoints array. Vercel BotID also needs the client-side setup below.

Installation

Install dependencies (Optional)

If you are using Vercel BotID, install its SDK in your application:

npm install botid

Add the plugin to your auth config

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { captcha } from "@entro314labs/entro-auth/plugins"; 

export const auth = entroAuth({
    plugins: [
        captcha({ 
            provider: "cloudflare-turnstile", // or google-recaptcha, hcaptcha, captchafox
            secretKey: process.env.TURNSTILE_SECRET_KEY!, 
        }), 
    ],
});

Send the token for token-based providers

The x-captcha-user-remote-ip header is no longer required—IP is now auto-detected server-side.

For token-based providers, add the captcha token to requests for protected endpoints. This example shows a signIn request:

import { authClient } from "@/lib/auth-client"

await authClient.signIn.email({
    email: "user@example.com",
    password: "secure-password",
    fetchOptions: { 
        headers: { 
            "x-captcha-response": turnstileToken, 
        }, 
    }, 
});

Providers

Vercel BotID

BotID requires a Vercel deployment and client-side setup. Follow Vercel's setup guide for the rewrites and client integration appropriate to your framework. The Entro Auth plugin does not use a secretKey or an x-captcha-response header:

auth.ts
import { checkBotId } from "botid/server";
import { entroAuth } from "@entro314labs/entro-auth";
import { captcha } from "@entro314labs/entro-auth/plugins";

export const auth = entroAuth({
    plugins: [
        captcha({
            provider: "vercel-botid",
            checkBotId,
        }),
    ],
});

When using initBotId, protect Entro Auth's default auth routes at their actual request paths:

import { initBotId } from "botid/client/core";

initBotId({
    protect: [
        { path: "/api/auth/sign-up/email", method: "POST" },
        { path: "/api/auth/sign-in/email", method: "POST" },
        { path: "/api/auth/request-password-reset", method: "POST" },
    ],
});

BotID uses the browser's full request path. The plugin's endpoints option omits the Entro Auth base path, as in /sign-in/email. Keep both in sync if you change basePath or endpoints.

With BotID initialized in the browser, sign in normally without a captcha token header:

import { authClient } from "@/lib/auth-client";

const { data, error } = await authClient.signIn.email({
    email: "user@example.com",
    password: "secure-password",
});

BotID does not support native HTML form submissions.

Local development allows requests by default, so verify the full flow on Vercel before relying on it in production. For route-specific detection levels, follow Vercel's advanced configuration.

Turnstile in the browser

A Turnstile token is good for one request, so a form needs one ready before each request the captcha guards, and the next one straight after. createTurnstileWidget does that: it loads Cloudflare's script once, renders the widget in an element of yours (out of sight unless the visitor has to do something), and gives the token out as the headers of the request.

import { createTurnstileWidget } from "@entro314labs/entro-auth/client/plugins";
import { authClient } from "@/lib/auth-client";

const widget = createTurnstileWidget(document.querySelector("#captcha")!, {
    siteKey: "0x4AAAAAAA...", // the public key
});

await authClient.signIn.email(
    { email, password },
    { headers: await widget.take() },
);

take() waits for a token when none is ready, and rejects with an error whose code says why, so the form can say it in its own words: CAPTCHA_WIDGET_FAILED (the script did not load, or the widget reported an error; providerCode is Cloudflare's own), CAPTCHA_WIDGET_TIMEOUT (nothing came within timeout, 30 seconds by default) or CAPTCHA_WIDGET_REMOVED. isCaptchaWidgetError tells them from the request's own errors. remove() takes the widget off the page.

In React, make it when the element mounts and remove it when it goes:

// The element is state, not a ref: a form inside a dialog mounts after the
// first effect has run, and the widget is made when the element appears.
const [element, setElement] = useState<HTMLDivElement | null>(null);
const widget = useRef<CaptchaWidget | null>(null);

useEffect(() => {
    if (!element) return;
    const made = createTurnstileWidget(element, { siteKey });
    widget.current = made;
    return () => {
        widget.current = null;
        made.remove();
    };
}, [element]);

// in the submit handler: { headers: await widget.current?.take() }
// in the form: <div ref={setElement} />

Take the token before the first of two requests that must both succeed (making an account, then signing it in): failing the captcha in between would leave the first one done and nobody signed in.

A real Turnstile key refuses an automated browser, so an end-to-end test of the form needs Cloudflare's test keys.

Native apps

A native app has no page to put the widget on. For Cloudflare Turnstile the plugin can serve one: with challengePage, GET /captcha/challenge under your auth base path answers a small page that runs the widget and hands its token to the web view showing it.

auth.ts
captcha({
    provider: "cloudflare-turnstile",
    secretKey: process.env.TURNSTILE_SECRET_KEY!,
    challengePage: { siteKey: process.env.TURNSTILE_SITE_KEY! }, 
})

The page is served by your own site, so the widget's hostname is the one your site key already allows. The app shows it in a web view and reads what it posts with readCaptchaChallengeMessage. With react-native-webview:

bot-check.tsx
import {
    CAPTCHA_CHALLENGE_PATH,
    CAPTCHA_CHALLENGE_RESET_SCRIPT,
    CAPTCHA_RESPONSE_HEADER,
    readCaptchaChallengeMessage,
} from "@entro314labs/entro-auth/client/plugins";
import { useRef, useState } from "react";
import { WebView } from "react-native-webview";

export function BotCheck({ onToken }: { onToken: (token: string | null) => void }) {
    const [interactive, setInteractive] = useState(false);
    return (
        <WebView
            source={{ uri: `https://example.com/api/auth${CAPTCHA_CHALLENGE_PATH}` }}
            // Out of sight unless the visitor has to do something.
            style={interactive ? { height: 80 } : { height: 0 }}
            onMessage={(event) => {
                const message = readCaptchaChallengeMessage(event.nativeEvent.data);
                if (message?.type === "token") onToken(message.token);
                if (message?.type === "expired") onToken(null);
                if (message?.type === "interactive") setInteractive(true);
                if (message?.type === "idle") setInteractive(false);
            }}
        />
    );
}

Send the token as a browser would, in the x-captcha-response header (CAPTCHA_RESPONSE_HEADER). A token is good for one request: after spending it, run CAPTCHA_CHALLENGE_RESET_SCRIPT in the web view (webView.injectJavaScript(...)) and wait for the next token message.

  • The page posts five kinds of message: token, expired, error (with the provider's code), interactive when the visitor has to do something, and idle when they are done.
  • It has no inline script or style, so it runs under a Content-Security-Policy that names origins. A policy your application sets on this path has to allow https://challenges.cloudflare.com for scripts and frames.
  • Anyone can open the page, as anyone can open a page of your site that carries the widget. A token it gives out is still only good where your server checks it.
  • Without challengePage, and for the other providers, the path answers 404.

How it works

The plugin acts as a middleware: it intercepts requests to configured endpoints (see endpoints in the Plugin Options section).

it validates the captcha token on the server, by calling the captcha provider's /siteverify.

Vercel BotID is the exception: it uses the supplied checkBotId function instead of a captcha token or /siteverify call.

  • if the token is missing, gets rejected by the captcha provider, or if the /siteverify endpoint is unavailable, the plugin returns an error and interrupts the request.
  • if the token is accepted by the captcha provider, the middleware returns undefined, meaning the request is allowed to proceed.
  • for Vercel BotID, the request is rejected when checkBotId (or your custom validateRequest) determines it's a bot, and allowed to proceed otherwise.

Plugin Options

  • provider (required): your captcha provider.
  • secretKey (required for all providers except vercel-botid): your provider's secret key used for the server-side validation.
  • endpoints (optional): Choose which paths require CAPTCHA. By default, CAPTCHA protects /sign-up/email, /sign-in/email, and /request-password-reset. Requests to other paths don't require CAPTCHA. When you set endpoints, include every path you want to protect because it replaces the defaults. You can use exact paths or wildcard patterns like /sign-in/* for one segment and /sign-in/** for nested routes. An endpoint that still answers under an older name is protected under that name too: listing /email-otp/request-password-reset also covers /forget-password/email-otp.
  • minScore (optional - only Google ReCAPTCHA v3): minimum score threshold. Default is 0.5.
  • siteKey (optional - only hCaptcha and CaptchaFox): prevents tokens issued on one sitekey from being redeemed elsewhere.
  • siteVerifyURLOverride (optional - token-based providers only): overrides the captcha verification URL.
  • challengePage (optional - only Cloudflare Turnstile): { siteKey }. Serves the hosted challenge page for native apps.
  • checkBotId (required for Vercel BotID): Vercel's server-side check function, imported from botid/server in your application. Wrap it in a function if you need to pass SDK options.
  • validateRequest (optional - only Vercel BotID): custom validation logic. Return true to allow the request, false to reject it. By default, only results with isBot: false are allowed.

On this page