Webhook signatures and verification
The Blüdhaven Pets platform delivers asynchronous webhooks when life-cycle events occur outside a direct HTTP request cycle.
Two events dispatch today:
| Event | Fired when | Payload highlights |
|---|---|---|
adoption.hold.expired | A hold on a reservation expires after 30 minutes with no application | hold_id, animal_id, reason |
veterinary.clearance.filed | A municipal veterinarian records certification, making the animal adoption-eligible | animal_id, certificate_number, status |
Every delivery travels as an HTTP POST with a JSON payload and an HMAC-SHA256 signature in the X-Bludhaven-Signature header.
Why verify signatures
A public webhook endpoint accepts incoming HTTP traffic from the internet. Without cryptographic verification:
- An attacker can forge an
adoption.hold.expiredevent to release animals prematurely. - An attacker can inject a fake
veterinary.clearance.filedevent to bypass mandatory rabies quarantine. - An attacker can replay an old valid payload to cause duplicate processing.
Signature verification proves that Blüdhaven Pets authored the exact payload bytes and that the delivery is fresh.
The signature header format
The X-Bludhaven-Signature header contains a UNIX timestamp and an HMAC-SHA256 hex digest:
X-Bludhaven-Signature: t=1795123456,v1=5d41402abc4b2a76b9719d911017c5926c459992f026a0b72a6a8b1a7f05252b
t: The UNIX epoch timestamp in seconds when the gateway signed the delivery.v1: The lowercase hexadecimal HMAC-SHA256 digest computed overt={timestamp},v1={raw_body}using your webhook signing secret.
Verify the signature in Node.js
Verification requires the exact raw request body before JSON parsing. A parser alters whitespace and key ordering, which breaks cryptographic validation.
import crypto from 'node:crypto';
export function verifyWebhookSignature({ rawBody, signatureHeader, secret, toleranceSeconds = 300 }) {
if (!signatureHeader) {
throw new Error('Missing X-Bludhaven-Signature header');
}
// 1. Extract timestamp and signature from the header
const elements = Object.fromEntries(
signatureHeader.split(',').map((pair) => pair.split('='))
);
const timestamp = parseInt(elements.t, 10);
const expectedSignature = elements.v1;
if (isNaN(timestamp) || !expectedSignature) {
throw new Error('Malformed X-Bludhaven-Signature header');
}
// 2. Reject replays outside tolerance window (default 5 minutes)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - timestamp) > toleranceSeconds) {
throw new Error('Webhook timestamp falls outside tolerance window');
}
// 3. Recreate the signed string: t={timestamp},v1={raw_body}
const signedPayload = `t=${timestamp},v1=${rawBody}`;
// 4. Compute expected HMAC-SHA256
const computedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload, 'utf8')
.digest('hex');
// 5. Compare in constant time to prevent timing attacks. A digest of the
// wrong length makes timingSafeEqual throw RangeError, so check the length.
const computed = Buffer.from(computedSignature, 'hex');
const expected = Buffer.from(expectedSignature, 'hex');
const valid =
computed.length === expected.length &&
crypto.timingSafeEqual(computed, expected);
if (!valid) {
throw new Error('Invalid webhook signature');
}
return JSON.parse(rawBody);
}
Verify the signature in Python
import hmac
import hashlib
import time
import json
def verify_webhook(raw_bytes: bytes, sig_header: str, secret: str, tolerance: int = 300) -> dict:
parts = dict(item.split("=", 1) for item in sig_header.split(","))
timestamp = int(parts.get("t", 0))
expected_hex = parts.get("v1", "")
if abs(time.time() - timestamp) > tolerance:
raise ValueError("Timestamp outside acceptable replay window")
signed_data = f"t={timestamp},v1=".encode("utf-8") + raw_bytes
computed_hex = hmac.new(secret.encode("utf-8"), signed_data, hashlib.sha256).hexdigest()
if not hmac.compare_digest(computed_hex, expected_hex):
raise ValueError("Signature mismatch")
return json.loads(raw_bytes.decode("utf-8"))
Test dispatch in the sandbox
The sandbox gateway provides a test dispatch endpoint. It signs a real payload and returns the headers. Point your receiver at it to test signature handling without waiting for a background event.
The reference console lists the same call under Webhooks. Select the Browser demo server and send it there. The demo signs at request time with the published secret, so the header you copy out of the console verifies against whsec_sandbox_bludhaven_test_secret_9981. A stored fixture would carry a stale timestamp and a digest over different bytes.
curl -X POST https://sandbox.bludhaven-pets.workers.dev/webhooks/test-dispatch \
-H "Content-Type: application/json" \
-o webhook-dispatch.json
Send no body and the gateway signs its full example payload. Send {"event": "veterinary.clearance.filed"} and that object becomes the payload instead.
{
"dispatched": true,
"event": "adoption.hold.expired",
"secret_used": "whsec_sandbox_bludhaven_test_secret_9981",
"headers": {
"Content-Type": "application/json",
"X-Bludhaven-Signature": "t=1795123456,v1=5d41402abc4b...",
"X-Bludhaven-Timestamp": "1795123456"
},
"payload": {
"id": "evt_wh_901ab2cd",
"event": "adoption.hold.expired",
"created_at": "2026-11-19T13:30:00Z",
"data": {
"hold_id": "hld_a8f90b",
"animal_id": "pet_krypto_210",
"reason": "30_MINUTE_WINDOW_LAPSED"
}
},
"verification_guide": {
"scheme": "HMAC-SHA256",
"signed_template": "t={timestamp},v1={raw_body}",
"header_format": "t={timestamp},v1={hex_signature}"
}
}
The response carries the signing secret, the computed signature, and the payload. Check it with the verifier in the sandbox worker repository:
node scripts/verify-webhook.mjs webhook-dispatch.json
event adoption.hold.expired
secret whsec_sandbox_bludhaven_test_secret_9981
signature header t=1795123456,v1=5d41402a...
computed header t=1795123456,v1=5d41402a...
signature match YES
delivery age 2s (tolerance 300s): fresh
PASS: HMAC-SHA256 signature verified.
The verifier reads the response from a file and recomputes the digest. Never pass the payload through a shell variable or an inline node -e string. Quote handling collapses nested JSON into invalid source, and you get a ReferenceError instead of a verdict.
Change one character of the payload and the verifier exits 1 with FAIL: signature does not match.
The verifier also rejects a delivery older than 300 seconds, which closes the replay window. Pass --ignore-age when you replay an archived fixture.
Related guides
- Domain model - adoption hold state machine and lifecycle triggers.
- Authentication and scopes - API key and OAuth credential management.