# Verifying submissions

> **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).

After the user solves the widget, your backend must verify the payload before it trusts the submission. Let Sentinel verify it (recommended), or verify it locally with the widget key's secret.

Prerequisites: the widget is set up as in [Widget integration](/docs/sentinel/v2/integrate/widget/).

## How it works

The widget calls `POST /v2/verify` itself, at the `verifyUrl` that Sentinel returns with the challenge. Sentinel checks the solution, burns the challenge, classifies the request, and signs the result with the `public` key's secret. The widget then puts the signed result, a base64 string, into the form's `altcha` field.

That string passes through the browser, so your backend must check its signature. Decoded, it looks like this:

```json
{
"algorithm": "SHA-256",
"apiKey": "key_…",
"id": "e8fa8997796d5d45d841698234b2bd69",
"signature": "ebbf73c5…",
"verificationData": "id=e8fa…&challenge.algorithm=PBKDF2%2FSHA-256&…&verified=true&classification=NEUTRAL&score=1.2&reasons=MX%2CUSER_AGENT_HEADER_UNCOMMON&…",
"verified": true
}
```

The signature covers only `verificationData`:

```text
signature = hex( HMAC-SHA256( key = API key secret, message = SHA-256(verificationData) ) )
```

Only the fields inside `verificationData` are trustworthy. The top-level `verified` is an unsigned copy.

You have two ways to check it:

| | Verify with Sentinel (recommended) | Verify locally |
| --- | --- | --- |
| Needs | A `restricted` or `full` key of the widget key's account | The `public` key's secret (`sec_…`) on your backend |
| Network call | One request to Sentinel | None |
| Replay protection | Built in | You implement it |

<Callout type="warning" title="Keep secrets on your server">

Load API key secrets from an environment variable or a secret store, never from client code. The `public` key's `sec_…` secret signs the key's challenges and results, so anyone with it can forge a verified payload.

## Option 1 — Verify with Sentinel (recommended)

Send the `altcha` field to `POST /v2/verify/signature` with a `restricted` or `full` key of the widget key's account. Sentinel checks the signature and expiry, accepts each payload only once, and rejects payloads signed by another account's key. Your backend needs neither the `public` key's secret nor its own store of used payloads. Sentinel doesn't see your form, so if the widget sends [`fields`](/docs/sentinel/v2/integrate/parameters/), check `fieldsHash` yourself, as in [Decide from the classification](#decide-from-the-classification).

### With a server library

These libraries call `POST /v2/verify/signature` with the key you pass and return Sentinel's `verified`, `reason` and `verificationData`: `altcha-lib` 2.9.0 (Node.js), `altcha-org/altcha` 2.4.0 (PHP), `altcha` 2.4.0 (Python), `altcha-lib-go` 2.5.0 and `Altcha` 1.2.0 (.NET), or later. Use a `restricted` or `full` key of the widget key's account, not the widget's `public` key.

<Tabs padding={false}>

### Node.js

```ts
import { verifyServer } from 'altcha-lib';

// `altcha` is the submitted form field.
export async function verifyWithSentinel(altcha: string) {
const result = await verifyServer({
  payload: altcha,
  url: 'https://sentinel.example.com/v2/verify/signature',
  apiKey: { id: 'key_…', secret: process.env.SENTINEL_API_KEY_SECRET! }, // restricted or full key
});
// result.verificationData.classification, result.verificationData['device.browser'], …
return result.verified ? result.verificationData : null;
}
```

### PHP

```php
use AltchaOrg\Altcha\Sentinel;
use AltchaOrg\Altcha\VerifyServerApiKey;
use AltchaOrg\Altcha\VerifyServerOptions;

$result = Sentinel::verify(new VerifyServerOptions(
  payload: $_POST['altcha'],
  url: 'https://sentinel.example.com/v2/verify/signature',
  apiKey: new VerifyServerApiKey('key_…', getenv('SENTINEL_API_KEY_SECRET')), // restricted or full key
));

if ($result->verified) {
  // $result->verificationData['classification'], …
}
```

### Python

```python
import os

from altcha import verify_server

def verify_with_sentinel(altcha: str):
  """`altcha` is the submitted form field."""
  result = verify_server(
      altcha,
      url="https://sentinel.example.com/v2/verify/signature",
      api_key="key_…",  # restricted or full key
      secret=os.environ["SENTINEL_API_KEY_SECRET"],
  )
  # result.verification_data["classification"], …
  return result.verification_data if result.verified else None
```

### Go

```go
import (
  "context"
  "os"

  altcha "github.com/altcha-org/altcha-lib-go/v2"
)

// payload is the submitted form field `altcha`.
func verifyWithSentinel(ctx context.Context, payload string) (bool, error) {
  result, err := altcha.VerifyServer(ctx, altcha.VerifyServerOptions{
      URL:     "https://sentinel.example.com/v2/verify/signature",
      Payload: payload,
      APIKey:  "key_…", // restricted or full key
      Secret:  os.Getenv("SENTINEL_API_KEY_SECRET"),
  })
  if err != nil {
      return false, err // network error, or an HTTP error such as 401/403 for wrong credentials
  }
  // result.VerificationData.Classification, …
  return result.Verified, nil
}
```

### .NET

```csharp
using Altcha;

// payload is the submitted form field `altcha`.
static async Task<bool> VerifyWithSentinelAsync(HttpClient httpClient, string payload)
{
  var client = new SentinelClient(httpClient);
  var result = await client.VerifyAsync(new VerifyServerOptions
  {
      Url = new Uri("https://sentinel.example.com/v2/verify/signature"),
      Payload = payload,
      ApiKey = "key_…", // restricted or full key
      Secret = Environment.GetEnvironmentVariable("SENTINEL_API_KEY_SECRET"),
  });
  // result.VerificationData?.Classification, …
  return result.Verified;
}
```

A replayed payload returns `verified: false` with `reason: PAYLOAD_ALREADY_USED`, as with plain HTTP. Wrong or missing credentials aren't retried: the Node.js, PHP and Python libraries return `verified: false` with the error `code` as `reason` (for example `API_KEY_REQUIRED`); the Go library returns an error and the .NET library throws `AltchaSentinelException`. The shape of `verificationData` differs per library; see its README, linked from [Server integration](/docs/integration/server/#libraries).

The `altcha-lib` framework plugins (Express, Fastify, Hono, NestJS, Next.js, Nuxt, SvelteKit) verify Sentinel payloads this way when you pass the same options as `verifyServer: { url, apiKey }`.

### With plain HTTP

Send the payload as JSON, authenticated with Basic credentials of the `restricted` or `full` key:

```bash
curl -s https://sentinel.example.com/v2/verify/signature \
-u 'key_…:sec_…' \
-H 'Content-Type: application/json' \
-d '{"payload": "eyJhbGdvcml0aG0iOiJTSEEtMjU2Ii…"}'
```

```json
{
"apiKey": "key_…",
"verificationData": {
"challenge": { "algorithm": "PBKDF2/SHA-256", "issued": 1794819603, "protectionLevel": "frictionless" },
"classification": "NEUTRAL",
"device": { "browser": "Chrome", "edk": "0aaccc64…", "os": "macOS", "score": 1, "triggeredRules": "USER_AGENT_HEADER_UNCOMMON", "type": "desktop" },
"email": { "score": 5, "triggeredRules": "MX" },
"expire": 1794820803,
"fields": ["email", "message"],
"fieldsHash": "509cde09…",
"id": "e8fa8997796d5d45d841698234b2bd69",
"ip": { "asname": "", "countryCode": "", "networks": "", "score": 0, "triggeredRules": "" },
"ipAddress": "203.0.113.10",
"origin": "https://www.example.com",
"params": { "formId": "contact" },
"reasons": ["MX", "USER_AGENT_HEADER_UNCOMMON"],
"score": 1.2,
"time": 1794819606,
"verified": true,
…
},
"verified": true
}
```

- `payload` is the base64 string (at most 32768 characters) or the decoded object.
- The response has no `{ "data": … }` envelope. Once the request is authenticated and the body is valid, the status is always `200`; branch on `verified`.
- `verificationData` is nested: keys are split on `.`, `fields` and `reasons` are arrays, `true`/`false` are booleans, and decimal numbers are numbers, except `id`, `fieldsHash`, `device.edk` and `params.*`, which stay strings. Other lists, such as `device.triggeredRules`, stay comma-separated strings.
- Don't send `secret`: it returns `400 VALIDATION_ERROR`. Without credentials you get `401 API_KEY_REQUIRED`; with a `public` key, `403 BASIC_AUTH_NON_PUBLIC_API_KEY` (Basic) or `403 NON_PUBLIC_API_KEY_REQUIRED` (by id).
- The caller's security group applies (IP rules, rate limits). On the `[server.public_api]` listener, this route is served only with `verify_signature = true`.

| Outcome | `verified` | `reason` | `apiKey`, `verificationData` |
| --- | --- | --- | --- |
| Valid, first use | `true` | omitted | set |
| Wrong signature, expired, or not verified | `false` | omitted | set (`verificationData` is `null` if it can't be parsed) |
| Already accepted once | `false` | `PAYLOAD_ALREADY_USED` | set |
| Signed by a key of another account | `false` | `API_KEY_NOT_ALLOWED` | `null` |
| Undecodable payload, unknown or deleted key, unsupported algorithm | `false` | `INVALID_PAYLOAD` | `null` |
| Verified, but without `id` or `expire` | `false` | `INVALID_PAYLOAD` | set |

Full schema: [`POST /v2/verify/signature`](/sentinel-api-docs-v2.html#tag/verify/POST/v2/verify/signature).

## Option 2 — Verify locally

Use this when your backend can't call Sentinel. Check the payload with `verifyServerSignature` from an ALTCHA server library and the secret of the `public` key that the widget uses. It doesn't prevent replays, so store each accepted payload `id` until its `expire` time (Unix seconds) and reject an `id` you've already seen.

This Node.js example uses `altcha-lib` 2.9.0 or later and the [`redis`](https://www.npmjs.com/package/redis) client for the used ids. Save it as `check-altcha.ts`:

```ts
import { verifyFieldsHash, verifyServerSignature } from 'altcha-lib';
import { createClient } from 'redis';

const ALTCHA_SECRET = process.env.ALTCHA_SECRET!; // the public key's sec_… secret
const redis = await createClient({ url: process.env.REDIS_URL }).connect();

// Records the payload id until it expires. Returns false if the id was already used.
async function isFirstUse(id: string, expire: number): Promise<boolean> {
return (await redis.set(`altcha:${id}`, '1', { NX: true, EXAT: expire })) === 'OK';
}

// `form` holds the submitted form fields, including `altcha`.
export async function checkAltcha(form: Record<string, string>) {
let result;
try {
result = await verifyServerSignature({ payload: form.altcha, hmacSecret: ALTCHA_SECRET });
} catch {
return null; // tampered payload, e.g. an unsupported algorithm
}
const data = result.verificationData;
if (!result.verified || !data?.id || !data.expire) {
return null; // bad signature, expired, or not verified
}
if (data.fields && !(await verifyFieldsHash({
formData: form,
fields: data.fields,
fieldsHash: String(data.fieldsHash),
}))) {
return null; // form changed after Sentinel classified it
}
if (!(await isFirstUse(data.id, data.expire))) {
return null; // replay
}
return data;
}
```

`verifyServerSignature` checks the signature, `verified=true` in `verificationData`, and `expire`. A payload that can't be decoded returns `verified: false`; a payload whose `algorithm` was changed to an unsupported one throws, hence the `try`. It returns `verificationData` as a flat object (`data['device.browser']`), with `fields` and `reasons` as arrays and numbers and booleans converted.

For other languages, see [Server integration](/docs/integration/server/).

## Replay protection

Sentinel blocks replays at two points:

| Check | Key | Kept until | Result on reuse |
| --- | --- | --- | --- |
| `POST /v2/verify` (the widget) | The challenge `id` | The challenge's expiry | `verified: false`, `reason: CHALLENGE_ALREADY_USED` |
| `POST /v2/verify/signature` (your backend) | `verificationData.id` | `verificationData.expire` | `verified: false`, `reason: PAYLOAD_ALREADY_USED` |

So a solved challenge verifies once, and a signed payload is accepted once by `POST /v2/verify/signature`. A local check has no such memory; add your own as shown in [Option 2](#option-2--verify-locally).

Claims live in the KV store: Redis when `[redis] nodes` or `[redis.sentinel]` is set, otherwise the built-in KV in the Sentinel database. If the KV store is unavailable, each replica falls back to its own memory, so during an outage a payload may be accepted once per replica. See [`[redis]`](/docs/sentinel/v2/reference/configuration/#redis).

The challenge expires after `20m` by default; a security-group `pow.expires` rule changes this, and `expire` follows it. See [Rules reference](/docs/sentinel/v2/reference/rules/#proof-of-work).

## The `verificationData` fields

`verificationData` is URL-encoded (`application/x-www-form-urlencoded`). Empty values are empty strings and lists are comma-separated. Fields marked *verified only* are signed only when the solution verified; an unverified result has just `id`, `challenge.algorithm`, `expire`, `ipAddress`, `origin`, `time` and `verified`.

| Field | Type | Present | Description |
| --- | --- | --- | --- |
| `id` | string | always | The challenge id. Use it for replay protection. |
| `challenge.algorithm` | string | always | Proof-of-work algorithm, e.g. `PBKDF2/SHA-256`. |
| `challenge.issued` | integer | verified only | When the challenge was issued (Unix seconds). `time` − `challenge.issued` is the solve time. |
| `challenge.protectionLevel` | string | verified only | `frictionless`, or `code_challenge` when the visitor solved a code challenge. |
| `expire` | integer | always | When the challenge expires (Unix seconds). |
| `ipAddress` | string | always | The client IP that called `POST /v2/verify`. |
| `origin` | string | always | The `Origin` (or `Referer`) of that request; empty if absent. |
| `time` | integer | always | When Sentinel verified the solution (Unix seconds). |
| `verified` | boolean | always | `true` only if every check passed. Require it. |
| `classification` | string | verified only | Verdict: `GOOD`, `NEUTRAL` or `BAD`. |
| `score` | number | verified only | Overall classification score. See [Scoring](/docs/sentinel/v2/concepts/scoring/). |
| `reasons` | list | verified only | Triggered classifier rules, highest score first; empty if none. |
| `device.browser`, `device.os`, `device.type` | string | verified only | Parsed from the request's headers; empty when unknown. |
| `device.edk` | string | verified only | The visitor's [EDK](/docs/sentinel/v2/reference/glossary/). |
| `device.score`, `device.triggeredRules` | number, list | verified only | Device rules. |
| `email.score`, `email.triggeredRules` | number, list | the sent fields contain an email address | Email rules. |
| `ip.asname`, `ip.countryCode`, `ip.networks` | string, string, list | verified only | Network owner, country and network types (`tor`, `proxy`, `hosting`, `mobile`, `fixed`); empty when unknown. |
| `ip.score`, `ip.triggeredRules` | number, list | verified only | IP rules. |
| `location.countryCode`, `location.timeZone` | string | a country is known (from the IP, else the time zone) | Country and the time zone the widget sent. |
| `location.score`, `location.triggeredRules` | number, list | as above | Location rules. |
| `text.score`, `text.triggeredRules` | number, list | the sent fields contain text | Spam and profanity rules. |
| `injection.score`, `injection.triggeredRules` | number, list | fields were sent | Injection rules. |
| `similarity.score`, `similarity.triggeredRules` | number, list | text was sent and a similarity rule is enabled | Similarity rules. |
| `ai.score`, `ai.triggeredRules` | number, list | the AI decider ran | AI rules. |
| `his.assistive` | boolean | the challenge was issued with HIS on | Keyboard-only or assistive-technology interaction. |
| `his.automation` | number | as above | Bot probability (0.01–1). |
| `his.flags` | list | as above | `INTEGRITY`, `NO_INTERACTION`, `REPLAY`; empty if none. |
| `his.mode` | string | as above | `monitor`, `relaxed` or `strict`. |
| `his.score`, `his.triggeredRules` | number, list | as above, outside `monitor` mode | HIS rules. |
| `fields` | list | fields were sent | Field names, sorted. |
| `fieldsHash` | string | as above | Hex SHA-256 of the field values in `fields` order, joined with `\n`. Check it with `verifyFieldsHash`. |
| `params.<name>` | string | verified only, if the challenge URL had `params.*` | Your [custom parameters](/docs/sentinel/v2/integrate/parameters/). |

Fields that don't apply are omitted, never `null`. Rule names and their scores are in [Classifier rules & scores](/docs/sentinel/v2/reference/classifier-rules/).

## `POST /v2/verify` reasons

When the widget's verification fails, `POST /v2/verify` returns `200` with `verified: false` and a `reason`. The widget shows an error and lets the visitor retry. You'll see these in request logs:

| `reason` | Meaning |
| --- | --- |
| `CHALLENGE_EXPIRED` | The challenge expired before it was verified. |
| `CHALLENGE_ALREADY_USED` | The challenge was already verified once. |
| `EDK_MISMATCH` | The challenge was fetched from another device (different IP network, User-Agent or language). The challenge isn't burned. |
| `HIS_BLOCKED` | The HIS data sent with a code challenge was missing or blocked. The challenge is burned. |
| `INCORRECT_CODE` | The code challenge answer is missing or wrong. The challenge is burned. |
| `INVALID_PAYLOAD` | The challenge is structurally invalid. |
| `INVALID_SIGNATURE` | The challenge wasn't issued for this key, or was changed. |
| `INVALID_SOLUTION` | The proof-of-work solution is wrong. |
| `TOO_FAST` | The code challenge was solved too quickly. The challenge is burned. See [Minimum solve time](/docs/sentinel/v2/features/code-challenge/#minimum-solve-time-too_fast). |

A payload that can't be decoded at all returns `400 INVALID_PAYLOAD` instead. Full schema: [`POST /v2/verify`](/sentinel-api-docs-v2.html#tag/verify/POST/v2/verify).

## Decide from the classification

`verified=true` means the proof-of-work (and any code challenge) passed. It doesn't mean the submission is clean: the classification can still be `BAD`. Decide on your backend, for example in an Express handler:

```ts
import { verifyFieldsHash, verifyServer } from 'altcha-lib';
import express from 'express';

const app = express();
app.use(express.urlencoded({ extended: false }));

app.post('/contact', async (req, res) => {
const result = await verifyServer({
payload: req.body.altcha,
url: 'https://sentinel.example.com/v2/verify/signature',
apiKey: { id: 'key_…', secret: process.env.SENTINEL_API_KEY_SECRET! }, // restricted or full key
});
const data = result.verified ? result.verificationData : null;
if (!data || (data.fields && !(await verifyFieldsHash({
formData: req.body,
fields: data.fields,
fieldsHash: String(data.fieldsHash),
})))) {
res.status(400).send('Verification failed.');
return;
}
switch (data.classification) {
case 'GOOD':
  // accept: send or store the message
  break;
case 'NEUTRAL':
  // accept, but flag it for review
  break;
default: // BAD
  res.status(403).send('Rejected.');
  return;
}
res.send('Thank you!');
});

app.listen(8080);
```

With [local verification](#option-2--verify-locally), call `checkAltcha(req.body)` instead of `verifyServer` and the fields check; it returns the same `data`, or `null`.

- `classification` is derived from `score`: `GOOD` below 1, `NEUTRAL` below 2, `BAD` otherwise. Use `score` directly for a finer threshold.
- Check the `params.*` and `origin` you rely on, for example that `params.formId` matches the form being submitted.
- To stop bad traffic before the widget even gets a challenge, use security-group rules instead. See [Security groups](/docs/sentinel/v2/concepts/security-groups/).

## Next steps

- [Custom parameters & fields](/docs/sentinel/v2/integrate/parameters/)
- [Backend detection APIs](/docs/sentinel/v2/integrate/backend-apis/): classify text, emails and IPs outside the widget flow.
- [Scoring](/docs/sentinel/v2/concepts/scoring/)
