Add a captcha
For: an app developer whose sign-up or mail flows get traffic from bots.
What it does: core asks for a captcha token on the flows that send mail or write rows, after their per-IP limit.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- A Cloudflare account with a Turnstile widget, for its site key and its secret key.
- Add
@authtempo/captcha-turnstileto the API. - Store the secret key in the secret store of the API.
- Set
captcha.porttocreateTurnstileCaptcha({ secretKey, siteKey }). - Set
captcha.flowswhen the default four flows are not the ones you want. - In your own page, pass the widget’s token as
captchaTokento the client call. The client sends it in the headerx-captcha-response. - In a server route that calls
auth.apifor a browser, pass the browser’s token ascaptchaToken.
import { createTurnstileCaptcha } from "@authtempo/captcha-turnstile";import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createCaptchaAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, password: {}, captcha: { // Cloudflare's always-pass test keys. Put your own secret key in the secret store. port: createTurnstileCaptcha({ secretKey: "1x0000000000000000000000000000000AA", siteKey: "1x00000000000000000000AA", }), // The default flows: the sign-up, the magic link, the email code, and the reset requests. // "allow" (the default) goes on when the captcha gives no answer. "refuse" answers 503. onUnavailable: "allow", }, });}import { afterEach, describe, expect, it, vi } from "vitest";import { call, harness } from "../support/harness.ts";import { createCaptchaAuth } from "./captcha.ts";
/** A siteverify stub that passes every token and counts the calls. No test calls the network. */function stubSiteverify(): { calls: number } { const seen = { calls: 0 }; vi.stubGlobal("fetch", async () => { seen.calls++; return Response.json({ success: true, "error-codes": [] }); }); return seen;}
describe("a captcha on the request flows", () => { afterEach(() => { vi.unstubAllGlobals(); });
it("asks for the token, and refuses a token that is too long, with no call to the supplier", async () => { const siteverify = stubSiteverify(); const auth = createCaptchaAuth(harness()); const bare = await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }); expect(bare.status).toBe(400); expect(await bare.json()).toEqual({ error: "captcha_required" }); const long = await call( auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }, { "x-captcha-response": "t".repeat(2049) }, ); expect(long.status).toBe(403); expect(await long.json()).toEqual({ error: "captcha_failed" }); expect(siteverify.calls).toBe(0); });
it("sends the mail after the supplier passes the token", async () => { const siteverify = stubSiteverify(); const h = harness(); const auth = createCaptchaAuth(h); const res = await call( auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }, { "x-captcha-response": "XXXX.DUMMY.TOKEN.XXXX" }, ); expect(await res.json()).toEqual({ sent: true }); expect(siteverify.calls).toBe(1); expect(h.sent.map((m) => m.to)).toEqual(["ada@example.com"]); });});How it behaves
Section titled “How it behaves”- The default flows are the sign-up, the magic link request, the email code request, and the reset requests. The password sign-in is opt-in.
- Each flow checks its per-IP limit first. A request over that limit costs no call to the captcha.
- The captcha runs before the per-email limits, the policy, and the breach check. A request with no token spends none of them.
- The captcha runs before the flow reads a user, so its answer is the same for every address.
- A call to
auth.apiwith nocaptchaTokenskips the check. A server route that proxies a browser must pass the browser’s token, or the check does not run. - Core’s own sign-in page shows the widget when the port gives a site key. With
handofforoauthand a gated flow on that page,createAuthrefuses a port with no page, unlesshandoff.signInPageis set. - A token passes once. After a refused answer, the person solves the widget again.
- When the captcha gives no answer, the flow goes on and writes one log line.
onUnavailable: "refuse"answers 503 instead. - The Turnstile package has one live test. It runs only with
AUTHTEMPO_LIVE_TURNSTILE=1, so a normal test run sends no call.
If it fails
Section titled “If it fails”captcha_required: the request has no token. Send the widget’s token.captcha_failed: the captcha refused the token, or the token is longer than 2048 characters.captcha_unavailable: the captcha gave no answer, andonUnavailableis"refuse".