> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuor.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Outbound Webhooks

> Receive real-time review verdicts with signature verification.

Webhooks let your systems react to reviewer verdicts in real time — for example, updating a record the instant a reviewer corrects a model output, or paging an on-call engineer when a critical trace is rejected.

This page covers receiver setup, payload shape, signature verification, and delivery semantics.

## How webhooks work

1. You configure a webhook URL and secret on a project.
2. Whenever a reviewer submits a verdict in the review workspace — `approve`, `reject`, or `correct` — Tuor enqueues a background job.
3. The background task dispatches an HTTP `POST` request asynchronously to the configured URL with a JSON body and signature headers.
4. Delivery status is recorded in Tuor and can be inspected from the Web Console.

```mermaid theme={null}
sequenceDiagram
    participant Reviewer as Review Workspace
    participant API as Tuor API
    participant Q as Background Task
    participant App as Your Server

    Reviewer->>API: Submit review (approve/reject/correct)
    API->>API: Persist trace + event
    API->>Q: Enqueue webhook delivery
    Q->>App: POST <webhook_url> (signed JSON)
    App-->>Q: 2xx OK
    Q->>API: Record delivery (success)
```

## Configure a webhook

Configure the webhook URL and secret from the **Webhook** section on the project's **Config** tab in the Web Console. The URL must be a publicly reachable `https://` address, and the secret must be at least 16 characters.

Send a test event from the same section, or with [`POST /v1/projects/{project_id}/test-webhook`](https://docs.tuor.dev/api-reference/webhooks/test-project-webhook), to check your receiver.

## Tying webhook events back to your system (the traceback loop)

A webhook payload is the same public `TraceEventResponse` event object returned in trace detail timelines, so it carries the Tuor `trace_id` (also sent in the `X-Tuor-Trace-Id` header) but **not** the trace's `spans` / `trace_config` / `model_output`. Map deliveries back to your own rows by storing the `trace_id` you receive at ingest time.

### 1. Record the trace id at ingest time

Creating a trace returns its Tuor `id`. Persist it against your own row:

```ts theme={null}
const trace = await tuor.createTrace({ project_id, spans, model_output, trace_config });
await db.runs.update(internalRunId, { tuor_trace_id: trace.id });
```

### 2. Look up the row when the webhook arrives

```ts theme={null}
app.post("/tuor", async (req, res) => {
  const { trace_id, event_type, final_output_after } = req.body;
  await db.runs.updateByTuorTraceId(trace_id, {
    verdict: event_type,
    final_output: final_output_after,
  });
  res.sendStatus(200);
});
```

The verdict (`event_type`) and authoritative output (`final_output_after`) are in the event itself, so the common case needs no callback.

## Payload structure

Every webhook delivery uses the same public `TraceEventResponse` shape returned in trace detail timelines. Datetimes are ISO 8601 strings, and enum values are plain strings:

```json theme={null}
{
  "id": "evt_abc123xyz",
  "org_id": "org_2xyz789",
  "trace_id": "trace_555aaa",
  "event_type": "review.corrected",
  "actor_type": "user",
  "actor_id": "user_2def3gh",
  "occurred_at": "2026-05-20T14:19:55Z",
  "trace_version_before": 1,
  "trace_version_after": 2,
  "status_before": "pending",
  "status_after": "corrected",
  "final_output_before": null,
  "final_output_after": { "company": "Google Inc." },
  "corrected_output_before": null,
  "corrected_output_after": { "company": "Google Inc." }
}
```

The payload carries the event and its before/after deltas, plus `trace_id` to link back to the trace — but not the trace's static fields (`spans`, `model_output`, `trace_config`, `output_schema`). Fetch `GET /v1/traces/{trace_id}` if a receiver needs the full canonical trace object.

`webhook.test` payloads are a separate, smaller shape: they include `event_type` (`webhook.test`), `action`, `occurred_at`, and `project`. A test ping has no real event or trace, so it carries no `id` and its `X-Tuor-Event-Id` / `X-Tuor-Trace-Id` headers are blank.

### Field reference

| Field | Description |
| - | - |
| `id` | ID of the trace event. Stable across manual retries, so use it for idempotent receiver-side processing. Also sent in the `X-Tuor-Event-Id` header. |
| `org_id` | Organization that owns the trace event. |
| `trace_id` | The trace this event belongs to. Use it to correlate to your own records. Also sent in the `X-Tuor-Trace-Id` header. |
| `trace_version_before` / `trace_version_after` | The trace's optimistic-locking version before and after the event. `trace_version_after` increases by one per mutation, so use it to order a trace's events. |
| `event_type` | One of `review.approved`, `review.rejected`, `review.corrected`, `webhook.test`. |
| `actor_type` | `user` for actions taken in the Web Console, `api_key` for actions taken with an API key. |
| `actor_id` | The ID of the user or API key that acted. |
| `occurred_at` | ISO 8601 timestamp of the underlying event. |
| `status_before` / `status_after` | Trace status before and after the review. |
| `final_output_before` / `final_output_after` | The authoritative output, before and after. `null` is meaningful (e.g. after a `reject`). |
| `corrected_output_before` / `corrected_output_after` | The stored correction, before and after. |

### Event types

| Event | Fires when |
| - | - |
| `review.approved` | A reviewer (or API caller) submits an approve action. |
| `review.rejected` | A reviewer submits a reject action. |
| `review.corrected` | A reviewer submits a correction. |
| `webhook.test` | You hit `POST /v1/projects/{project_id}/test-webhook` to verify wiring. |

> [!NOTE]
>
> Only review outcomes produce webhook deliveries. Resets, deletes, restores, and tag changes don't call your webhook.

## Request headers

Every webhook request includes:

| Header | Purpose |
| - | - |
| `Content-Type: application/json` | Body is always JSON. |
| `X-Tuor-Event-Id` | Unique event identifier (matches `id` in the body). |
| `X-Tuor-Trace-Id` | The trace's ID. Empty string for `webhook.test` events. |
| `X-Tuor-Signature` | HMAC-SHA256 signature of the raw request body, formatted `sha256=<hex_digest>`. |

## Signature verification

**Always** verify the signature before trusting a webhook body. Tuor signs the **raw request body bytes** with HMAC-SHA256 using the `webhook_secret` you configured on the project.

Use a constant-time comparison; never compare hex strings with `==` in user code.

### Python

```python theme={null}
import hmac
import hashlib

def verify_tuor_signature(raw_body: bytes, header_value: str, secret: str) -> bool:
    if not header_value.startswith("sha256="):
        return False
    expected = hmac.new(
        secret.encode("utf-8"),
        raw_body,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(header_value.split("=", 1)[1], expected)
```

### TypeScript

```ts theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyTuorSignature(
  rawBody: Buffer,
  headerValue: string,
  secret: string,
): boolean {
  if (!headerValue.startsWith("sha256=")) return false;
  const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
  const provided = headerValue.slice("sha256=".length);
  const a = Buffer.from(expected, "hex");
  const b = Buffer.from(provided, "hex");
  return a.length === b.length && timingSafeEqual(a, b);
}
```

> [!WARNING]
>
> Signatures are computed over the **raw bytes** of the request body, *before* any JSON parsing. Frameworks that re-serialize the body will produce a different digest. In Express, use `express.raw({ type: "application/json" })` on the webhook route; in FastAPI, read `await request.body()` before parsing.

### Complete raw-body handlers

Mount the raw-body webhook route before any global JSON parser middleware.

```ts Express theme={null}
import express from "express";

const app = express();
const webhookSecret = process.env.TUOR_WEBHOOK_SECRET!;

app.post("/tuor", express.raw({ type: "application/json" }), (req, res) => {
  const signature = req.header("X-Tuor-Signature") ?? "";

  if (!verifyTuorSignature(req.body, signature, webhookSecret)) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body.toString("utf8"));
  // Store event.id idempotently, then enqueue your own processing.

  return res.sendStatus(204);
});

app.use(express.json());
```

```python FastAPI theme={null}
import json
import os

from fastapi import FastAPI, Header, HTTPException, Request, Response

app = FastAPI()
webhook_secret = os.environ["TUOR_WEBHOOK_SECRET"]

@app.post("/tuor")
async def tuor_webhook(
    request: Request,
    x_tuor_signature: str = Header(default=""),
) -> Response:
    raw_body = await request.body()

    if not verify_tuor_signature(raw_body, x_tuor_signature, webhook_secret):
        raise HTTPException(status_code=401, detail="invalid signature")

    event = json.loads(raw_body)
    # Store event["id"] idempotently, then enqueue your own processing.

    return Response(status_code=204)
```

## Delivery semantics

* **Asynchronous**: review API calls return as soon as the trace is saved; webhooks fire shortly after.
* **Timeout**: 10 seconds per attempt. Any `2xx` response counts as delivered; anything else is a failure.
* **One automatic retry**: if Tuor can't reach your server at all, it tries once more a second later. Once your server responds, with any status, that response is final.
* **Manual retries**: a failed delivery stays failed until you retry it from the **Webhook** section in the Web Console, or with the API.

| Method | Path | Use when |
| - | - | - |
| `GET` | [`/v1/projects/{project_id}/webhook-deliveries`](https://docs.tuor.dev/api-reference/webhooks/list-webhook-deliveries) | List a project's recent deliveries, newest first. |
| `GET` | [`/v1/projects/{project_id}/webhook-deliveries/stats`](https://docs.tuor.dev/api-reference/webhooks/get-webhook-delivery-stats) | Count deliveries by status, for alerting. |
| `POST` | [`/v1/webhook-deliveries/{delivery_id}/retry`](https://docs.tuor.dev/api-reference/webhooks/retry-webhook-delivery) | Send a delivery again. |

If your setup needs delivery guarantees beyond these, [get in touch](mailto:support@tuor.dev).

## Receiver checklist

* [ ] Listen on a stable, publicly routable HTTPS URL.
* [ ] Respond with `2xx` only **after** you've durably stored the event (or are sure you can drop it).
* [ ] Verify `X-Tuor-Signature` on every request — constant-time compare.
* [ ] Deduplicate on the event `id` (or the `X-Tuor-Event-Id` header). Retries reuse the same `id`.
* [ ] Process within 10 seconds; for heavy work, hand off to your own background queue and return immediately.
* [ ] Handle `webhook.test` events gracefully — they carry no trace data and identify the project being tested.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.