# Webhook Signature Verification

Every PAX webhook delivery carries an `X-PAX-Signature` header. This page shows exactly how to verify it, including behavior during a 24h dual-secret grace window after you rotate.

## The signature header

Format:

```
X-PAX-Signature: t=<unix_ms>,v1=<hex>[,v1=<hex>]
```

Each `v1=` value is `HMAC-SHA256(secret, "<t>.<raw_body>")` in lowercase hex. The signed message is the timestamp, a literal dot, and the request body **exactly as received on the wire** — do not re-serialize JSON, do not trim whitespace.

During the 24h grace after a rotate the header contains **two** `v1=` values: the first signed with the new secret, the second with the previous secret. **Accept if any one matches your configured secret.** Outside of grace only one `v1=` is present.

## Verification algorithm

1. Read `X-PAX-Signature` and the raw request body (before JSON parsing).
2. Split on `,` and pull the `t=` value and every `v1=` value.
3. Reject if `|now - t|` is above your replay tolerance (recommend 5 minutes).
4. Compute `HMAC-SHA256(your_secret, t + "." + raw_body)`.
5. Constant-time compare against each `v1=`. Accept on first match.

**Rotation window.** When you rotate, you get a new `whsec_*`. Immediately store it alongside the old one and try both in the verify path — do NOT delete the old secret until `grace_expires_at_ms` has passed. Standard "single stored secret" implementations will start dropping the second delivery within seconds of rotation.

## Python (Flask)

```
import hmac, hashlib, re, time, os
from flask import request, abort

SIGNING_SECRETS = [os.environ["PAX_WEBHOOK_SECRET_CURRENT"],
                   os.environ.get("PAX_WEBHOOK_SECRET_PREVIOUS", "")]
SIGNING_SECRETS = [s for s in SIGNING_SECRETS if s]
TOLERANCE_MS = 5 * 60 * 1000

@app.post("/webhook/pax")
def pax_webhook():
    header = request.headers.get("X-PAX-Signature", "")
    raw = request.get_data()  # exact bytes — do not use request.json
    pairs = [p.split("=", 1) for p in header.split(",") if "=" in p]
    t = next((v for k, v in pairs if k == "t"), "")
    if not re.fullmatch(r"[0-9]{1,16}", t):
        abort(400, "missing or malformed signature timestamp")
    if abs(int(time.time() * 1000) - int(t)) > TOLERANCE_MS:
        abort(400, "signature timestamp outside tolerance")
    presented = [v.encode() for k, v in pairs if k == "v1"]
    message = t.encode() + b"." + raw  # sign the raw bytes; never decode and re-encode
    for secret in SIGNING_SECRETS:
        expected = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest().encode()
        for sig in presented:
            if hmac.compare_digest(expected, sig):  # bytes: any header content is safe
                return "", 200
    abort(401, "no v1 signature matched")
```

## Node.js (Express)

```
import crypto from "node:crypto";
import express from "express";
const app = express();

const SECRETS = [process.env.PAX_WEBHOOK_SECRET_CURRENT,
                 process.env.PAX_WEBHOOK_SECRET_PREVIOUS].filter(Boolean);
const TOLERANCE_MS = 5 * 60 * 1000;

app.post("/webhook/pax", express.raw({ type: "*/*" }), (req, res) => {
  const header = req.header("x-pax-signature") ?? "";
  const pairs = header.split(",").filter((p) => p.includes("="))
    .map((p) => [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)]);
  const t = pairs.find(([k]) => k === "t")?.[1] ?? "";
  // A missing timestamp must fail: Math.abs(NaN) > TOLERANCE_MS is false.
  if (!/^[0-9]{1,16}$/.test(t)) return res.sendStatus(400);
  if (Math.abs(Date.now() - Number(t)) > TOLERANCE_MS) return res.sendStatus(400);
  const presented = pairs.filter(([k]) => k === "v1").map(([, v]) => Buffer.from(v, "utf8"));
  const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  const message = Buffer.concat([Buffer.from(t + "."), raw]);  // the raw bytes, not a decoded string
  for (const secret of SECRETS) {
    const expected = Buffer.from(crypto.createHmac("sha256", secret).update(message).digest("hex"));
    for (const sig of presented) {
      // Compare byte lengths: timingSafeEqual throws when the buffers differ in length.
      if (sig.length === expected.length && crypto.timingSafeEqual(expected, sig)) {
        return res.sendStatus(200);
      }
    }
  }
  res.sendStatus(401);
});
```

## Bash / curl (probe your own webhook)

```
# Fire a test event and inspect the header your receiver got
API_KEY=sk_live_...
WH_ID=wh_...
curl -sX POST "https://api.predictasiax.com/v1/webhooks/$WH_ID/test" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_type":"trade.filled","data":{"probe":true}}'

# Then in your receiver logs: count the v1= entries. During grace = 2.
```

## The rotation flow (Stripe-model)

1. Call [`POST /v1/webhooks/{id}/rotate-secret`](https://docs.predictasiax.com/openapi#tag/Webhooks/paths/~1v1~1webhooks~1%7Bid%7D~1rotate-secret/post).
2. Response contains the new `signing_secret`, plus `rotated_at_ms`, `grace_expires_at_ms`, and `grace_window_ms` (currently 86400000 = 24h).
3. Store BOTH the new and previous secret in your receiver's config. Both should be in the accept list.
4. Deploy the new receiver code. All deliveries during grace verify against either secret.
5. After `grace_expires_at_ms`, drop the old secret. Deliveries then carry only one `v1=`.

**What can go wrong.** A receiver that reads its secret from an env var and does not support two-at-a-time will lose the first delivery after rotate (signed with new secret it does not have yet) OR every delivery after grace expiry (still trying old). Always support two secrets briefly.

## Delivery and retries

Each delivery is an HTTPS `POST` with `Content-Type: application/json`, the `X-PAX-Signature` header above, `X-PAX-Delivery` (the delivery id, `evt_*`) and `User-Agent: PAX-Webhook/1`. The body:

```
{
  "event_id": "fill_7d0c6f1e-2b4a-4c1e-9a53-0f5b2c8e41d7_bld_3f9a2c71d0e4",
  "event_type": "trade.filled",
  "is_test_event": false,
  "created_at_ms": 1796022000000,
  "data": { ... }
}
```

- **Success** is any 2xx response within 10 seconds. Redirects are not followed; a 3xx counts as a failure.
- **Retries** follow the endpoint's `retry_policy`. The default is 8 attempts, retried after 15 s, 1 min, 5 min, 30 min, 2 h, 8 h and 24 h. Due retries are picked up once a minute.
- **Once per endpoint.** An endpoint receives each `event_id` once; retries resend the same body. Use `event_id` to de-duplicate on your side (a replay you request sends it again). Events are not guaranteed to arrive in order; use `created_at_ms`.
- **Dead letters.** When the last attempt fails the delivery becomes `dead_letter`. List them with `GET /v1/webhooks/{id}/deliveries` or `GET /v1/webhook-events?status=dead_letter`, and send one again with `POST /v1/webhooks/{id}/deliveries/{delivery_id}/replay`.
- **Withdrawn deliveries.** A delivery PredictAsiaX withdrew before sending it is `dead_letter` with an `error_message` starting `withdrawn:`. It was never sent, cannot be replayed, and is left out of both lists unless you add `include_withdrawn=true`.

## Disabling and re-enabling a webhook

`DELETE /v1/webhooks/{id}` (or `PATCH` with `{"active": false}`) disables an endpoint: the row stays with `active=false` and `disabled_reason` `user_requested`, and no further deliveries are made.

PAX also disables an endpoint by itself, with one of these reasons:

| `disabled_reason` | When |
|---|---|
| `auto_disabled_failing` | A delivery reached `dead_letter`, the endpoint has had no successful delivery (test events excluded) for 3 days, and it was registered more than 3 days ago. |
| `target_blocked` | The URL points at an address deliveries are never sent to (IP literals, private or internal hosts, PAX's own hosts). Registration already refuses these. |

Re-enable with `PATCH /v1/webhooks/{id}` and `{"active": true}`. The URL is checked again exactly as at registration (`400 WEBHOOK_URL_INVALID` if it fails), and `disabled_at_ms` / `disabled_reason` are cleared. Events that happened while the endpoint was disabled are not sent.

## Event catalog

An endpoint receives the event types listed in its `events`. Except for `market.resolved`, every event concerns one builder account and goes only to that builder's endpoints.

| Event | Sent when | Sent to |
|---|---|---|
| `trade.filled` | An order-book fill involves you: the taker or maker order was placed through your builder account, or the taker's acquisition builder is you | That builder |
| `market.resolved` | A market settles (fast rounds excluded: see `fast_round.resolved`) | Every endpoint that lists it |
| `payout.available` | A builder earnings payout to your payout wallet is created | That builder |
| `payout.paid` | That payout is sent on-chain | That builder |
| `auth.token.revoked` | One of your API keys is revoked or rotated, or your Builder Portal sessions are revoked | That builder |
| `price.alert.triggered` | One of your [price alerts](https://docs.predictasiax.com/price-alerts) crosses its threshold | That builder |
| `fast_round.resolved` | A fast round settles in which your builder account held a position | That builder, only endpoints that list it |

### The `data` object

Order prices, sizes and amounts are strings; a fast round's reference prices are numbers. Times are Unix milliseconds.

`trade.filled` — one event per fill and builder. `roles` lists every way the fill involves you (`taker`, `maker`, `acquisition`). `order_id` and `side` are your order's, and are `null` when your only role is `acquisition`. `trade_id` is the same id as in `GET /v1/fills` and the order reply.

```
{ "trade_id": "t_5b1f0a3e9c2d4b7a8e6f1c0d2b3a4e5f_1", "market_id": "fed-cut-3x-2026", "outcome_index": 0,
  "roles": ["taker"], "order_id": "5b1f0a3e-...", "side": "BUY",
  "price": "0.6200", "size": "10", "notional_usdt": "6.200000", "executed_at_ms": 1796022000000 }
```

`market.resolved`

```
{ "market_id": "fed-cut-3x-2026", "title": "...", "category": "economy", "result": "YES",
  "winner_outcome_index": 0, "resolution_source": "...", "resolved_at_ms": 1796022000000 }
```

`payout.available` and `payout.paid`

```
{ "payout_id": "...", "amount_usdt": "12.500000", "currency": "USDT", "network": "TRC20",
  "wallet_address": "T...", "status": "pending", "hold_until_ms": null, "created_at_ms": 1796022000000 }
{ "payout_id": "...", "amount_usdt": "12.500000", "currency": "USDT", "network": "TRC20",
  "wallet_address": "T...", "tx_hash": "...", "sent_at_ms": 1796022000000 }
```

`auth.token.revoked` — `reason` is `self_revoked`, `user_requested` or `rotated` for an API key.

```
{ "credential_type": "api_key", "key_id": "...", "app_id": "app_...", "reason": "rotated", "revoked_at_ms": 1796022000000 }
{ "credential_type": "portal_session", "sessions_revoked": 2, "kept_current_session": true, "revoked_at_ms": 1796022000000 }
```

`price.alert.triggered` — the alert as [GET /v1/price-alerts/{id}](https://docs.predictasiax.com/price-alerts) returns it, now `triggered`.

```
{ "alert": { "id": "pa_...", "market_id": "fed-cut-3x-2026", "outcome": "yes", "condition": "above", "price": "0.6000",
  "label": "breakout", "status": "triggered", "created_at_ms": 1796020000000,
  "triggered_at_ms": 1796022000000, "triggered_price": "0.6100", "ended_at_ms": 1796022000000 } }
```

`fast_round.resolved` — `result` is `YES`, `NO` or `TIE`; the prices are the round's start and final reference prices.

```
{ "market_id": "...", "round_id": "...", "result": "YES", "start_price": 97123.5, "end_price": 97210.1, "resolved_at_ms": 1796022000000 }
```

Spec version 2.7.96 · Last updated 2026-12-05

Source: https://docs.predictasiax.com/webhook-signing
