# Custom Webhooks API

Source: https://docs.autessa.com/docs/api/custom-webhooks

> Receive events from external systems over a single public endpoint and trigger tools, agents, managers, or AutessaDB operations asynchronously.

# Custom Webhooks API

Custom webhooks give every webhook handler you configure in Autessa a public HTTPS trigger URL. External systems (payment processors, CRMs, CI pipelines, form builders) call the URL when something happens; Autessa authenticates the request (with the webhook's own key, the sender's signature, or a script you write), transforms the payload into variables, and executes the handler you attached — a tool, an agent, a manager, or an AutessaDB operation. Providers such as Meta, Stripe, GitHub, Slack, Shopify, and Twilio can point straight at the trigger URL, and any other service can too, with a short script for its signature scheme. You don't need a server of your own in between.

> By default webhook execution is **asynchronous**: a successful call is answered immediately with an `executionId`, and the handler runs in the background. The default status is `200` when the webhook checks a sender signature or answers a handshake, and `202 Accepted` otherwise. You can change the reply's status, content type, and body, or return a tool's output directly to the sender — see [Customizing the reply](#customizing-the-reply). Use the execution history in the builder to inspect the outcome of each delivery.

---

## Base URL

Each webhook has a short trigger URL:

```
https://api.autessa.com/w/{webhookId}
```

The same URL accepts **GET, POST, PUT, PATCH, and DELETE**, so it fits whatever method the external system insists on sending.

Anything after the ID is passed to your scripts as `path`, so one webhook can serve many links. For example, `https://api.autessa.com/w/{webhookId}/summer-sale` gives `path` = `/summer-sale`.

The long form still works everywhere, and the examples on this page use it:

```
https://api.autessa.com/clients/custom-webhooks?resourceId={webhookId}
```

---

## Authentication

Each webhook chooses how callers prove who they are with its `authMode`:

| `authMode` | What the caller sends |
| --- | --- |
| `API_KEY` (default) | The webhook's own key. If the webhook also has a `signatureConfig`, the signature is required too: both must be valid. |
| `SIGNATURE` | No key. The sender signs each request, and Autessa verifies the signature with a signing secret you stored as an [Autessa Secret](/docs/guide/agentic/secrets.md). |
| `API_KEY_OR_SIGNATURE` | Either one. A key that is sent must be valid; with no key, the signature must verify. Useful while moving a sender from key to signature. |
| `SCRIPT` | No key, and no built-in signature check. The webhook's [validation script](#webhook-scripts) decides whether to accept each call, so the script is required. Use it for senders whose signature scheme isn't built in, such as Discord, Twitch, SendGrid, PayPal, and AWS SNS. |
| `PUBLIC` | Nothing. A [public link](#public-link) that anyone can open in a browser, for links you share in messages and posts. |

### Webhook key

Each webhook has a dedicated **webhook API key**, generated when you create the handler. Webhook keys have the shape:

```
wh:{keyId}:{keySecret}
```

Send the full key (including the `wh:` prefix) in whichever place the sending system supports:

- `Authorization: wh:...` (no prefix)
- `Authorization: Bearer wh:...`
- `X-API-Key: wh:...`
- In the URL, as the `authorization`, `auth`, `apiKey`, or `key` query parameter, for senders that can't set headers.

If a key arrives in both a header and the URL, the header wins.

Each webhook key is bound to exactly one webhook: the `{keyId}` segment must match the key registered for the webhook selected by `resourceId`, the secret is verified against its stored hash, and both the webhook and the key must be enabled. Regular client API keys and poweruser keys are rejected on this endpoint.

### Sender signature

With `authMode` set to `SIGNATURE`, the trigger URL carries no key at all. You paste the plain `?resourceId=` URL into the provider's dashboard, and Autessa checks the provider's signature header on every call using the webhook's `signatureConfig`. A missing or wrong signature is rejected with `401`. See [Signature verification](#signature-verification) for the supported providers.

### Script

With `authMode` set to `SCRIPT`, the trigger URL carries no key either, and there is no `signatureConfig`. Instead, the webhook's validation script checks each call, typically by verifying the sender's signature with the [script helpers](#helpers): an Ed25519, ECDSA, or RSA public-key signature, or an HMAC over whatever fields the sender signs. A call the script doesn't accept is rejected with `401`. A webhook in `SCRIPT` mode can't be saved without a validation script. See [Any other service: scripts](/docs/guide/api-management/webhook-handlers.md#any-other-service-scripts) for worked recipes.

### Public link

With `authMode` set to `PUBLIC`, the URL carries no key, so it is safe to share in DMs, emails, and posts. Use it with a [redirect reply](#redirects) to send people on to another page.

- Only `GET` and `HEAD` are accepted. Any other method gets `405`.
- Each visitor can open the link up to 30 times a minute. Beyond that they get `429` until the minute passes.
- A validation script still runs if you set one.
- Chat apps often open a link to build its preview, and those visits count as opens too. Your tool can check the `User-Agent` header if it matters.
- In `HANDLER_OUTPUT` mode a public link waits at most 10 seconds for its tool.

Autessa redacts the key, and credential headers such as `Authorization`, `X-API-Key`, and cookies, from stored execution history and from what your scripts see. Signature headers are kept, so a script can check them.

> If the webhook has a **validation script** (`validationConfig.validationScript`), it runs on every delivery after the key or signature check (in `SCRIPT` mode, it is the only check). The script receives the method, URL, body, headers, and query parameters, and the request is rejected with `401` if it returns `false`. To stop validating, remove the script. See [Webhook scripts](#webhook-scripts).

**Header:**

```bash
curl 'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF' \
  -H "Authorization: wh:your_key_id:your_key_secret" \
  -H "Content-Type: application/json" \
  -d '{"event": "ping"}'
```

**Query parameter:**

```bash
curl 'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF&key=wh:your_key_id:your_key_secret' \
  -H "Content-Type: application/json" \
  -d '{"event": "ping"}'
```

**Signature:**

```bash
# authMode SIGNATURE with a GITHUB signatureConfig:
# no key in the URL, the body is signed with the shared secret
curl 'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF' \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=5d61605c3feea9799210ddcb71307d4ba264225f" \
  -d '{"action": "opened"}'
```

---

## How execution works

Every request to the trigger URL goes through the same pipeline:

1. **Handshake** — if the request is a verification handshake the webhook is set up to answer (see [Verification handshakes](#verification-handshakes)), including one a handshake script answers, Autessa replies right away without running the handler. History shows it as `HANDSHAKE`.
2. **Authenticate** — the webhook is looked up by `resourceId`, the key and/or sender signature is verified, and the validation script runs if the webhook has one (in `SCRIPT` mode the validation script is the check). Failures return `401` immediately and are recorded in history as `REJECTED` with the reason.
3. **Drop duplicates** — if this delivery's ID was already seen within the dedupe window, the sender gets the normal success reply and nothing runs again. History shows it as `DUPLICATE`. See [Duplicate deliveries](#duplicate-deliveries).
4. **Transform** — the body, headers, and query parameters are turned into a flat map of variables using the webhook's transform configuration (JSONPath mappings or an AutessaScript transform). Form-encoded bodies (Twilio, Slack slash commands) are read as a JSON object, so JSONPath and scripts work on them the same way. If the transform fails, the delivery is recorded as `TRANSFORM_FAILED` and the handler doesn't run, but the sender still gets the success status (with `"success": false` in the default JSON body).
5. **Reply** — by default the sender receives the `executionId` right away, with status `200` when the webhook has a `signatureConfig` or `handshakeConfig` and `202 Accepted` otherwise. The reply can be customized, or can carry a tool's output (see [Customizing the reply](#customizing-the-reply)).
6. **Execute** — the configured handler (tool, agent, manager, or AutessaDB operation) runs in the background, with the transformed variables substituted into its inputs via `@@{variableName}` references. If it fails, it is retried under the webhook's [retry settings](#retries-and-replay). The execution record is updated with the result.

Problems inside your own configuration, such as a transform that throws or a handler that fails in the background, are recorded in execution history, but the sender still gets the success status. That keeps providers from retrying the same event over and over or disabling your endpoint. Correlate deliveries with the `executionId` when reviewing execution history. (Every response also carries a separate per-request `X-Request-Id` header.)

---

## Trigger a webhook **POST** `/clients/custom-webhooks`

Delivers an event to a webhook handler. `POST` with a JSON body is the most common shape, but `PUT`, `PATCH`, and `DELETE` behave identically — the method is recorded in execution history and otherwise does not change processing.

### Query Parameters

- `resourceId` (string, required) — The ID of the webhook to trigger. This is baked into the trigger URL shown for the webhook in the builder.
- `authorization` (string) — The webhook API key, as an alternative to a header (see [Authentication](#authentication)). `auth`, `apiKey`, and `key` are accepted as well.
- `*` (string) — Any additional query parameters are passed through to the validation script and payload transform as `queryParams`, with the key redacted.

### Headers

- `Authorization` (string) — The webhook API key (`wh:{keyId}:{keySecret}`), with or without a `Bearer` prefix. `X-API-Key` works too. Not needed when the key is in the URL or the webhook uses `SIGNATURE` or `SCRIPT` mode.
- `Content-Type` (string) — The body content type. JSON and form-encoded (`application/x-www-form-urlencoded`) bodies are both mapped by JSONPath and transform scripts.
- `*` (string) — All request headers are passed through to the validation script and payload transform as `headers`, with the key and other credential headers redacted. Signature headers are passed through.

### Request Body

There is no required schema. The body (up to 10&nbsp;MB) is delivered byte for byte to the validation script as `body` and to the payload transform as `payload`. Send whatever the external system produces; the webhook's transform configuration maps it to the variables your handler needs.

### Response

With the default reply, the fields below are returned with `202 Accepted` (or `200` when the webhook has a `signatureConfig` or `handshakeConfig`). A webhook with a [`responseConfig`](#customizing-the-reply) can return its own status, content type, and body instead.

- `success` (boolean) — `true` if the request was accepted for execution; `false` if the payload transform failed.
- `message` (string) — Human-readable status, e.g. `"Webhook execution queued successfully"`.
- `executionId` (string) — Unique ID for this delivery. Use it to find the delivery in the webhook's execution history.
- `webhookId` (string) — ID of the webhook that was triggered.
- `errors` — "> Array of error messages if any occurred.

The `X-Request-Id` response header carries a per-request correlation ID.

**cURL:**

```bash
curl --request POST \
  --url 'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: wh:your_key_id:your_key_secret' \
  --data '{
    "event": "payment.succeeded",
    "customer": {
      "email": "jane@example.com",
      "name": "Jane Doe"
    },
    "amountCents": 4900
  }'
```

**JavaScript:**

```javascript
const response = await fetch(
  'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'wh:your_key_id:your_key_secret'
    },
    body: JSON.stringify({
      event: 'payment.succeeded',
      customer: {
        email: 'jane@example.com',
        name: 'Jane Doe'
      },
      amountCents: 4900
    })
  }
);

const data = await response.json(); // 202 Accepted
console.log(data.executionId);
```

**Python:**

```python
import requests

response = requests.post(
    'https://api.autessa.com/clients/custom-webhooks',
    params={'resourceId': 'wH6pJ3sF'},
    headers={
        'Content-Type': 'application/json',
        'Authorization': 'wh:your_key_id:your_key_secret'
    },
    json={
        'event': 'payment.succeeded',
        'customer': {
            'email': 'jane@example.com',
            'name': 'Jane Doe'
        },
        'amountCents': 4900
    }
)

data = response.json()  # 202 Accepted
print(data['executionId'])
```

```json title="202 Accepted"
{
  "success": true,
  "message": "Webhook execution queued successfully",
  "executionId": "3f1c9a52-8f0e-4a7d-9b6f-2d4c1e8a7b31",
  "webhookId": "V1StGXR8Z5"
}
```

---

## Trigger with GET **GET** `/clients/custom-webhooks`

Some senders (email link trackers, simple pingers, legacy systems) can only issue `GET` requests. The endpoint accepts them at the same URL — carry your event data in query parameters instead of a body.

Every query parameter (including `resourceId`, with the key redacted) is available to the validation script and payload transform as `queryParams`, so an AutessaScript transform can map them to handler variables.

### Query Parameters

- `resourceId` (string, required) — The ID of the webhook to trigger.
- `authorization` (string) — The webhook API key, if not sent as a header. `auth`, `apiKey`, and `key` are accepted as well.
- `*` (string) — Your event data — arbitrary key-value pairs, passed through to the transform.

### Response

Identical to the `POST` response: by default `202 Accepted` (or `200` for a webhook with a `signatureConfig` or `handshakeConfig`) with `success`, `message`, `executionId`, and `webhookId`.

**cURL:**

```bash
curl --request GET \
  --url 'https://api.autessa.com/clients/custom-webhooks?resourceId=wH6pJ3sF&event=user.signup&email=jane%40example.com' \
  --header 'Authorization: wh:your_key_id:your_key_secret'
```

**JavaScript:**

```javascript
const params = new URLSearchParams({
  resourceId: 'wH6pJ3sF',
  event: 'user.signup',
  email: 'jane@example.com'
});

const response = await fetch(
  `https://api.autessa.com/clients/custom-webhooks?${params}`,
  {
    headers: {
      'Authorization': 'wh:your_key_id:your_key_secret'
    }
  }
);

const data = await response.json(); // 202 Accepted
```

**Python:**

```python
import requests

response = requests.get(
    'https://api.autessa.com/clients/custom-webhooks',
    params={
        'resourceId': 'wH6pJ3sF',
        'event': 'user.signup',
        'email': 'jane@example.com'
    },
    headers={'Authorization': 'wh:your_key_id:your_key_secret'}
)

data = response.json()  # 202 Accepted
```

```json title="202 Accepted"
{
  "success": true,
  "message": "Webhook execution queued successfully",
  "executionId": "9d2b7e10-4c3a-4f58-a1e2-6b8f0d5c9e44",
  "webhookId": "V1StGXR8Z5"
}
```

---

## Configuring handlers

The trigger endpoint is only half of a webhook — the other half is the handler configuration you create in the builder, which controls:

- **Handler resource** — the tool, agent, manager, or AutessaDB operation to execute for each delivery, and the inputs it receives (with `@@{variableName}` references to transformed variables).
- **Payload transform** — JSONPath mappings over the body, or an AutessaScript transform with access to `payload`, `headers`, and `queryParams`, producing the variable map.
- **Authentication** — `authMode`, plus a `signatureConfig` when the sender signs its requests with a built-in scheme, or a validation script in `SCRIPT` mode.
- **Handshakes, reply, and duplicates** — `handshakeConfig`, `responseConfig`, and `dedupeConfig`, described below.
- **Validation script** — request-authenticity check (allow-listing, a signature scheme not covered below) that runs on every delivery whenever the webhook has a `validationConfig.validationScript`; remove the script to stop validating. It is required in `SCRIPT` mode. It can check an HMAC against an Autessa Secret with `secrets.verifyHmac` or `secrets.verifyHmacSha256`, or a public-key signature with `cryptoUtils.verifySignature`. See [Webhook scripts](#webhook-scripts).
- **API key lifecycle** — the webhook key is shown once at creation and can be rotated at any time; rotating it invalidates the old key immediately.

See [Webhook Handlers](/docs/guide/api-management/webhook-handlers.md) for the full configuration walkthrough and provider recipes (including [Any other service: scripts](/docs/guide/api-management/webhook-handlers.md#any-other-service-scripts) for Discord, Twitch, Twitter/X, SendGrid, PayPal, and AWS SNS), and the [management API](/docs/api/poweruser/custom-webhooks.md#the-webhookconfig-object) for every field.

---

## Signature verification

Set `authMode` to `SIGNATURE` (or `API_KEY_OR_SIGNATURE`) and add a `signatureConfig`:

```json
{
  "authMode": "SIGNATURE",
  "signatureConfig": {
    "scheme": "STRIPE",
    "secretName": "stripe-signing-secret"
  }
}
```

`secretName` names an [Autessa Secret](/docs/guide/agentic/secrets.md) that holds the provider's signing secret. The secret's value is never stored in the webhook itself. Saving the webhook adds it to the secret's [What can use it](/docs/guide/agentic/secrets.md#what-can-use-a-secret) list if you have **Use** on the secret; the check works only while the person who last saved the webhook's configuration has Use. With `authMode` left at `API_KEY`, a `signatureConfig` adds the signature check on top of the key: both are required.

| `scheme` | Providers | Signature header | Secret to store |
| --- | --- | --- | --- |
| `META` | Meta, Instagram, WhatsApp | `X-Hub-Signature-256` | The app's App Secret |
| `GITHUB` | GitHub | `X-Hub-Signature-256` | The webhook secret |
| `STRIPE` | Stripe | `Stripe-Signature` | The endpoint's signing secret (`whsec_...`) |
| `SLACK` | Slack | `X-Slack-Signature` and `X-Slack-Request-Timestamp` | The app's Signing Secret |
| `SHOPIFY` | Shopify | `X-Shopify-Hmac-Sha256` | The app's webhook secret |
| `TWILIO` | Twilio | `X-Twilio-Signature` | The account's Auth Token |
| `SVIX` | Svix and Standard Webhooks senders, such as Resend and Clerk | `svix-id`, `svix-timestamp`, `svix-signature` | The endpoint's signing secret (`whsec_...`) |
| `GENERIC_HMAC` | Any sender that signs the raw body with an HMAC | You choose | The shared secret |

For `STRIPE`, `SLACK`, and `SVIX`, the signed timestamp must be recent: `toleranceSeconds` sets the maximum age (default `300`).

For `TWILIO`, the signature covers the full URL, so the URL configured in Twilio must be exactly the URL Autessa shows for the webhook.

`GENERIC_HMAC` uses these extra fields, and the HMAC is computed over the raw request body:

| Field | Meaning |
| --- | --- |
| `header` | The header that carries the signature. |
| `algorithm` | `SHA256` (default), `SHA1`, or `SHA512`. |
| `encoding` | `HEX` (default) or `BASE64`. |
| `prefix` | Text removed from the header value before comparing, such as `sha256=`. |

---

## Verification handshakes

Many providers check a new webhook URL before they send real events, by sending a challenge and expecting it echoed back. A `handshakeConfig` answers these immediately: the handler does not run, and the call appears in history as `HANDSHAKE`.

```json
{
  "handshakeConfig": {
    "preset": "META",
    "verifyToken": "a-random-string-you-also-paste-into-meta"
  }
}
```

| `preset` | Request it answers | Reply |
| --- | --- | --- |
| `META` | `GET` with `hub.mode=subscribe`; `hub.verify_token` must equal `verifyToken` | `200`, `text/plain`, the `hub.challenge` value |
| `SLACK` | `POST` with `{"type": "url_verification", "challenge": "..."}` | `200`, `text/plain`, the challenge. The signature is still checked when a `SLACK` signature is configured. |
| `MS_GRAPH` | A `validationToken` query parameter | `200`, `text/plain`, the token |
| `DROPBOX` | `GET` with a `challenge` query parameter | `200`, `text/plain`, the challenge |
| `ZOOM` | `POST` with event `endpoint.url_validation` | `200`, JSON `{"plainToken": "...", "encryptedToken": "..."}`, where `encryptedToken` is the hex HMAC-SHA256 of `plainToken` keyed by your Zoom Secret Token. Set `secretName` to the Autessa Secret holding that token. |
| `X` | `GET` with a `crc_token` query parameter | `200`, JSON `{"response_token": "sha256=..."}`, the base64 HMAC-SHA256 of `crc_token` keyed by your X app's consumer secret. Set `secretName` to the Autessa Secret holding it. A token containing `{` or `[`, or longer than 512 characters, is refused, so the answer can never be used as a delivery signature. |

A handshake `secretName` works the same way as a signature one: saving adds the webhook to that secret's list if you have Use.

For any other provider, use `"preset": "CUSTOM"` with `rules`. Rules also work alongside a preset, and are checked after it. Each rule matches a request and says what to reply:

| Field | Meaning |
| --- | --- |
| `method` | HTTP method to match. Omit to match any. |
| `whenSource` | Where the field lives: `QUERY`, `HEADER`, or `BODY`. |
| `whenPath` | The query parameter or header name, or a dotted path into the body such as `data.kind`. |
| `whenEquals` | The value the field must have. Omit to match whenever the field is present. |
| `replyStatus` | Reply status. Default `200`. |
| `replyContentType` | Reply content type. Default `text/plain`. |
| `replyFrom` | What to reply with: `query.<name>`, `header.<name>`, `body.<path>`, or any other text, sent as-is. |

```json
{
  "handshakeConfig": {
    "preset": "CUSTOM",
    "rules": [
      {
        "method": "GET",
        "whenSource": "QUERY",
        "whenPath": "crc_token",
        "replyFrom": "query.crc_token"
      }
    ]
  }
}
```

### Handshake script

When a rule can't express the answer, because it has to be computed (Twitter/X's CRC token) or because the sender expects you to call it back to confirm a subscription (AWS SNS), add a `handshakeConfig.script`. It is checked after the preset and the rules, on every call, and it can be used on its own, with no preset:

```json
{
  "handshakeConfig": {
    "script": "…the handshake script…"
  }
}
```

The script decides what the call is:

- If it sets no response, the call is a normal delivery and goes on to authentication and the handler.
- If it calls `response.setResponse(JSON.stringify({status, contentType, body}))`, that is the reply, and the call is recorded as `HANDSHAKE`.
- If it calls `response.setResponse('text')`, the reply is `200` with that text as `text/plain`.
- If it throws, the call is refused with `401` and the same `{"error": "This webhook call was refused."}` as any other refused call (see [Errors](#errors)). The script's own error is kept in the webhook's history, not sent to the caller.

Anyone with the webhook URL can make a handshake script run, so what it can do is limited, and nothing it gets from elsewhere is sent back to the caller:

- It can use only the `api`, `secrets`, `cryptoUtils`, and `mathUtils` helpers. The `autessa` SDK, tools, agents, and the database aren't available.
- Its `api` calls are sent, so it can call the sender back to confirm a subscription, but each returns only `{statusCode}` (plus `error` and `errorCode` when the call failed), never the body or headers. They are rate limited per webhook.
- Once it has called out (with `api` or `cryptoUtils.fetchCertificate`), the reply is a plain `200` with an empty body, whatever the script set. A test delivery notes when this happens.

To answer callers with data you fetch, run a tool from the webhook and reply with its output instead.

A handshake runs before authentication, so the validation script has not run yet when the handshake script does. A handshake script that answers or acts on a call must check the sender's signature itself. See [Webhook scripts](#webhook-scripts) for the variables and helpers it can use.

---

## Webhook scripts

Three scripts can run on a delivery. Each is AutessaScript, run as the person who last saved the webhook's configuration (its owner, if no one else has edited it), so `secrets.*` helpers and signing secrets work only for [Autessa Secrets](/docs/guide/agentic/secrets.md) that list this webhook under [What can use it](/docs/guide/agentic/secrets.md#what-can-use-a-secret) and that person has **Use** on. If that person loses Use or leaves the company, those checks fail until someone with Use saves the webhook again:

| Script | Field | Runs | Decides |
| --- | --- | --- | --- |
| Handshake | `handshakeConfig.script` | First, on every call | Whether the call is a handshake, and the reply |
| Validation | `validationConfig.validationScript` | After the key or signature check; in `SCRIPT` mode, it is the check | Whether the call is accepted |
| Transform | `payloadTransformConfig.transformScript` | After authentication, with `transformType: AUTESSA_SCRIPT` | The variables passed to the handler |

### Variables

Validation and handshake scripts read these with `variables.get(...)`:

| Variable | Value |
| --- | --- |
| `method` | The HTTP method. |
| `url` | The public webhook URL, including the query string. |
| `path` | What follows the ID in a short URL, such as `/summer-sale`, or empty. |
| `body` | The raw body, exactly as sent. Signatures are computed over this. |
| `headers` | A JSON string of the headers, with their original names. |
| `headersLower` | A JSON string of the headers, with lower-cased names. Use this one, since senders and proxies vary the case. |
| `queryParams` | A JSON string of the query parameters and form fields. |

Keys are redacted from `headers`, `headersLower`, and `queryParams`.

The transform script keeps its own variables: `payload` (the raw body), `headers`, `queryParams`, and `path`.

### Helpers

| Helper | What it does |
| --- | --- |
| `cryptoUtils.verifySignature(algorithm, publicKey, message, signature[, encoding='BASE64'])` | Verifies a public-key signature and returns `true` or `false`. `algorithm` is `ED25519`, `ECDSA_P256_SHA256`, `RSA_SHA256`, `RSA_SHA1`, or `RSA_PSS_SHA256`. `publicKey` is a PEM certificate, a PEM public key, base64 DER, or hex (a raw 32-byte Ed25519 key is accepted). `encoding` is `HEX` or `BASE64`. An ECDSA signature may be DER or raw r\|\|s. |
| `cryptoUtils.fetchCertificate(url, ['host', '*.suffix'])` | Fetches a PEM over https, only from the listed hosts, and caches it for 1 hour. |
| `cryptoUtils.hmac(key, message[, algorithm='SHA256', encoding='HEX'])` | An HMAC with a key you have in the script. `encoding` is `HEX`, `BASE64`, or `BASE64URL` (URL-safe base64 without padding, as used in JWTs). |
| `cryptoUtils.sha256Hex(s)`, `cryptoUtils.sha256Base64(s)` | SHA-256 of a string, as hex or base64. |
| `cryptoUtils.sha256(s, encoding)` | SHA-256 of a string in the given `encoding`: `HEX`, `BASE64`, or `BASE64URL`. |
| `cryptoUtils.crc32(s)` | CRC32 of a string, as an unsigned decimal string. |
| `cryptoUtils.timingSafeEqual(a, b)` | Compares two strings in constant time. |
| `secrets.verifyHmac(secretName, message, signature[, {algorithm, encoding, prefix}])` | Checks an HMAC keyed by an Autessa Secret, in constant time; the secret is never exposed to the script. `algorithm` is `SHA256` (default), `SHA1`, or `SHA512`; `encoding` is `HEX` or `BASE64`; `prefix` is text such as `sha256=` removed from the signature first. |
| `secrets.verifyHmacSha256(secretName, message, signatureHex)` | Checks a hex HMAC-SHA256 keyed by an Autessa Secret. |
| `api.get(JSON.stringify({endpoint: url, headers: {...}}))` | Makes an outbound GET and returns a JSON string `{statusCode, body, headers}`; in a handshake script, only `{statusCode}` (see [Handshake script](#handshake-script)). Outbound calls are protected against reaching internal addresses. |

Webhook scripts can check a signature with an Autessa Secret but never make one: they can answer callers who haven't signed in, so a signature made there would be one anyone could ask for. To answer X's CRC check, use the `X` handshake preset.

### Return values

- **Validation script:** `response.setResponse(String(true))` accepts the call; `response.setResponse(String(false))` rejects it with `401`.
- **Handshake script:** set no response for a normal delivery; `response.setResponse(JSON.stringify({status, contentType, body}))` to answer the call; or `response.setResponse('text')` for a `200` `text/plain` reply. Throwing refuses the call with `401`.
- **Transform script:** the JSON object of variable mappings.

For example, a validation script for a sender that signs `timestamp + body` with Ed25519 (this is Discord's scheme):

```js
const PUBLIC_KEY = 'YOUR_DISCORD_PUBLIC_KEY_HEX';
const h = JSON.parse(variables.get('headersLower'));
const ok = cryptoUtils.verifySignature('ED25519', PUBLIC_KEY,
    (h['x-signature-timestamp'] || '') + variables.get('body'), h['x-signature-ed25519'] || '00', 'HEX');
response.setResponse(String(ok));
```

Worked recipes for Discord, Twitch EventSub, Twitter/X, SendGrid, PayPal, and AWS SNS are in [Any other service: scripts](/docs/guide/api-management/webhook-handlers.md#any-other-service-scripts). To try a script against a sample call before pointing the sender at it, use [`autessa custom-webhooks test`](/docs/guide/api-management/webhook-handlers.md#test-and-replay-from-the-cli).

---

## Customizing the reply

A `responseConfig` controls what the sender receives. Without one, the endpoint answers with the JSON shown above: status `200` when the webhook has a `signatureConfig` or `handshakeConfig`, `202 Accepted` otherwise.

| Field | Meaning |
| --- | --- |
| `mode` | `ACK` (default) or `HANDLER_OUTPUT`. |
| `statusCode` | Reply status. Defaults to `200` when the webhook has a `signatureConfig` or `handshakeConfig`, otherwise `202`. |
| `contentType` | Reply content type. Default `application/json`. |
| `bodyTemplate` | Reply body. Omit to keep the default JSON. |
| `headers` | Fixed reply headers, such as `Location` for a [redirect](#redirects). |
| `syncTimeoutSeconds` | `HANDLER_OUTPUT` only: how long to wait for the tool. Default `10`, maximum `25` (`10` for a public link). |

**`ACK`** replies immediately and runs the handler afterwards. The default body is:

```json
{"success": true, "message": "Webhook execution queued successfully", "executionId": "...", "webhookId": "..."}
```

`bodyTemplate` can use `@@{executionId}`, `@@{webhookId}`, `@@{query.<name>}`, `@@{header.<name>}`, and `@@{body.<path>}`. For example, a plain-text `ok`:

```json
{
  "responseConfig": {
    "mode": "ACK",
    "statusCode": 200,
    "contentType": "text/plain",
    "bodyTemplate": "ok"
  }
}
```

**`HANDLER_OUTPUT`** (TOOL handlers only) runs the tool during the request and sends its result as the reply. If the tool returns an object with `status`, `contentType`, and `body`, those are used as the reply, which is how you answer Twilio with TwiML or a Slack slash command with a message:

```json
{
  "status": 200,
  "contentType": "text/xml",
  "body": "<Response><Message>Thanks, we got it.</Message></Response>"
}
```

The object can also carry `headers`, and `body` can be left out when `headers` is set, as in a [redirect](#redirects).

Any other result is returned as JSON (for objects) or as text. If the tool fails, the sender gets `500` with `{"error": "..."}`. If the tool takes longer than `syncTimeoutSeconds`, the sender gets the `ACK` reply and the tool finishes in the background, with its result in history. The tool never runs twice.

### Redirects

A reply with a `3xx` status and a `Location` header sends the browser on to another page. That makes a webhook a trackable link: the click runs your handler, and the visitor lands where you choose.

To send every visit to the same page, set it in `responseConfig`. A `3xx` status in `responseConfig` must come with a `Location`. The handler still runs in the background.

```json
{
  "authMode": "PUBLIC",
  "responseConfig": {
    "statusCode": 302,
    "headers": { "Location": "https://example.com/landing-page" }
  }
}
```

To choose the destination per visit, use `HANDLER_OUTPUT` and have the tool return the redirect:

```json
{
  "status": 302,
  "headers": { "Location": "https://example.com/offers/summer-sale" }
}
```

### Reply headers

Headers can come from `responseConfig.headers` or from a tool's result. Only headers that describe the reply can be set:

- `Location`. It must be a full address starting with `https://` or `http://`.
- `Cache-Control`, `Content-Disposition`, `Content-Language`, `Vary`, `ETag`, `Last-Modified`, `Expires`, `Retry-After`, and `Link`.
- Your own headers starting with `X-`.

Cookies, CORS headers, and security headers can't be set. Neither can `Content-Type`; use `contentType` instead.

In `responseConfig`, a header that isn't allowed stops the webhook from saving. In a tool's result, it is left out of the reply.

Values can't contain line breaks or be longer than 2,048 characters. A reply can set at most 20 headers.

### Reply content types

A reply is data for the service that called the webhook, never a web page. So:

- HTML, XHTML, SVG, JavaScript, and CSS can't be used as `contentType`. A webhook that sets one won't save, and a tool's result that asks for one is sent as `text/plain`.
- JSON, plain text, and CSV replies display in a browser as they are. Every other type, such as XML (TwiML) or a PDF, is sent with `Content-Disposition: attachment`, so a browser downloads it instead of showing it. Services that call webhooks, such as Twilio, read the body as usual. A tool's own `attachment; filename=...` is kept.
- Every reply is sent with `Content-Security-Policy: sandbox; default-src 'none'; frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, and `Referrer-Policy: no-referrer`.

To show people a page after they open a webhook link, [redirect](#redirects) them to it, for example to a custom app.

---

## Duplicate deliveries

Providers retry when they don't hear back in time, so the same event can arrive more than once. A delivery whose ID was already seen within the window gets the normal success reply and is not run again; history shows it as `DUPLICATE`.

Webhooks with a `signatureConfig` whose provider sends a delivery ID dedupe on it automatically:

| `scheme` | Deduped on |
| --- | --- |
| `GITHUB` | `X-GitHub-Delivery` header |
| `STRIPE` | Body `id` |
| `SLACK` | Body `event_id` |
| `SHOPIFY` | `X-Shopify-Webhook-Id` header |
| `SVIX` | `svix-id` header |

`META`, `TWILIO`, and `GENERIC_HMAC` don't dedupe by default, and neither do webhooks in `SCRIPT` mode. To choose the field yourself, or to dedupe a key- or script-authenticated webhook, add a `dedupeConfig`:

```json
{
  "dedupeConfig": {
    "source": "BODY",
    "path": "event.id",
    "windowHours": 72
  }
}
```

`source` is `HEADER` or `BODY`; `path` is a header name or a dotted path into the body. `windowHours` defaults to `72`. A `dedupeConfig` with an empty `path` turns deduplication off.

---

## Retries and replay

When the handler fails in the background, Autessa runs it again under the webhook's `executionSettings`: up to `maxRetries` more times (default `3`), waiting `retryDelaySeconds` before the first retry (default `5`) and doubling the wait on each attempt, up to 15 minutes. History shows the waiting attempt as `RETRYING`, with its attempt number. Retries don't apply to a tool answering the sender directly with `HANDLER_OUTPUT`.

Anyone with edit access can run a stored delivery again from the webhook's execution history page with **Replay**. The replay is a new execution that uses the webhook's *current* transform, handler, and reply settings, so it's the way to re-run deliveries after fixing a mapping. `HANDSHAKE`, `REJECTED`, and `DUPLICATE` entries can't be replayed. From the CLI, `autessa custom-webhooks replay --executionId <executionId>` does the same, and `autessa custom-webhooks test` runs a sample call through the webhook's real checks without a sender; see [Test and replay from the CLI](/docs/guide/api-management/webhook-handlers.md#test-and-replay-from-the-cli).

---

## Errors

Authentication and lookup failures are rejected **before** anything runs, with a `401` and one body, whatever the reason:

```json title="401 Unauthorized"
{
  "error": "This webhook call was refused."
}
```

The answer is the same for a missing or unknown webhook ID, a disabled webhook, a missing, malformed, wrong or disabled key, a missing or bad signature, a validation script that refused the call, and a handshake that was refused. Telling callers which of these happened would let anyone check whether a webhook ID is real. The actual reason for a key, signature, validation or handshake refusal is recorded in the webhook's execution history as `REJECTED`, and **Test** in the editor (or `autessa custom-webhooks test`) shows it too. Calls to a disabled webhook aren't recorded.

| Status | Body | When |
| --- | --- | --- |
| `401` | `{"error": "This webhook call was refused."}` | Any authentication or lookup failure (see above). |
| `405` | `{"error": "This public link only accepts GET requests."}` | A public link was called with a method other than `GET` or `HEAD`. |
| `429` | `{"error": "Too many requests; please wait a minute and try again."}` | A visitor opened a public link more than 30 times in a minute. |
| `500` | `{"error": "..."}` | `HANDLER_OUTPUT` only: the tool answering the sender failed. |
| `503` | Error message | A temporary problem on Autessa's side. The delivery was not accepted, so the sender should retry it, and providers do so automatically. |

A transform failure does not change the status: the sender gets the usual success status, and the default JSON body carries `"success": false`. The delivery is recorded as `TRANSFORM_FAILED`:

```json title="Transform failed"
{
  "success": false,
  "message": "Failed to transform webhook payload",
  "executionId": "3f1c9a52-8f0e-4a7d-9b6f-2d4c1e8a7b31",
  "webhookId": "V1StGXR8Z5"
}
```

> A success status means the delivery was accepted — not that the handler succeeded. Problems inside your own configuration (a transform that throws, a tool erroring in the background, an agent timing out) still get the success status, so providers don't keep retrying or disable your endpoint. They are recorded in the webhook's execution history.

---

## Related

- [API Overview](/docs/api.md)
- [Webhook Handlers guide](/docs/guide/api-management/webhook-handlers.md)
- [API Keys](/docs/guide/api-management/api-keys.md)
- [Authentication](/docs/guide/authentication.md)
- [Agent API](/docs/api/agents.md)
- [Manager API](/docs/api/managers.md)
- [Tool API](/docs/api/tools.md)
- [AutessaDB API](/docs/api/autessadb.md)
- [Scheduled Events API](/docs/api/scheduled-events.md)

