$ cat docs/middleware/captcha.md
CaptchaCaptcha
Stop bots on sign-up and lead forms with Turnstile, and never silently skip the check in production.Pare bots em cadastro e formulários de lead com Turnstile, sem nunca pular a checagem em produção.
What it doesO que faz
captcha(options: CaptchaOptions): MiddlewareHandler. On POST, PUT, PATCH and DELETE it sends the token (cf-turnstile-response header or JSON field) to Turnstile siteverify with the secret and, when clientIp() ran, the remoteip. Only success: true (and the expected hostname/action, when set) lets the request through.
captcha(options: CaptchaOptions): MiddlewareHandler. Em POST, PUT, PATCH e DELETE ele envia o token (header ou campo JSON cf-turnstile-response) ao siteverify do Turnstile com o segredo e, quando o clientIp() rodou, o remoteip. Só success: true (e o hostname/action esperados, quando definidos) deixa a requisição passar.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware Register it on the public form routes, after clientIp(). Tokens are single-use: reset the widget after each submit.
Registre nas rotas de formulário público, depois do clientIp(). Tokens são de uso único: reinicie o widget depois de cada envio.
ExampleExemplo
import { createModule } from '@tupik/core';
import { captcha, clientIp } from '@tupik/middleware';
const signup = createModule('/signup')
.use(clientIp({ trust: 'cloudflare' }))
.use(captcha({
secret: env.TURNSTILE_SECRET,
production: env.ENVIRONMENT === 'production', // missing secret → throws
allowMissingSecretInDev: true,
hostname: 'app.example.com',
}))
.post('/', { access: 'public', handler: (ctx) => createAccount(ctx.body) });import { createModule } from '@tupik/core';
import { captcha, clientIp } from '@tupik/middleware';
const signup = createModule('/signup')
.use(clientIp({ trust: 'cloudflare' }))
.use(captcha({
secret: env.TURNSTILE_SECRET,
production: env.ENVIRONMENT === 'production', // segredo ausente → lança
allowMissingSecretInDev: true,
hostname: 'app.example.com',
}))
.post('/', { access: 'public', handler: (ctx) => createAccount(ctx.body) }); APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
secret | string | undefined | Required unless allowMissingSecretInDev (never in production).Obrigatório, salvo allowMissingSecretInDev (nunca em produção). |
allowMissingSecretInDev, production | boolean | false. Explicit opt-out for local dev; production: true always throws without a secret.false. Saída explícita para dev local; production: true sempre lança sem segredo. |
token | (ctx) => string | undefined | cf-turnstile-response header, then JSON body field.Header cf-turnstile-response, depois o campo JSON. |
hostname, action | string | Absent. Expected values from siteverify.Ausente. Valores esperados do siteverify. |
methods, timeoutMs, fetch | string[], number, fn | Unsafe methods, 10 s, globalThis.fetch.Métodos inseguros, 10 s, globalThis.fetch. |
interface CaptchaOptions { secret; allowMissingSecretInDev?; production?; token?; hostname?; action?; methods?; fetch?; timeoutMs? }
interface CaptchaOptions { secret; allowMissingSecretInDev?; production?; token?; hostname?; action?; methods?; fetch?; timeoutMs? }
Errors and limitsErros e limites
- Missing, oversized or rejected token:
403 CAPTCHA_INVALID. - Siteverify down, slow or not OK:
503 CAPTCHA_UNAVAILABLE(fail closed). - No secret without the explicit dev flag, or with
production: true, throws at creation.
- Token ausente, grande demais ou recusado:
403 CAPTCHA_INVALID. - Siteverify fora, lento ou com erro:
503 CAPTCHA_UNAVAILABLE(falha fechada). - Sem segredo e sem a flag explícita de dev, ou com
production: true, lança na criação.
When not to use itQuando não usar
It slows bots down; it is not authentication or a rate limit. Keep rateLimit on the same routes.
Ele atrasa bots; não é autenticação nem limite de requisições. Mantenha o rateLimit nas mesmas rotas.