# Webhooks

> Receive finished answers at your own URL with automatic retries, and verify the HMAC-SHA256 signature in Node.js or Python before you trust them.

Pass `webhookUrl` when you create a task and we POST the finished task to that URL, so you do not have to poll.

## What you receive

```json
{
  "event": "task.completed",
  "data": { "id": "tsk_...", "status": "COMPLETED", "result": { "text": "...", "sources": [] } }
}
```

`event` is `task.completed` or `task.failed`. `data` is the task, exactly as `GET /v1/tasks/{id}` returns it. A batch sends `batch.completed` once: see [Batches](https://promptgale.com/docs/batches.md).

## Delivery

- Any `2xx` response counts as delivered.
- Other responses and timeouts (30 seconds) are retried 4 more times, after 2, 4, 8 and 16 minutes.
- Redirects are not followed.
- The URL must use `https` and point to a public host. Private, loopback and link-local addresses, `localhost`, `*.local` and `*.internal` are refused with `400` `VALIDATION_ERROR` (`path: webhookUrl`).

## Headers

| Header | Description |
| --- | --- |
| `promptgale-webhook-id` | Unique per delivery and the same on every retry (`whd_<n>`; `batch_<id>` for `batch.completed`). Use it to deduplicate. |
| `promptgale-webhook-timestamp` | Unix seconds when the request was signed. |
| `promptgale-webhook-signature` | `v1,<base64 HMAC-SHA256>`. |
| `plinda-webhook-*` | Deprecated: the same three headers under the older prefix, with identical values. Still sent; read `promptgale-webhook-*` in new code. |
| `x-request-id` | Id of this attempt, for support. |

Deliveries come with `User-Agent: PromptGale-Webhook/1`.

## Verify the signature

The signed message is `${taskId}.${timestamp}.${rawBody}`. The key is the signing secret of the API key that created the task, shown once when the key is created. Tasks created without an API key (MCP over OAuth, the dashboard) are signed with the account webhook secret.

Compute the signature over the raw request body, before any JSON parsing.

**Node.js**

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const SECRET = process.env.PROMPTGALE_SIGNING_SECRET; // shown once when the key is created

// Keep the raw body: the signature covers the exact bytes we sent.
app.post('/hooks/promptgale', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8');
  const timestamp = req.header('promptgale-webhook-timestamp');
  const signature = req.header('promptgale-webhook-signature') ?? '';
  const event = JSON.parse(raw);

  // Reject old deliveries (replay protection): 5 minutes of tolerance.
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(400);

  const expected = crypto
    .createHmac('sha256', SECRET)
    .update(`${event.data.id}.${timestamp}.${raw}`)
    .digest('base64');
  const given = signature.replace(/^v1,/, '');
  const ok =
    given.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
  if (!ok) return res.sendStatus(401);

  // Deduplicate on promptgale-webhook-id, then handle event.data
  res.sendStatus(200);
});
```

**Python**

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

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["PROMPTGALE_SIGNING_SECRET"].encode()

@app.post("/hooks/promptgale")
def promptgale_webhook():
    raw = request.get_data()  # the exact bytes we sent
    timestamp = request.headers.get("promptgale-webhook-timestamp", "")
    signature = request.headers.get("promptgale-webhook-signature", "").removeprefix("v1,")
    event = json.loads(raw)

    # Reject old deliveries (replay protection): 5 minutes of tolerance.
    if abs(time.time() - int(timestamp or 0)) > 300:
        abort(400)

    message = event["data"]["id"].encode() + b"." + timestamp.encode() + b"." + raw
    expected = base64.b64encode(hmac.new(SECRET, message, hashlib.sha256).digest()).decode()
    if not hmac.compare_digest(signature, expected):
        abort(401)

    # Deduplicate on promptgale-webhook-id, then handle event["data"]
    return "", 200
```

---

Docs index: https://promptgale.com/llms.txt · Full reference: https://promptgale.com/llms-full.txt · OpenAPI: https://promptgale.com/v1/openapi.json
