# Code challenge

> **Sentinel v2 (beta):** This page documents Sentinel v2, a beta rewrite that may change before the stable release. It does not apply to Sentinel v1, the current stable version: see the [Sentinel v1 documentation](/docs/sentinel.md).

The code challenge asks the visitor to type a short code, shown as an image and spoken on request, in addition to solving the [proof-of-work](/docs/sentinel/v2/features/proof-of-work/). It is off by default; security-group rules turn it on, usually only for clients that look risky.

<Callout type="note" title="Changed in v2">

There is no adaptive mode: put conditions on the rule that sets `codeChallenge.enabled`. A wrong or missing code burns the challenge, a code entered too quickly fails with [`TOO_FAST`](#minimum-solve-time-too_fast), and the audio plays only on the network that fetched the challenge. See [Breaking changes](/docs/sentinel/v2/upgrade/breaking-changes/#code-challenge).

## How it works

1. A matching `set` rule sets `codeChallenge.enabled` to `true`. `GET /v2/challenge` then generates a random code and adds a `codeChallenge` object with the image, the audio URL and the code length to the challenge.
2. The widget solves the proof-of-work, opens its code dialog with the image and an audio button, and sends the typed code as `code` to `POST /v2/verify`. See [Code challenge in the widget](/docs/sentinel/v2/integrate/widget/#code-challenge-in-the-widget).
3. `POST /v2/verify` checks the proof-of-work and marks the challenge as used, then compares the code: trimmed, case-insensitive, at most 10 characters. A missing or wrong code answers `verified: false` with `INCORRECT_CODE`. A correct code entered sooner than a person could type it answers `verified: false` with [`TOO_FAST`](#minimum-solve-time-too_fast). Either way the challenge is burned, and the widget fetches a new one.

The code is drawn from `codeChallenge.alphabet` (default `234579`), with no two equal characters next to each other. It travels encrypted (AES-256-GCM, under a key derived from the API key's secret) in the challenge's signed data, together with the client network it was issued to. Neither the code nor the token appears in `verificationData`; a verified solution signs `challenge.protectionLevel=code_challenge` instead of `frictionless`.

### The image

The image is a JPEG `data:` URL, 36 pixels wide per character and 50 pixels high: the code in a dot-matrix font under colored lines and noise dots. `codeChallenge.imageDifficulty` picks the style:

| Style | Noise |
| --- | --- |
| `low` | 50 noise dots, little rotation and shift |
| `standard` (default) | 60 noise dots, more rotation and vertical shift |
| `high` | 75 noise dots as large as the font's own dots, so they pass for parts of characters |

### The audio

`GET /v2/challenge/audio/<token>.wav` speaks the code as a mono 16-bit WAV. Sentinel generates it from voice recordings shipped in `assets/tts`, with no external text-to-speech service. The recording announces how many characters (or digits) follow, plays a short tone, speaks each character, and ends with a tone.

- **Delayed.** Each answer waits `[code_challenge] audio_delay`, default `3s`.
- **Bound to the network.** Only the client network the challenge was issued to gets the audio: the same IPv4 address, or the same IPv6 /64. From any other network, the token answers `404 NOT_FOUND`, so an audio URL handed to a captcha-solving service is useless there.
- **Rate limited per client IP** by `[code_challenge] audio_rate_limit`, default `10/5m`. Requests over the limit get `429 RATE_LIMITED`; refused tokens count too.
- **Varied per token.** Each rendering varies the leading silence, the gaps, and each clip's level and speed, so the clips don't match the shipped recordings byte for byte. Fetching the same token again returns the same bytes, so refetching doesn't collect variants to compare.
- **Cacheable privately** (`Cache-Control: private, max-age=600`) and never written to the request logs. The security group's rules gate it like any API-key request, with the path `/v2/challenge/audio/<token>.wav`.

The URL in the challenge carries `?apiKey=key_…`, because the browser's `<audio>` element can't send an `Authorization` header. It is relative and gets the path of the listener's `base_url` as a prefix (see [Listeners & reverse proxy](/docs/sentinel/v2/configure/listeners/)).

### Languages

The voice is the first match among the `language` query parameter and the request's `Accept-Language` tags, by primary subtag (`fr-CH` uses `fr`); otherwise English. The widget sets `language` to its `audioChallengeLanguage` option, or else to its interface language.

| Voice speaks | Languages |
| --- | --- |
| Digits and letters | Afrikaans (`af`), Bulgarian (`bg`), Croatian (`hr`), Czech (`cs`), Danish (`da`), Dutch (`nl`), English (`en`), Estonian (`et`), Finnish (`fi`), French (`fr`), German (`de`), Hungarian (`hu`), Indonesian (`id`), Italian (`it`), Latvian (`lv`), Lithuanian (`lt`), Malay (`ms`), Norwegian Bokmål (`nb`), Polish (`pl`), Portuguese (`pt`), Romanian (`ro`), Russian (`ru`), Serbian (`sr`), Slovak (`sk`), Slovenian (`sl`), Spanish (`es`), Swedish (`sv`), Turkish (`tr`), Ukrainian (`uk`), Vietnamese (`vi`) |
| Digits only | Arabic (`ar`), Bengali (`bn`), Cantonese (`yue`), Chinese (`zh`), Greek (`el`), Hebrew (`he`), Hindi (`hi`), Japanese (`ja`), Korean (`ko`), Marathi (`mr`), Punjabi (`pa`), Tamil (`ta`), Telugu (`te`), Thai (`th`), Urdu (`ur`) |

A code with letters is spoken in English by the digits-only voices. The default alphabet has digits only, so every voice can speak it.

#### Restricting the voices

`codeChallenge.audioLanguages` limits the audio to the voices you list, for example `de fr en`. Use it when your site serves fewer languages than Sentinel has voices, or to keep visitors on voices you've checked. Language codes are case-insensitive and can be separated by `,`, `;` or spaces. An unknown language code makes the group's rules fail to save (`400 INVALID_RULES`). An empty value allows every voice, the default.

With a list, the voice is chosen like this:

1. The first `language` or `Accept-Language` candidate that is on the list.
2. Otherwise, the first voice on the list that can speak the code, instead of English. Order the list by preference.

A digits-only voice on the list doesn't speak codes with letters; they fall back as in step 2. If no listed voice can speak the code, for example `ja zh` with a letter alphabet, the challenge has no `audio`.

```json
{
"action": "set",
"set": [{ "field": "codeChallenge.audioLanguages", "value": "de fr en" }]
}
```

The list comes from the rules that matched `GET /v2/challenge` and travels encrypted in the audio token, so rules that match the audio request itself don't change it.

### Accessibility

The audio is the alternative for visitors who can't read the image, for example screen-reader users. Keep it accessible:

- **Leave `codeChallenge.audio` on.** With `false`, the challenge has no audio and visually impaired visitors can't pass it. If you restrict `codeChallenge.audioLanguages`, include a voice that can speak your alphabet, or the audio disappears.
- **Keep the default digits-only alphabet** for international audiences. Letters are spoken in English by 15 of the voices, and similar-looking characters are harder to read in the image.
- **Prefer short codes and the `low` or `standard` style** where you require the challenge often. Reserve `high` and long codes for clients that are clearly suspicious.
- **Account for listening time.** Visitors who use the audio can submit only after the code has finished playing ([`TOO_FAST`](#minimum-solve-time-too_fast) enforces it), and each audio response waits `audio_delay` first. The recording of a four- to six-character code is about 15 to 20 seconds long, so keep `audio_delay` short.
- **Avoid the challenge where you can.** The **Recommended without code challenge** preset escalates with a harder proof-of-work instead. See [Security presets](/docs/sentinel/v2/policies/presets/#recommended-without-code-challenge).

### Minimum solve time (TOO_FAST)

`TOO_FAST` is the `reason` that `POST /v2/verify` returns when the code is correct but arrived too soon after the challenge to have been typed by a person. It stops scripts that read the image or audio by machine and answer at once.

A correct code is too fast if either of these is true:

- Less than `[code_challenge] min_solve_time` (default `4s`) has passed since `GET /v2/challenge` issued the challenge.
- The audio was fetched, and the spoken code hasn't finished playing yet. The end of the recording is counted from the first audio response.

The check runs only after the code matched, so a wrong code entered quickly answers `INCORRECT_CODE`. Like a wrong code, `TOO_FAST` burns the challenge and adds 1 to the client's [penalty](/docs/sentinel/v2/concepts/scoring/#penalty); the widget fetches a new challenge and the visitor has to type the new code. If real visitors get `TOO_FAST`, see [Tuning](#tuning).

## Enabling it

The server settings only tune the audio and the minimum solve time; the defaults fit most sites:

```toml
[code_challenge]
audio_delay      = "3s"     # wait before each audio response
min_solve_time   = "4s"     # TOO_FAST below this; "0s" turns the floor off
audio_rate_limit = "10/5m"  # audio requests per client IP; "" = unlimited
```

The audio needs the voices in `[code_challenge] tts_dir` (default `assets/tts`, included in the container image). Without the English voice and the tone file, challenges carry no audio URL and the startup log warns that the audio is disabled. `audio_rate_limit` uses the [`[rate_limit]`](/docs/sentinel/v2/reference/configuration/#rate_limit) syntax, but not `key=uid`, since the limit is per client IP. See [`[code_challenge]`](/docs/sentinel/v2/reference/configuration/#code_challenge).

Turn the challenge on with a `set` rule in the security group of your widget key. This one requires a six-character code from clients with a penalty of 3 or more, for example after a few failed verifications:

```json
{
"name": "code-on-penalty",
"action": "set",
"conditions": [{ "field": "penalty", "operator": ">=", "value": ["3"] }],
"set": [
{ "field": "codeChallenge.enabled", "value": "true" },
{ "field": "codeChallenge.length", "value": "6" }
]
}
```

Other useful conditions are `risk` `>=` `4`, `network` `=` `hosting`, `proxy`, `tor`, or the `signal` field. See [Writing security rules](/docs/sentinel/v2/policies/security-rules/#force-the-code-challenge-for-hosting-ips) for a recipe. The **Recommended**, **Strict** and **Lockdown** presets include a code challenge already; see [Security presets](/docs/sentinel/v2/policies/presets/).

| Field | Default | What it controls |
| --- | --- | --- |
| `codeChallenge.enabled` | `false` | Adds the code challenge. |
| `codeChallenge.alphabet` | `234579` | 2–36 ASCII letters or digits, at least 2 distinct. Letters are case-insensitive. |
| `codeChallenge.length` | `5` | `N` or a random `MIN-MAX` range, within 4–8. |
| `codeChallenge.imageDifficulty` | `standard` | `low`, `standard` or `high`. |
| `codeChallenge.audio` | `true` | `false` removes the audio URL; the token's audio then answers `404`. |
| `codeChallenge.audioLanguages` | Every voice | Voices the audio may use, e.g. `de fr en`; the first listed voice that can speak the code replaces English as the fallback. See [Restricting the voices](#restricting-the-voices). |

Values are strings, as in every `set` entry. See the [Rules reference](/docs/sentinel/v2/reference/rules/#code-challenge).

## Rules & signals

The code challenge has no classifier rules. It shows up in these places:

| Signal | Meaning |
| --- | --- |
| `INCORRECT_CODE` | `POST /v2/verify` reason: the code was missing or wrong. The challenge is burned and the client's penalty goes up by 1. |
| `TOO_FAST` | `POST /v2/verify` reason: a correct code arrived before the minimum solve time or before the audio finished playing. The challenge is burned and the penalty goes up by 1. See [Minimum solve time](#minimum-solve-time-too_fast). |
| `HIS_BLOCKED` | `POST /v2/verify` reason, only with `his.codeChallenge`: the interaction data sent with the code was missing or blocked. See [Human Interaction Signature](/docs/sentinel/v2/features/human-interaction-signature/). |
| `challenge.protectionLevel` | `code_challenge` in `verificationData` of a verified code challenge, else `frictionless`. Request logs show it as **Protection level**. |
| `rate_limit_audio` | `reason` label of `altcha_sentinel_requests_blocked_total` for audio requests over `audio_rate_limit`. |

Because failures raise the [penalty](/docs/sentinel/v2/concepts/scoring/#penalty), a client that keeps guessing reaches stricter rules, such as a `deny` at a high penalty. See [`POST /v2/verify` reasons](/docs/sentinel/v2/integrate/verification/#post-v2verify-reasons) for every reason.

## Using the API

The widget handles the code challenge itself. To check your rules, fetch a challenge with the `public` key from a client the rule matches:

```bash
curl 'https://sentinel.example.com/v2/challenge?apiKey=key_…'
```

```json
{
"codeChallenge": {
"audio": "/v2/challenge/audio/VLDYxpKsJeDpESTV1FJ_U-Mw-yj94Cwh….wav?apiKey=key_…",
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD…",
"length": 6
},
"configuration": { "serverVerificationFields": false, "serverVerificationTimeZone": true, "verifyUrl": "/v2/verify" },
"parameters": {
"algorithm": "PBKDF2/SHA-256",
"data": { "codeChallenge": "VLDYxpKsJeDpESTV1FJ_U-Mw-yj94Cwh…", "edk": "…", "id": "…", "issued": 1795056016272 },
…
},
"signature": "…"
}
```

- `codeChallenge` is omitted when no rule enables the challenge.
- `audio` is omitted without voices, with `codeChallenge.audio` `false`, or when no voice in `codeChallenge.audioLanguages` can speak the code.
- `his` (`true`) appears only when `his.codeChallenge` is on and `his.mode` isn't `off`.

The widget submits the code with the solved payload. A wrong code still answers `200`, with the reason in the body:

```bash
curl -X POST 'https://sentinel.example.com/v2/verify?apiKey=key_…' \
-H 'Content-Type: application/json' \
-d '{ "payload": "eyJjaGFsbGVuZ2Ui…", "code": "000000" }'
```

```json
{
"algorithm": "SHA-256",
"apiKey": "key_…",
"id": "e067879371e269ecc39f6235a0cd6684",
"payload": "eyJhbGdvcml0aG0i…",
"reason": "INCORRECT_CODE",
"signature": "c022ca43…",
"verificationData": "id=e067879371e269ecc39f6235a0cd6684&challenge.algorithm=PBKDF2%2FSHA-256&expire=1795057216&ipAddress=203.0.113.2&origin=&time=1795056028&verified=false",
"verified": false
}
```

Sending the same payload again answers `CHALLENGE_ALREADY_USED`, because the first attempt burned it. Like the challenge, the verify response isn't wrapped in `{ "data": … }`. See [`GET /v2/challenge`](/sentinel-api-docs-v2.html#tag/challenge/GET/v2/challenge), [`GET /v2/challenge/audio/{file}`](/sentinel-api-docs-v2.html#tag/challenge) and [`POST /v2/verify`](/sentinel-api-docs-v2.html#tag/verify/POST/v2/verify) in the API reference.

## Tuning

- **Require it only when needed.** A code challenge on every request costs real visitors time and completed forms. Condition it on `penalty`, `risk`, `network` or `signal`, and keep a harder proof-of-work for the middle ground.
- **Start with the defaults.** Five digits from `234579` in the `standard` style read well. Raise `codeChallenge.length` (for example `6-7`) and use `high` in a second rule for the most suspicious clients, as the **Strict** preset does.
- **Pick letters with care.** If you use letters, leave out characters that look alike in a dot-matrix font, such as `O` and `0` or `I` and `1`.
- **Keep `min_solve_time`.** It stops scripts that read the image or audio by machine and answer at once. Set `"0s"` only if real visitors hit `TOO_FAST`.
- **Watch the reasons.** Many `INCORRECT_CODE` results from real visitors mean the code is too hard to read; lower the style or the length. Request logs record the reason of each failed verification as `error`, for keys with request logging on (see [Request logs & analytics](/docs/sentinel/v2/operations/request-logs/)).
- **Try it before it applies.** Monitor mode records when a rule would have fired, but a monitored rule's settings aren't applied, so its visitors get no code. Use the counts to see how many visitors a condition would catch, then remove `monitor`.

## Limitations

- Human solving services can type codes for an attacker; the challenge raises the cost per submission but doesn't stop a paid human. Combine it with [Human Interaction Signature](/docs/sentinel/v2/features/human-interaction-signature/) and rate limits.
- The network binding stops audio URLs from being fetched elsewhere, not a client that downloads the audio itself and passes the bytes on.
- The widget must support code challenges (v3 and later). With `his.codeChallenge`, widgets before 3.6.0 fail with `HIS_BLOCKED`.
- Visitors who change network between fetching the challenge and playing the audio (for example from Wi-Fi to mobile data) get `404` for the audio and need a new challenge.

## Related

- [`codeChallenge.*` set fields](/docs/sentinel/v2/reference/rules/#code-challenge) in the Rules reference
- [`[code_challenge]`](/docs/sentinel/v2/reference/configuration/#code_challenge) in the Configuration reference
- [Code challenge in the widget](/docs/sentinel/v2/integrate/widget/#code-challenge-in-the-widget)
- [Proof-of-work](/docs/sentinel/v2/features/proof-of-work/)
- [Human Interaction Signature](/docs/sentinel/v2/features/human-interaction-signature/)
- [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/)
- [Security presets](/docs/sentinel/v2/policies/presets/)
