# Bot protection

> A bot challenge on your application's public forms, its site key given by Apigami and each token checked by Apigami, with no key to create.

A page anyone may open without signing in, a booking form, a contact form, a sign-up, can ask its visitor to pass a
bot challenge before an action writes anything. Apigami gives your application the challenge's site key and checks
each token for it: you create no key, hold no secret, and set nothing up in any dashboard.

The challenge is [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/), most often passed without the
visitor seeing anything. It adds no subprocessor of yours and no box on the connect page. A target site whose own
anti-bot wall refuses `request.fetch` is another matter: [Errors](/docs/errors/).

## Declare it

```json
"x-apigami": { "bot_protection": true }
```

Every version deployed with it receives `env.APIGAMI_BOT_PROTECTION_SITE_KEY`, in clear: the key your pages draw the
widget with. Do not declare it in `x-apigami.env`, every `APIGAMI_*` name is Apigami's. A version without the field
receives no key, which is how you turn the challenge off: deploy one without it, and back with it to turn it on.

The challenge works on `{slug}.apigami.tech`, on `{slug}--staging.apigami.tech`, the real challenge on both, and on
your own domains within five minutes of becoming active. `app_status` says whether it is active, the site key, the
hosts it covers, and any own domain left out, where the challenge fails. A trial (`app_run`) receives no key and
draws no challenge: try the whole path on `--staging`, where a visitor's call reaches the version deployed there.

While `env.APIGAMI_BOT_PROTECTION_SITE_KEY` is absent, the protection is not active: the page draws no widget, and
your action decides whether a form without a token passes or waits, `app_status` saying why.

## Draw the widget

Your server writes the site key into the page, escaped as a JavaScript string:

```ts title="main.ts"
const siteKey = JSON.stringify(env.APIGAMI_BOT_PROTECTION_SITE_KEY ?? null).replace(/</g, '\\u003c')
return new Response(page.replace('__SITE_KEY__', siteKey), { headers: { 'Content-Type': 'text/html; charset=utf-8' } })
```

The page loads the widget's script and renders it once that script has loaded, with an `action` naming the gesture:

```html
<div id="challenge"></div>
<script>
  const SITE_KEY = __SITE_KEY__
  let challenge = null
  window.onChallengeLoaded = () => {
    if (SITE_KEY) turnstile.render('#challenge', { sitekey: SITE_KEY, action: 'contact', callback: (token) => { challenge = token } })
  }
</script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onChallengeLoaded" async defer></script>
```

The token travels with the form to your action, in its body. It is valid five minutes and only once: after a refusal
or a failed submission, call `turnstile.reset()` for a new one. The widget's other options, `appearance`, `language`,
`theme`, are Turnstile's own.

**Content Security Policy.** Apigami's router sets only `frame-ancestors` on your pages. A page that sends its own
`Content-Security-Policy` admits `https://challenges.cloudflare.com` in both `script-src` and `frame-src`.

## Verify the challenge in your action

Your action asks Apigami, under its version key, before anything it does for the visitor:

```ts title="main.ts"
const verdict = await fetch(`${env.APIGAMI_API_URL}/v1/apps/${env.APIGAMI_APP_ID}/bot-protection/verify`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${env.APIGAMI_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ token: body.challenge, action: 'contact' }),
}).then((response) => (response.ok ? response.json() : null))
if (verdict?.success !== true) return Response.json({ error: 'challenge_failed' }, { status: 403 })
```

```json
{ "success": true, "hostname": "contact.apigami.tech", "action": "contact", "challenge_ts": "2026-11-13T10:00:00.000Z" }
```

`success` is `true` only when the challenge passed, on a host your application serves, and, when you send `action`,
under that action. Otherwise the answer is still a `200`, `{ "success": false, "error_codes": [...] }`; your action
refuses the request then, with the status of its choice:

| `error_codes` | Meaning |
|---|---|
| `timeout-or-duplicate` | The token is older than five minutes, or was already checked |
| `invalid-input-response` | The token is empty, malformed or not one of a widget |
| `hostname-mismatch` | The challenge was passed on a page of another application |
| `action-mismatch` | The widget's `action` is not the one you sent |

| Status | Meaning |
|---|---|
| `409` | The version whose key calls does not declare `bot_protection`; under an application key, neither production nor `--staging` does |
| `503` | The challenge cannot be checked right now: try again shortly, or ask the visitor to retry |

The check spends the token, whatever it answers: check once per submission, never before a retry of your own. An
application key works too, for a script of yours; a trial (`app_run`) has no version key and checks nothing.