Skip to main content
ALTCHA®

Verifying submissions

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.

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:

{
  "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:

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
NeedsA restricted or full key of the widget key's accountThe public key's secret (sec_…) on your backend
Network callOne request to SentinelNone
Replay protectionBuilt inYou implement it

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, check fieldsHash yourself, as in 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.

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;
}
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'], …
}
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
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
}
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.

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:

curl -s https://sentinel.example.com/v2/verify/signature \
  -u 'key_…:sec_…' \
  -H 'Content-Type: application/json' \
  -d '{"payload": "eyJhbGdvcml0aG0iOiJTSEEtMjU2Ii…"}'
{
  "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.
OutcomeverifiedreasonapiKey, verificationData
Valid, first usetrueomittedset
Wrong signature, expired, or not verifiedfalseomittedset (verificationData is null if it can't be parsed)
Already accepted oncefalsePAYLOAD_ALREADY_USEDset
Signed by a key of another accountfalseAPI_KEY_NOT_ALLOWEDnull
Undecodable payload, unknown or deleted key, unsupported algorithmfalseINVALID_PAYLOADnull
Verified, but without id or expirefalseINVALID_PAYLOADset

Full schema: 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 client for the used ids. Save it as check-altcha.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.

Replay protection

Sentinel blocks replays at two points:

CheckKeyKept untilResult on reuse
POST /v2/verify (the widget)The challenge idThe challenge's expiryverified: false, reason: CHALLENGE_ALREADY_USED
POST /v2/verify/signature (your backend)verificationData.idverificationData.expireverified: 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.

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].

The challenge expires after 20m by default; a security-group pow.expires rule changes this, and expire follows it. See Rules reference.

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.

FieldTypePresentDescription
idstringalwaysThe challenge id. Use it for replay protection.
challenge.algorithmstringalwaysProof-of-work algorithm, e.g. PBKDF2/SHA-256.
challenge.issuedintegerverified onlyWhen the challenge was issued (Unix seconds). time − challenge.issued is the solve time.
challenge.protectionLevelstringverified onlyfrictionless, or code_challenge when the visitor solved a code challenge.
expireintegeralwaysWhen the challenge expires (Unix seconds).
ipAddressstringalwaysThe client IP that called POST /v2/verify.
originstringalwaysThe Origin (or Referer) of that request; empty if absent.
timeintegeralwaysWhen Sentinel verified the solution (Unix seconds).
verifiedbooleanalwaystrue only if every check passed. Require it.
classificationstringverified onlyVerdict: GOOD, NEUTRAL or BAD.
scorenumberverified onlyOverall classification score. See Scoring.
reasonslistverified onlyTriggered classifier rules, highest score first; empty if none.
device.browser, device.os, device.typestringverified onlyParsed from the request's headers; empty when unknown.
device.edkstringverified onlyThe visitor's EDK.
device.score, device.triggeredRulesnumber, listverified onlyDevice rules.
email.score, email.triggeredRulesnumber, listthe sent fields contain an email addressEmail rules.
ip.asname, ip.countryCode, ip.networksstring, string, listverified onlyNetwork owner, country and network types (tor, proxy, hosting, mobile, fixed); empty when unknown.
ip.score, ip.triggeredRulesnumber, listverified onlyIP rules.
location.countryCode, location.timeZonestringa country is known (from the IP, else the time zone)Country and the time zone the widget sent.
location.score, location.triggeredRulesnumber, listas aboveLocation rules.
text.score, text.triggeredRulesnumber, listthe sent fields contain textSpam and profanity rules.
injection.score, injection.triggeredRulesnumber, listfields were sentInjection rules.
similarity.score, similarity.triggeredRulesnumber, listtext was sent and a similarity rule is enabledSimilarity rules.
ai.score, ai.triggeredRulesnumber, listthe AI decider ranAI rules.
his.assistivebooleanthe challenge was issued with HIS onKeyboard-only or assistive-technology interaction.
his.automationnumberas aboveBot probability (0.01–1).
his.flagslistas aboveINTEGRITY, NO_INTERACTION, REPLAY; empty if none.
his.modestringas abovemonitor, relaxed or strict.
his.score, his.triggeredRulesnumber, listas above, outside monitor modeHIS rules.
fieldslistfields were sentField names, sorted.
fieldsHashstringas aboveHex SHA-256 of the field values in fields order, joined with \n. Check it with verifyFieldsHash.
params.<name>stringverified only, if the challenge URL had params.*Your custom parameters.

Fields that don't apply are omitted, never null. Rule names and their scores are in Classifier rules & scores.

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:

reasonMeaning
CHALLENGE_EXPIREDThe challenge expired before it was verified.
CHALLENGE_ALREADY_USEDThe challenge was already verified once.
EDK_MISMATCHThe challenge was fetched from another device (different IP network, User-Agent or language). The challenge isn't burned.
HIS_BLOCKEDThe HIS data sent with a code challenge was missing or blocked. The challenge is burned.
INCORRECT_CODEThe code challenge answer is missing or wrong. The challenge is burned.
INVALID_PAYLOADThe challenge is structurally invalid.
INVALID_SIGNATUREThe challenge wasn't issued for this key, or was changed.
INVALID_SOLUTIONThe proof-of-work solution is wrong.
TOO_FASTThe code challenge was solved too quickly. The challenge is burned. See Minimum solve time.

A payload that can't be decoded at all returns 400 INVALID_PAYLOAD instead. Full schema: 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:

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, 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.

Next steps

Start typing to search...

↑ ↓ Navigate ↵ Select