Skip to content

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.

  • A working setup from a getting started tutorial.
  • A Cloudflare account with a Turnstile widget, for its site key and its secret key.
  1. Add @authtempo/captcha-turnstile to the API.
  2. Store the secret key in the secret store of the API.
  3. Set captcha.port to createTurnstileCaptcha({ secretKey, siteKey }).
  4. Set captcha.flows when the default four flows are not the ones you want.
  5. In your own page, pass the widget’s token as captchaToken to the client call. The client sends it in the header x-captcha-response.
  6. In a server route that calls auth.api for a browser, pass the browser’s token as captchaToken.
The captcha config
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",
},
});
}
The captcha as a test
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"]);
});
});
  • 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.api with no captchaToken skips 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 handoff or oauth and a gated flow on that page, createAuth refuses a port with no page, unless handoff.signInPage is 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.