> For the complete documentation index, see [llms.txt](https://diffio.ai/llms.txt). This page is also available as HTML at https://diffio.ai/docs/developers/webhooks/.

# Webhooks: events, signatures and retries

Webhooks notify your server with signed HTTP POST events whenever a project, generation, separated-track stem, export or transcript assistant turn finishes or fails, so your application does not need to poll.

## How webhooks work

1. Diffio: **State transition**. A generation, project, stem, export or turn completes or fails
2. Signed POST: **JSON event**. `svix-id`, `svix-timestamp`, `svix-signature` headers
3. Your endpoint: **Verify, then answer `200`**. Answer fast; any non-2xx response is retried with backoff
4. Background job: **Fetch media or details**. Call generation media or get generation, then update records

**Account scope and portal model**

Webhooks belong to your whole Diffio account rather than a single API key. Once enabled, events fire across all API keys and all end users on the account; every event payload carries `data.end_user` (`null` when created without `Diffio-End-User`).

Development and production use separate webhook portals and applications. Disable CSRF middleware on your webhook route so incoming signed POST requests reach your signature check untouched.

## Add an endpoint

### 1. Open the webhook portal

Call [POST /webhooks/portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) with an API key that has Write permission (a read-only key gets `403`). The first call creates your account's webhook application and turns event delivery on. Open the returned `url` right away: portal links are short-lived, so request a fresh link each time you visit.

Do not send the `Diffio-End-User` header on `POST /webhooks/portal`; the endpoint is account-wide and refuses that header with `403` (`permission_denied`). Both SDKs leave it off this call, even on a client created for an end user.

**Python**

```python
from diffio import DiffioClient

client = DiffioClient()  # reads DIFFIO_API_KEY
portal = client.webhooks.portal()
print(portal.url, portal.event_types)
```

**Node.js**

```javascript
import { DiffioClient } from "diffio";

const client = new DiffioClient(); // reads DIFFIO_API_KEY
const portal = await client.webhooks.portal();
console.log(portal.url, portal.event_types);
```

**cURL**

```bash
curl -sS -X POST "https://api.diffio.ai/v2/webhooks/portal" \
  -H "Authorization: Bearer $DIFFIO_API_KEY"
```

![Webhook portal endpoints list with the Add Endpoint button.](https://diffio.ai/images/docs/webhooks/WebhookPortal1AddEndpointCrop.png)

**Select Add Endpoint in the webhook portal. [Full-size screenshot](https://diffio.ai/images/docs/webhooks/WebhookPortal1AddEndpoint.png)**

> **No server yet**
>
> If you do not have an HTTPS receiver deployed yet, use the portal to create a temporary test receiver URL so you can inspect real deliveries while building your handler.

### 2. Add your endpoint URL and events

Paste your HTTPS endpoint URL and tick the events you handle. Leaving every box clear subscribes the endpoint to all of them.

- **Generations** `generation.completed` `generation.failed` `generation.stems_ready` `generation.stems_failed`
- **Projects** `project.ready` `project.failed`
- **Exports** `export.ready` `export.failed`
- **Assistant turns** `transcript_assistant_turn.completed` `transcript_assistant_turn.failed`

> **About the portal's event list**
>
> - It also lists `generation.queued` and `generation.processing`, kept for an older API. This API never sends them; follow progress with [Get a generation](https://diffio.ai/docs/api-reference/get-generation/).
> - Its sample payloads for `generation.completed` and `generation.failed` show that older schema. Real deliveries use the `{ type, id, created_at, data }` envelope under [Events and payloads](#events).

### 3. Save the signing secret

Open the new endpoint's details page, reveal its `whsec_...` signing secret and store it as `DIFFIO_WEBHOOK_SECRET` in your secret manager. Each endpoint has its own unique secret.

![The Signing Secret row of the endpoint details, with the hidden secret and its reveal button.](https://diffio.ai/images/docs/webhooks/WebhookPortal3SigningSecretRowCrop.png)

**Copy the Signing Secret from the endpoint details. [Full-size screenshot](https://diffio.ai/images/docs/webhooks/WebhookPortal3Endpoint.png)**

## Test endpoints

1. Trigger: **Run a short restore**. Upload a short clip and restore it; there is no test-event API endpoint
2. Inspect: **Portal message log**. View each delivery's payload and your endpoint's response in the portal
3. Confirm: **Signature + `200`**. Your receiver verifies `svix-signature` and returns a `2xx` status

## Events and payloads

Every delivery is `{ type, id, created_at, data }`. `id` is `"evt_"` plus 32 hex characters, the same on every retry, so dedupe on it. Only finished or failed states send events, never progress.

Every `data` has `id`, `project_id`, `end_user` and `status`. The table lists what each event adds.

| Event `type` | `data.object` | `status` | Also in `data` |
| --- | --- | --- | --- |
| `generation.completed` | object `generation` | status `"complete"` | also `kind` (`"restore"` or `"edit"`) |
| `generation.failed` | object `generation` | status `"failed"` | also `kind`, `error_code` |
| `generation.stems_ready` | object `generation` | status the generation's | also `kind`, `stems_status: "ready"` |
| `generation.stems_failed` | object `generation` | status the generation's | also `kind`, `stems_status: "failed"` |
| `export.ready` | object `generation_export` | status `"ready"` | also `generation_id`; `id` ends `-inline` for inline exports |
| `export.failed` | object `generation_export` | status `"failed"` | also `generation_id` |
| `transcript_assistant_turn.completed` | object `transcript_assistant_turn` | status `"complete"` | also `generation_id` |
| `transcript_assistant_turn.failed` | object `transcript_assistant_turn` | status `"failed"` | also `generation_id` |
| `project.ready` | object `project` | status `"ready"` | also none (`project_id` equals `id`) |
| `project.failed` | object `project` | status `"failed"` | also none (`project_id` equals `id`) |

**generation.completed**

```json
{
  "type": "generation.completed",
  "id": "evt_4b8c1d0e9f2a3b4c5d6e7f8091a2b3c4",
  "created_at": "2026-11-13T00:33:41Z",
  "data": {
    "object": "generation",
    "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f",
    "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe",
    "end_user": "customer-42",
    "status": "complete",
    "kind": "restore"
  }
}
```

**generation.failed**

```json
{
  "type": "generation.failed",
  "id": "evt_9a7e6f5d4c3b2a1098f7e6d5c4b3a210",
  "created_at": "2026-11-13T00:35:12Z",
  "data": {
    "object": "generation",
    "id": "80cb25c0-31b4-5e9a-9c71-04d2a1b8e3f9",
    "project_id": "2f8ee512-71a0-5c4d-8e12-91f3b4c5d6e7",
    "end_user": "customer-42",
    "status": "failed",
    "kind": "restore",
    "error_code": "no_speech_detected"
  }
}
```

> **Reading generation and failure details**
>
> - **Generation id location:**: on all four `generation.*` events, the generation id is `data.id` (there is no `generation_id` field on generation payloads). On `export.*` and `transcript_assistant_turn.*` events, `data.id` is the export or turn id and `data.generation_id` names the generation.
> - **Fetching media and errors:**: webhook payloads intentionally stay compact and never embed media URLs or human-readable error messages. On `generation.completed`, call [GET /projects/{project_id}/generations/{generation_id}/media](https://diffio.ai/docs/api-reference/get-generation-media/) (or [GET .../transcript](https://diffio.ai/docs/api-reference/get-transcript/)). On `generation.failed`, `data.error_code` gives the machine-readable code; call [GET /projects/{project_id}/generations/{generation_id}](https://diffio.ai/docs/api-reference/get-generation/) to inspect the full `error` object and `warnings`.

## Verify signatures

Every webhook delivery is signed with Svix headers so you can verify authenticity and reject replay attacks. Always verify against the exact raw request body bytes (or string) before parsing JSON.

Required delivery headers `svix-id` `svix-timestamp` `svix-signature`

### Verify with the Diffio SDK

Both SDKs verify signatures locally with zero external dependencies (default timestamp tolerance: `300` seconds) and return the parsed `{ type, id, created_at, data }` event. In WebCrypto runtimes (Cloudflare Workers, Deno, Bun or browsers), call `client.webhooks.verifySignatureAsync` (or standalone `verifyWebhookSignatureAsync`). Python also exports standalone `diffio.verify_webhook_signature`.

**Python**

```python
import os

from diffio import DiffioClient, WebhookVerificationError

client = DiffioClient()
secret = os.environ["DIFFIO_WEBHOOK_SECRET"]  # the endpoint's whsec_... signing secret from the webhook portal


def handle_webhook(raw_body, headers):
    """raw_body: the request body bytes as received; headers: the request headers (any mapping)."""
    try:
        event = client.webhooks.verify_signature(raw_body, headers, secret)
    except WebhookVerificationError:
        return 400
    if event.type == "generation.completed":
        print("restored", event.data.project_id, event.data.id, event.data.end_user)
    elif event.type == "generation.failed":
        print("failed", event.data.id, event.data.error_code)
    return 200
```

**Node.js**

```javascript
import http from "node:http";
import { DiffioClient, DiffioWebhookVerificationError } from "diffio";

const client = new DiffioClient();
const secret = process.env.DIFFIO_WEBHOOK_SECRET; // whsec_... from the webhook portal

http
  .createServer((req, res) => {
    const chunks = [];
    req.on("data", (chunk) => chunks.push(chunk));
    req.on("end", () => {
      try {
        // Pass the raw body exactly as received.
        const event = client.webhooks.verifySignature(Buffer.concat(chunks), req.headers, secret);
        console.log("verified", event.type, event.id, event.data.id);
        res.writeHead(204).end();
      } catch (error) {
        if (!(error instanceof DiffioWebhookVerificationError)) throw error;
        console.log("rejected", error.message);
        res.writeHead(400).end();
      }
    });
  })
  .listen(Number(process.env.PORT ?? 3000));
```

### Drop-in handlers

Each framework hides the raw body differently, and a parsed body never verifies. These read it the way the signature needs.

**Next.js: app/api/webhooks/diffio/route.ts**

```typescript
import { DiffioWebhookVerificationError, verifyWebhookSignatureAsync } from "diffio";

export async function POST(request: Request) {
  const rawBody = await request.text(); // read once, never request.json()
  try {
    const event = await verifyWebhookSignatureAsync(rawBody, request.headers, process.env.DIFFIO_WEBHOOK_SECRET!);
    // Record event.id and queue the work, then answer quickly.
    console.log(event.type, event.id, event.data.id);
    return new Response(null, { status: 204 });
  } catch (error) {
    if (error instanceof DiffioWebhookVerificationError) return new Response(null, { status: 400 });
    throw error;
  }
}
```

**Express: server.mjs**

```javascript
import express from "express";
import { DiffioWebhookVerificationError, verifyWebhookSignature } from "diffio";

const app = express();

// express.raw keeps the body as a Buffer; register it before any express.json() for this route.
app.post("/webhooks/diffio", express.raw({ type: "application/json" }), (req, res) => {
  try {
    const event = verifyWebhookSignature(req.body, req.headers, process.env.DIFFIO_WEBHOOK_SECRET);
    console.log(event.type, event.id, event.data.id);
    res.sendStatus(204);
  } catch (error) {
    if (!(error instanceof DiffioWebhookVerificationError)) throw error;
    res.sendStatus(400);
  }
});

app.listen(3000);
```

**FastAPI: main.py**

```python
import os

from fastapi import FastAPI, Request, Response
from diffio import WebhookVerificationError, verify_webhook_signature

app = FastAPI()
SECRET = os.environ["DIFFIO_WEBHOOK_SECRET"]


@app.post("/webhooks/diffio")
async def diffio_webhook(request: Request):
    raw_body = await request.body()  # the exact bytes that were signed
    try:
        event = verify_webhook_signature(raw_body, request.headers, SECRET)
    except WebhookVerificationError:
        return Response(status_code=400)
    print(event.type, event.id, event.data.id)
    return Response(status_code=204)
```

**Cloudflare Workers: src/index.ts**

```typescript
import { DiffioWebhookVerificationError, verifyWebhookSignatureAsync } from "diffio";

export default {
  async fetch(request: Request, env: { DIFFIO_WEBHOOK_SECRET: string }): Promise<Response> {
    if (request.method !== "POST") return new Response(null, { status: 405 });
    const rawBody = await request.text();
    try {
      // WebCrypto: the async helper works in Workers, Deno, Bun and browsers.
      const event = await verifyWebhookSignatureAsync(rawBody, request.headers, env.DIFFIO_WEBHOOK_SECRET);
      console.log(event.type, event.id, event.data.id);
      return new Response(null, { status: 204 });
    } catch (error) {
      if (error instanceof DiffioWebhookVerificationError) return new Response(null, { status: 400 });
      throw error;
    }
  },
};
```

### Verify by hand

If you do not use a Diffio SDK (or an official Svix library), verify the HMAC-SHA256 signature directly:

1. Read `svix-id`, `svix-timestamp` (Unix seconds) and `svix-signature` from the headers, plus the raw body bytes.
2. Reject the delivery if `svix-timestamp` is not an integer or differs from the current Unix time by more than `300` seconds.
3. Strip the `whsec_` prefix from your endpoint's signing secret and base64-decode the remaining string into raw key bytes.
4. Compute HMAC-SHA256 over `{svix-id}.{svix-timestamp}.{raw_body}` using those key bytes, then base64-encode the digest.
5. Split `svix-signature` on spaces; each entry has the form `<version>,<digest>`. Compare your digest in constant time against every `v1,` entry and accept if any matches.

**Python**

```python
import base64
import hashlib
import hmac
import json
import time


def verify_svix_webhook(raw_body: bytes, headers: dict, secret: str, tolerance_seconds: int = 300) -> dict:
    lower = {k.lower(): v for k, v in headers.items()}
    msg_id = lower.get("svix-id") or ""
    msg_timestamp = lower.get("svix-timestamp") or ""
    msg_signature = lower.get("svix-signature") or ""
    if not msg_id or not msg_timestamp or not msg_signature:
        raise ValueError("Missing Svix signature headers")

    ts = int(msg_timestamp)
    if abs(time.time() - ts) > tolerance_seconds:
        raise ValueError("Webhook timestamp outside tolerance")

    key = base64.b64decode(secret[len("whsec_"):] if secret.startswith("whsec_") else secret)
    signed_content = f"{msg_id}.{msg_timestamp}.".encode("utf-8") + raw_body
    expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode("ascii")

    for entry in msg_signature.split():
        version, _, digest = entry.partition(",")
        if version == "v1" and hmac.compare_digest(expected, digest):
            return json.loads(raw_body.decode("utf-8"))

    raise ValueError("Webhook signature does not match")
```

**Node.js**

```javascript
import crypto from "node:crypto";

export function verifySvixWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
  const msgId = headers["svix-id"];
  const msgTimestamp = headers["svix-timestamp"];
  const msgSignature = headers["svix-signature"];
  if (!msgId || !msgTimestamp || !msgSignature) {
    throw new Error("Missing Svix signature headers");
  }

  const ts = Number(msgTimestamp);
  if (!Number.isInteger(ts) || Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds) {
    throw new Error("Webhook timestamp outside tolerance");
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const prefix = Buffer.from(`${msgId}.${msgTimestamp}.`, "utf8");
  const bodyBytes = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
  const expected = crypto.createHmac("sha256", key).update(prefix).update(bodyBytes).digest();

  for (const entry of String(msgSignature).split(/\s+/)) {
    const [version, b64] = entry.split(",", 2);
    if (version !== "v1" || !b64) continue;
    const candidate = Buffer.from(b64, "base64");
    if (candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected)) {
      return JSON.parse(bodyBytes.toString("utf8"));
    }
  }
  throw new Error("Webhook signature does not match");
}
```

**cURL / OpenSSL: OpenSSL**

```bash
# Compute the expected Svix signature from raw_body.json, SVIX_ID, SVIX_TIMESTAMP and DIFFIO_WEBHOOK_SECRET
KEY_HEX=$(printf "%s" "${DIFFIO_WEBHOOK_SECRET#whsec_}" | base64 -d | xxd -p -c 256)
EXPECTED_SIG=$( (printf "%s.%s." "$SVIX_ID" "$SVIX_TIMESTAMP"; cat raw_body.json) \
  | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$KEY_HEX" -binary | base64 )
echo "v1,$EXPECTED_SIG"
```

## Retries and recovery

Return any `2xx` HTTP status code (such as `200` or `204`) as soon as signature verification succeeds, and hand downloads or database updates off to a background worker. Any non-`2xx` response or connection failure is retried automatically by Svix with backoff.

- Deduplicate: **Record `event.id` (`evt_...`) before running side effects.** The event `id` is derived from the event type, resource and transition, so it stays identical across every automatic retry and manual redelivery.
- Signature fails: **Verify the raw body with the endpoint's own secret.** Never pass `JSON.stringify(req.body)`: re-serialized JSON changes bytes and breaks the HMAC (see [drop-in handlers](#framework-handlers)). Each endpoint has its own `whsec_...` secret, and timestamps more than 300 seconds from your clock are rejected.
- Missed events: **Inspect and resend deliveries in the webhook portal.** Open a fresh portal link via `POST /webhooks/portal` to review attempt responses and trigger manual redeliveries.

## Next steps

[Open the webhook portal Endpoint reference for `POST /webhooks/portal` and its response schema.](https://diffio.ai/docs/api-reference/open-webhook-portal/) [Get a generation Read full generation status, quality score, warnings and failure details.](https://diffio.ai/docs/api-reference/get-generation/) [Full API guide Projects, upload descriptors, media grants, transcripts and idempotency.](https://diffio.ai/docs/developers/full-api-guide/)
