# Webhooks

> Receive push notifications when tasks finish and verify Standard Webhooks HMAC-SHA256 signatures.

## Events & payload

Kerox sends an HTTP `POST` request with `Content-Type: application/json` to the task's `webhook_url` (or, when the task has none, the default endpoint URL you set in [Console → API → Webhook](/console/webhooks)) whenever a task reaches a terminal state. Only `https://` URLs are accepted. `data` is the full task object, the same as `GET /v1/tasks/{id}` returns:

- `task.succeeded`
- `task.failed`
- `task.canceled`

```json
{
  "type": "task.succeeded",
  "created_at": "2026-11-20T08:01:10Z",
  "data": {
    "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
    "object": "task",
    "model": "bytedance/seedream-5.5",
    "status": "succeeded",
    "source": "api",
    "format": "native",
    "input": {
      "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
      "size": "2K"
    },
    "output": {
      "images": [
        {
          "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
          "content_type": "image/png",
          "width": 2048,
          "height": 2048
        }
      ]
    },
    "error": null,
    "cost": { "amount": "0.0280", "currency": "USD", "status": "settled" },
    "metadata": { "order_id": "A1001" },
    "warnings": [],
    "created_at": "2026-11-20T08:01:02Z",
    "started_at": "2026-11-20T08:01:02Z",
    "completed_at": "2026-11-20T08:01:10Z",
    "expires_at": "2026-11-27T08:01:10Z"
  }
}
```

## Signature verification (Standard Webhooks)

Every delivery is signed using the [Standard Webhooks](https://www.standardwebhooks.com/) specification and carries three headers. Verifying the signature is optional but recommended: it proves the delivery came from Kerox.

| Header | Value |
| --- | --- |
| `webhook-id` | Unique delivery ID (`msg_...`), unchanged across retries — use it for deduplication |
| `webhook-timestamp` | Unix timestamp in seconds when the signature was generated |
| `webhook-signature` | One or more `v1,<base64>` signatures separated by spaces (two appear during the 24 h key-rotation overlap) |

The signed string is `{webhook-id}.{webhook-timestamp}.{raw_body}`, signed with **HMAC-SHA256** using the base64-decoded bytes of your signing secret (shown in [Console → API → Webhook](/console/webhooks)) after stripping the `whsec_` prefix.

> **Verify the raw request body**
>
> Compute the HMAC over the exact UTF-8 bytes received on the wire before parsing or re-serializing JSON. Reject timestamps more than 5 minutes from the current time to prevent replay attacks.

### Verify with the Standard Webhooks SDK

```javascript

const wh = new Webhook(process.env.KEROX_WEBHOOK_SECRET);

export async function handleKeroxWebhook(rawBody, headers) {
  // Throws if the signature is invalid or the timestamp is outside the 5-minute window.
  const event = wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
  console.log(event.type, event.data.id, event.data.status);
}
```
```python
import os
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["KEROX_WEBHOOK_SECRET"])

def handle_kerox_webhook(raw_body: bytes, headers: dict[str, str]):
    event = wh.verify(raw_body, headers)
    print(event["type"], event["data"]["id"], event["data"]["status"])
```

### Verify manually with built-in crypto

```javascript

export function verifyKeroxSignature(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatureHeader = headers['webhook-signature'];
  if (!id || !timestamp || !signatureHeader) {
    throw new Error('Missing webhook signature headers');
  }

  const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
  if (!Number.isFinite(ageSeconds) || ageSeconds > 300) {
    throw new Error('Webhook timestamp outside tolerance');
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest();

  const valid = signatureHeader.split(' ').some((entry) => {
    const [version, sig] = entry.split(',');
    if (version !== 'v1' || !sig) return false;
    const actual = Buffer.from(sig, 'base64');
    return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);
  });

  if (!valid) throw new Error('Invalid webhook signature');
  return JSON.parse(rawBody);
}
```
```python
import base64
import hashlib
import hmac
import json
import time

def verify_kerox_signature(raw_body: str, headers: dict[str, str], secret: str):
    msg_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    sig_header = headers.get("webhook-signature", "")
    if not (msg_id and timestamp and sig_header):
        raise ValueError("Missing webhook signature headers")

    if abs(int(time.time()) - int(timestamp)) > 300:
        raise ValueError("Webhook timestamp outside tolerance")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(
        key,
        f"{msg_id}.{timestamp}.{raw_body}".encode("utf-8"),
        hashlib.sha256,
    ).digest()

    for entry in sig_header.split(" "):
        parts = entry.split(",", 1)
        if len(parts) != 2 or parts[0] != "v1":
            continue
        if hmac.compare_digest(base64.b64decode(parts[1]), expected):
            return json.loads(raw_body)

    raise ValueError("Invalid webhook signature")
```

## Retries, rotation & best practices

- **Success criteria**: Return any HTTP `2xx` within **10 seconds**. Any non-2xx response or timeout counts as failed.
- **Retry schedule**: Backoff intervals of `1m, 5m, 15m, 30m, 1h, 2h, 3h, 4h, 4h, 4h, 4h` — up to **12 attempts** over ~24 hours. Deliveries are kept for 7 days, and a failed delivery can be resent from [Console → API → Webhook](/console/webhooks).
- **Secret rotation**: Rotating your signing secret in the console keeps the previous secret valid for **24 hours**, during which `webhook-signature` includes both `v1,...` signatures separated by a space.
- **Idempotency**: Deduplicate on `webhook-id`, acknowledge with `200` quickly, and process downloads asynchronously. You can always fall back to `GET /v1/tasks/{id}`.
