# Verifying webhook signatures

> Check that a webhook really comes from MoreVoice before you act on it: with the SDK, with plain Node.js crypto, or in Python. Includes a test vector.

Anyone who learns your endpoint's URL can send it a request. Before you act on a webhook, check its signature: it proves that MoreVoice sent the request and that nobody changed it on the way. MoreVoice signs webhooks with [Standard Webhooks](https://www.standardwebhooks.com), an open scheme with verifiers in many languages.

> **Verify the raw body**
>
> The signature covers the exact bytes MoreVoice sent. Read the body as text or bytes, verify it, and only then parse the JSON. A body that was parsed and serialised again no longer matches.

## With the SDK

`webhooks.constructEvent()` in `@morevoice/sdk` checks the headers, the timestamp and the signature, then returns the parsed event. It throws a `WebhookVerificationError` (with a `code` such as `bad_signature` or `timestamp_out_of_range`) when the request isn't genuine; answer `400` and MoreVoice retries. `constructEventAsync()` does the same on WebCrypto, for edge runtimes.

```ts title="app/webhooks/route.ts"
// A webhook endpoint for any runtime with Fetch API handlers:
// Next.js route handlers, Hono, Bun, Deno, Cloudflare Workers.
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

const secret = process.env.MOREVOICE_WEBHOOK_SECRET!; // whsec_…

export async function POST(request: Request): Promise<Response> {
	const body = await request.text(); // the raw body, exactly as sent
	try {
		const event = await webhooks.constructEventAsync(body, request.headers, secret);
		if (event.type === "call.ended") {
			console.log(`Call ${event.data.object.id} ended`);
		}
		// Acknowledge fast; do slow work afterwards.
		return new Response(null, { status: 204 });
	} catch (err) {
		if (err instanceof WebhookVerificationError) {
			return new Response(err.code, { status: 400 });
		}
		throw err;
	}
}
```

With Express, mount the route with `express.raw({ type: "application/json" })` so `req.body` is the raw `Buffer`, and pass it to `webhooks.constructEvent(req.body, req.headers, secret)`.

## Without the SDK

The check takes a few lines in any language:

1. Read the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, and the raw body.
2. Reject the request if the timestamp is more than 5 minutes away from your clock. This stops an old request from being replayed.
3. Decode your secret: drop the `whsec_` prefix and base64-decode the rest.
4. Compute HMAC-SHA256 over `<webhook-id>.<webhook-timestamp>.<body>` with that key, and base64-encode it.
5. Compare it, in constant time, with each `v1,<signature>` entry of `webhook-signature` (entries are separated by spaces). One match is enough.

**cURL**

```sh title="verify-webhook.sh"
# Check a delivery's signature by hand with openssl, to debug your own verifier. Pass the three headers and the raw
# body, saved byte for byte; the secret comes from the environment. In your server, use the SDK or the code in the
# other tabs: they compare in constant time.
#   MOREVOICE_WEBHOOK_SECRET=whsec_… sh verify-webhook.sh "$WEBHOOK_ID" "$WEBHOOK_TIMESTAMP" "$WEBHOOK_SIGNATURE" body.json
set -eu
msg_id="$1" timestamp="$2" signatures="$3" body="$4"

# 1. Reject a request more than 5 minutes away from your clock.
now="${NOW:-$(date +%s)}"
if [ $((now - timestamp)) -gt 300 ] || [ $((timestamp - now)) -gt 300 ]; then echo "invalid: timestamp out of range"; exit 1; fi

# 2. The key: the secret without "whsec_", base64-decoded (as hex, for openssl).
key=$(printf '%s' "${MOREVOICE_WEBHOOK_SECRET#whsec_}" | openssl base64 -d -A | od -An -v -tx1 | tr -d ' \n')

# 3. HMAC-SHA256 over "<webhook-id>.<webhook-timestamp>.<body>", base64-encoded.
expected=$({ printf '%s.%s.' "$msg_id" "$timestamp"; cat "$body"; } | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key" -binary | openssl base64 -A)

# 4. One match among the space-separated "v1,<signature>" entries is enough.
for sig in $signatures; do
	if [ "$sig" = "v1,$expected" ]; then echo "valid"; exit 0; fi
done
echo "invalid: no signature matches"
exit 1
```

**Node.js**

```ts title="verify-webhook.ts"
// Standard Webhooks verification with Node's crypto module only: no SDK, no dependencies.
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SEC = 5 * 60;

/** Verifies a MoreVoice webhook and returns the parsed event. Throws when the request isn't genuine. */
export function verifyWebhook(rawBody: string, headers: Record<string, string | undefined>, secret: string, nowSec = Math.floor(Date.now() / 1000)): unknown {
	const id = headers["webhook-id"];
	const timestamp = headers["webhook-timestamp"];
	const signatures = headers["webhook-signature"];
	if (!id || !timestamp || !signatures) throw new Error("Missing webhook headers");
	if (!/^\d+$/.test(timestamp) || Math.abs(nowSec - Number(timestamp)) > TOLERANCE_SEC) throw new Error("Timestamp out of range");

	const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
	const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
	const valid = signatures.split(" ").some((entry) => {
		const [version, signature] = entry.split(",");
		if (version !== "v1" || !signature) return false;
		const received = Buffer.from(signature, "base64");
		return received.length === expected.length && timingSafeEqual(received, expected);
	});
	if (!valid) throw new Error("Bad signature");
	return JSON.parse(rawBody);
}
```

**Python**

```python title="verify_webhook.py"
# Standard Webhooks verification with Python's standard library only (Python 3.10+).
import base64
import hashlib
import hmac
import json
import time

TOLERANCE_SEC = 5 * 60


def verify_webhook(raw_body: bytes, headers: dict, secret: str, now: int | None = None) -> dict:
    """Verify a MoreVoice webhook and return the parsed event. Raises ValueError when it isn't genuine."""
    headers = {name.lower(): value for name, value in headers.items()}
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        raise ValueError("Missing webhook headers")
    now = int(time.time()) if now is None else now
    if not timestamp.isdigit() or abs(now - int(timestamp)) > TOLERANCE_SEC:
        raise ValueError("Timestamp out of range")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(raw_body)
    raise ValueError("Bad signature")
```

## Test your code

Run your verifier against this request. It must accept it when your clock reads the `webhook-timestamp` below, and reject it when you change a single character of the body or the secret.

| Field | Example |
| --- | --- |
| Secret | `whsec_o7vehMKPiam3Ecgstvh931HBnZCcr6ww` |
| `webhook-id` | `evt_3fT9kq2ZpLr8YwVbN1cX0a` |
| `webhook-timestamp` | `1762161262` |
| Expected `webhook-signature` | `v1,Py7y93taSs6W/aMMKVpfJxrj5zQIb14una9a+V/Gw1A=` |

```json title="Body (exactly as sent)"
{"id":"evt_3fT9kq2ZpLr8YwVbN1cX0a","object":"event","type":"call.ended","created":"2025-11-03T09:14:22Z","api_version":"2026-11-01","livemode":true,"org_id":"org_0000000000000000000001","data":{"object":{"id":"call_7HkQ2mXr9","object":"call","direction":"outbound","status":"ended","end_reason":"hangup","duration_ms":93120,"campaign_id":"cmp_4Lz","metadata":{"crm_contact_id":"0031x00000AbCdE"}}},"request":{"id":"req_9aB","idempotency_key":null}}
```

To test the endpoint itself, sign your own payload with `webhooks.generateTestHeaders({ payload, secret })` from the SDK and `POST` it to your server.

## Ed25519 (public-key) signatures

An endpoint can sign with Ed25519 instead of a shared secret (`signing: "ed25519"` when you create it, or when you rotate its secret). MoreVoice keeps the private key; you only ever get the endpoint's **public key**, so there is no secret to store or leak on your side. Deliveries then carry a `v1a,<signature>` entry: an Ed25519 signature of the same `<webhook-id>.<webhook-timestamp>.<body>`, as in the [Standard Webhooks](https://www.standardwebhooks.com) asymmetric scheme.

> **Beta**
>
> Ed25519 signing is in beta. Ask us to turn it on for your organization.

- **Get the key**: the endpoint's `public_key` (`whpk_` + the base64 of the 32-byte key), or `GET /v1/webhook_endpoints/{id}/public_key`, which also returns it as PEM. In the dashboard: **Developers › Webhooks**, open the endpoint and copy its public key.
- **With the SDK**: pass the public key where the secret goes: `webhooks.constructEvent(body, headers, publicKey)`. `constructEventAsync()` verifies on WebCrypto, for edge runtimes.
- **Rotation**: a new key pair signs next to the previous one for the overlap you choose (both `v1a` entries are sent); the response shows the new `public_key` and the `previous_public_key`. Switching between a secret and Ed25519 works the same way: during the overlap the header carries a `v1` and a `v1a` entry, and each verifier checks its own.

Without the SDK:

**cURL**

```sh title="verify-ed25519.sh"
# Check an Ed25519 ("v1a") delivery by hand with OpenSSL 3, to debug your own verifier. Pass the three headers and the
# raw body, saved byte for byte; the endpoint's public key comes from the environment.
#   MOREVOICE_WEBHOOK_PUBLIC_KEY=whpk_… sh verify-ed25519.sh "$WEBHOOK_ID" "$WEBHOOK_TIMESTAMP" "$WEBHOOK_SIGNATURE" body.json
set -eu
msg_id="$1" timestamp="$2" signatures="$3" body="$4"

# 1. Reject a request more than 5 minutes away from your clock.
now="${NOW:-$(date +%s)}"
if [ $((now - timestamp)) -gt 300 ] || [ $((timestamp - now)) -gt 300 ]; then echo "invalid: timestamp out of range"; exit 1; fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
# 2. The public key as DER: the fixed Ed25519 key header, then the 32 bytes after "whpk_" (base64-decoded).
{ printf '\060\052\060\005\006\003\053\145\160\003\041\000'; printf '%s' "${MOREVOICE_WEBHOOK_PUBLIC_KEY#whpk_}" | openssl base64 -d -A; } > "$tmp/key.der"
# 3. The signed content: "<webhook-id>.<webhook-timestamp>.<body>".
{ printf '%s.%s.' "$msg_id" "$timestamp"; cat "$body"; } > "$tmp/signed"

# 4. One valid "v1a,<signature>" entry among the space-separated ones is enough.
for sig in $signatures; do
	case "$sig" in v1a,*) ;; *) continue ;; esac
	printf '%s' "${sig#v1a,}" | openssl base64 -d -A > "$tmp/sig"
	if openssl pkeyutl -verify -pubin -keyform DER -inkey "$tmp/key.der" -rawin -in "$tmp/signed" -sigfile "$tmp/sig" > /dev/null 2>&1; then echo "valid"; exit 0; fi
done
echo "invalid: no signature matches"
exit 1
```

**Node.js**

```ts title="verify-ed25519.ts"
// Standard Webhooks "v1a" (Ed25519) verification with Node.js crypto only, for an endpoint created with `signing: ed25519`.
import { createPublicKey, verify } from "node:crypto";

const TOLERANCE_SEC = 5 * 60;

/** True when the delivery is genuine. `publicKey` is the endpoint's public key as the API shows it: "whpk_<base64 of 32 bytes>". */
export function isGenuine(body: string, headers: Record<string, string | undefined>, publicKey: string, now = Date.now()): boolean {
	const raw = Buffer.from(publicKey.replace(/^whpk_/, ""), "base64");
	const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") }, format: "jwk" });
	const id = headers["webhook-id"];
	const timestamp = headers["webhook-timestamp"];
	if (!id || !timestamp || Math.abs(now / 1000 - Number(timestamp)) > TOLERANCE_SEC) return false;
	const signed = Buffer.from(`${id}.${timestamp}.${body}`);
	return (headers["webhook-signature"] ?? "").split(" ").some((entry) => {
		const [version, signature] = entry.split(",");
		return version === "v1a" && !!signature && verify(null, signed, key, Buffer.from(signature, "base64"));
	});
}
```

**Python**

```python title="verify_ed25519.py"
# Standard Webhooks "v1a" (Ed25519) verification in Python, for an endpoint created with `signing: ed25519`.
# Needs the `cryptography` package (pip install cryptography) and Python 3.10+.
import base64
import binascii
import json
import time

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

TOLERANCE_SEC = 5 * 60


def verify_webhook_ed25519(raw_body: bytes, headers: dict, public_key: str, now: int | None = None) -> dict:
    """Verify a MoreVoice webhook and return the parsed event. `public_key` is the endpoint's "whpk_…" key.
    Raises ValueError when the delivery isn't genuine."""
    headers = {name.lower(): value for name, value in headers.items()}
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        raise ValueError("Missing webhook headers")
    now = int(time.time()) if now is None else now
    if not timestamp.isdigit() or abs(now - int(timestamp)) > TOLERANCE_SEC:
        raise ValueError("Timestamp out of range")

    key = Ed25519PublicKey.from_public_bytes(base64.b64decode(public_key.removeprefix("whpk_")))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version != "v1a" or not signature:
            continue
        try:
            key.verify(base64.b64decode(signature), signed)
            return json.loads(raw_body)
        except (InvalidSignature, binascii.Error):
            continue
    raise ValueError("Bad signature")
```

## Endpoints created before v2

Endpoints from **Settings › Compliance** and campaign settings use the earlier signature: `X-Webhook-Signature: sha256=<hex>`, an HMAC-SHA256 of `<timestamp>.<body>` with the endpoint secret used as is, plus `X-Webhook-Timestamp`. The SDK verifies it with `webhooks.verifyLegacy()`:

```ts title="legacy-webhook.ts"
// Endpoints created before webhooks v2 use the legacy signature:
// X-Webhook-Signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<body>")>
import { webhooks, type LegacyWebhookEvent } from "@morevoice/sdk";

const secret = process.env.MOREVOICE_WEBHOOK_SECRET!;

export function handleLegacyWebhook(rawBody: string, headers: Record<string, string>): LegacyWebhookEvent {
	const event = webhooks.verifyLegacy(rawBody, headers, secret);
	console.log(event.event, event.data); // e.g. "call.ended", { … }
	return event;
}
```
