# Verify signatures (/webhooks/verify-signatures)

Every delivery to a [webhook endpoint](/webhooks/endpoints) is signed with that endpoint's secret. Check the signature before you trust the body. The scheme follows the [Standard Webhooks](https://www.standardwebhooks.com/) specification.

## How the signature works [#how-the-signature-works]

Each delivery has three headers:

| Header | Example |
| --- | --- |
| `webhook-id` | `evt_5f0c6a1e9b2d4c7e8a1f3b5d7c9e0a2b` |
| `webhook-timestamp` | `1763184730` (Unix seconds, new on each attempt) |
| `webhook-signature` | `v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=` |

CallMitra computes the signature like this:

1. **Key:** take your secret (`whsec_MfKQ…`), remove the `whsec_` prefix, and base64-decode the rest. The result is 32 bytes.
2. **Signed content:** the `webhook-id`, a dot, the `webhook-timestamp`, a dot, then the raw request body: `{webhook-id}.{webhook-timestamp}.{body}`.
3. **Signature:** HMAC-SHA256 of the signed content with the key, base64-encoded (standard alphabet, with padding), prefixed with `v1,`.

`webhook-signature` can hold more than one signature, separated by spaces. For 24 hours after you [rotate the secret](/webhooks/endpoints#rotate-the-signing-secret), it holds one from the new secret and one from the old secret. Accept the request if **any** `v1` signature matches.

## Steps [#steps]

<Steps>
<Step>
### Read the raw body [#read-the-raw-body]

Use the body bytes exactly as received. Do not parse and re-serialize the JSON first: any change in spacing or key order breaks the signature.
</Step>

<Step>
### Check the timestamp [#check-the-timestamp]

Reject the request if `webhook-timestamp` is more than **5 minutes** away from your clock. This stops someone replaying a captured request later.
</Step>

<Step>
### Compute and compare [#compute-and-compare]

Compute the expected signature as above. Compare it with each `v1,` entry in `webhook-signature` using a **constant-time** comparison. If none match, answer `401`.
</Step>

<Step>
### Drop duplicates [#drop-duplicates]

Skip the event if you already handled its `webhook-id`. Retries and redeliveries reuse it.
</Step>
</Steps>

## Examples [#examples]

Each example reads the secret from `CALLMITRA_WEBHOOK_SECRET`.

<Tabs groupId="language" persist items={["Node.js","Python","PHP","Go"]}>
<Tab value="Node.js">
```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const SECRET = process.env.CALLMITRA_WEBHOOK_SECRET; // whsec_...
const KEY = Buffer.from(SECRET.replace(/^whsec_/, ''), 'base64');
const TOLERANCE_S = 300;

function verify(rawBody, headers) {
  const id = headers['webhook-id'];
  const ts = headers['webhook-timestamp'];
  const sigHeader = headers['webhook-signature'];
  if (!id || !sigHeader || !/^\d+$/.test(ts ?? '')) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > TOLERANCE_S) return false;

  const expected = crypto
    .createHmac('sha256', KEY)
    .update(`${id}.${ts}.`)
    .update(rawBody)
    .digest();

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

// express.raw keeps the body as a Buffer, so the bytes are unchanged.
app.post('/webhooks/callmitra', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verify(req.body, req.headers)) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  // Skip event.id if you have already handled it, then queue the work.
  res.sendStatus(204);
});
```
</Tab>

<Tab value="Python">
```python
import base64
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
KEY = base64.b64decode(os.environ["CALLMITRA_WEBHOOK_SECRET"].removeprefix("whsec_"))
TOLERANCE_S = 300

def verify(raw: bytes, headers) -> bool:
    msg_id = headers.get("webhook-id", "")
    ts = headers.get("webhook-timestamp", "")
    sig_header = headers.get("webhook-signature", "")
    if not (msg_id and sig_header and ts.isascii() and ts.isdigit()):
        return False
    if abs(time.time() - int(ts)) > TOLERANCE_S:
        return False

    signed = f"{msg_id}.{ts}.".encode() + raw
    expected = base64.b64encode(hmac.new(KEY, signed, hashlib.sha256).digest()).decode()
    for entry in sig_header.split():
        version, _, sig = entry.partition(",")
        if version == "v1" and hmac.compare_digest(sig, expected):
            return True
    return False

@app.post("/webhooks/callmitra")
def callmitra_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    if not verify(raw, request.headers):
        abort(401)

    event = json.loads(raw)
    # Skip event["id"] if you have already handled it, then queue the work.
    return "", 204
```
</Tab>

<Tab value="PHP">
```php
<?php
const TOLERANCE_S = 300;

function callmitra_verify(string $secret, string $raw, string $id, string $ts, string $sigHeader): bool
{
    if ($id === '' || $sigHeader === '' || !ctype_digit($ts)) {
        return false;
    }
    if (abs(time() - (int) $ts) > TOLERANCE_S) {
        return false;
    }
    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = base64_encode(hash_hmac('sha256', "$id.$ts.$raw", $key, true));
    foreach (explode(' ', $sigHeader) as $entry) {
        [$version, $sig] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $sig)) {
            return true;
        }
    }
    return false;
}

$raw = file_get_contents('php://input');
$valid = callmitra_verify(
    getenv('CALLMITRA_WEBHOOK_SECRET'),
    $raw,
    $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? ''
);
if (!$valid) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
// Skip $event['id'] if you have already handled it, then queue the work.
http_response_code(204);
```
</Tab>

<Tab value="Go">
```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const toleranceS = 300

var key = mustKey(os.Getenv("CALLMITRA_WEBHOOK_SECRET"))

func mustKey(secret string) []byte {
	k, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		panic("CALLMITRA_WEBHOOK_SECRET is not a whsec_ secret")
	}
	return k
}

func verify(raw []byte, h http.Header) bool {
	id, ts, sigHeader := h.Get("webhook-id"), h.Get("webhook-timestamp"), h.Get("webhook-signature")
	sent, err := strconv.ParseInt(ts, 10, 64)
	if id == "" || sigHeader == "" || err != nil {
		return false
	}
	if d := time.Now().Unix() - sent; d > toleranceS || d < -toleranceS {
		return false
	}

	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + ts + "."))
	mac.Write(raw)
	expected := mac.Sum(nil)

	for _, entry := range strings.Fields(sigHeader) {
		version, sig, ok := strings.Cut(entry, ",")
		if !ok || version != "v1" {
			continue
		}
		received, err := base64.StdEncoding.DecodeString(sig)
		if err == nil && hmac.Equal(received, expected) {
			return true
		}
	}
	return false
}

func callmitraWebhook(w http.ResponseWriter, r *http.Request) {
	raw, err := io.ReadAll(r.Body)
	if err != nil || !verify(raw, r.Header) {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
	// Parse raw as JSON, skip ids you have already handled, then queue the work.
	w.WriteHeader(http.StatusNoContent)
}
```
</Tab>
</Tabs>

## Use a Standard Webhooks library [#use-a-standard-webhooks-library]

Because the scheme follows Standard Webhooks, the official libraries verify CallMitra deliveries too. For example, `standardwebhooks` on npm and PyPI. See [github.com/standard-webhooks/standard-webhooks](https://github.com/standard-webhooks/standard-webhooks) for other languages. Pass the whole `whsec_…` secret, the raw body and the request headers.

```python
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["CALLMITRA_WEBHOOK_SECRET"])
event = wh.verify(raw_body, request.headers)  # raises if the signature or timestamp is wrong
```

## Test your receiver [#test-your-receiver]

Call [`POST /api/v1/webhook-endpoints/{endpoint_id}/test`](/api-reference/webhooks/sendTestWebhook). It sends a signed `webhook.test` event and returns your server's status code and the first 1 KB of its answer. A `401` there usually means one of the mistakes below.

## Common mistakes [#common-mistakes]

- **Verifying parsed JSON.** Frameworks that parse the body first (for example `express.json()`) lose the original bytes. Use the raw body.
- **Using the secret as text.** The HMAC key is the base64-decoded part after `whsec_`, not the secret string itself.
- **Checking only the first signature.** After a rotation the header has two. Split on spaces and try each one.
- **Plain string comparison.** `==` leaks timing information. Use the constant-time helpers shown above.
- **Wrong endpoint's secret.** Each endpoint has its own secret.
- **Clock drift.** The 5-minute window assumes your server clock is in sync (NTP).

## The `X-Signature-SHA256` header [#the-x-signature-sha256-header]

Deliveries to webhook endpoints also carry `X-Signature-SHA256`, so a receiver built for [campaign and agent webhooks](/webhooks/campaign-agent-webhooks) keeps working. Prefer `webhook-signature`: it covers the id and timestamp, and it supports secret rotation. If you do check `X-Signature-SHA256` on an endpoint delivery, see [Verify X-Signature-SHA256](/webhooks/campaign-agent-webhooks#verify-x-signature-sha256) for the key it uses and how to check replays.