Verifying webhook signatures
Every webhook delivery carries an X-Nexiel-Signature header. Check it before you trust the body, with about ten lines of standard library code and no Nexiel package.
The signature scheme
The header looks like t=1763030000,v1=5f2b.... t is the Unix time, in seconds, when the delivery attempt was signed. v1 is the hex HMAC-SHA256 of the text {t}.{rawBody}, keyed with your endpoint's signing secret as UTF-8 text. rawBody is the request body exactly as received, before any JSON parsing.
- Read the raw body. Parsing and re-serialising JSON changes the bytes and breaks the signature.
- Recompute the HMAC over
{t}.{rawBody}and compare it with eachv1value in constant time. - Reject a timestamp more than 300 seconds from your clock, so a captured delivery cannot be replayed later.
- Answer with a 2xx status, then deduplicate on the event
id. Each retry is signed again with a new timestamp.
While you rotate a signing secret, the header carries two v1 values, one per secret: t=1763030000,v1=<previous>,v1=<current>. The verifiers below accept a match on either, so you can deploy the new secret without missing an event. See rotating the signing secret.
The verifier
Both versions return true only for a genuine, recent delivery, and refuse to run without a signing secret, because an empty key would let anyone sign a delivery. They are tested against Nexiel's own signer for genuine, changed, expired, wrongly keyed and rotated deliveries.
import { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 300;
// rawBody: the request body exactly as received (string or Buffer).
export function verifyNexielSignature(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
if (!secret) throw new Error('NEXIEL_WEBHOOK_SECRET is not set');
const parts = header.split(',').map((part) => part.trim().split('='));
const timestamp = Number(parts.find(([key]) => key === 't')?.[1]);
if (!Number.isInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false;
const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
const signatures = parts.filter(([key]) => key === 'v1').map(([, value]) => Buffer.from(value ?? '', 'hex'));
return signatures.some((signature) => signature.length === expected.length && timingSafeEqual(signature, expected));
}import hashlib
import hmac
import time
TOLERANCE_SECONDS = 300
def verify_nexiel_signature(raw_body: bytes, header: str, secret: str, now: int | None = None) -> bool:
if not secret:
raise ValueError("NEXIEL_WEBHOOK_SECRET is not set")
pairs = [part.strip().split("=", 1) for part in header.split(",")]
values = [(pair[0], pair[1]) for pair in pairs if len(pair) == 2]
timestamps = [value for key, value in values if key == "t"]
if len(timestamps) != 1 or not (timestamps[0].isascii() and timestamps[0].isdigit()):
return False
timestamp = int(timestamps[0])
if abs((now if now is not None else int(time.time())) - timestamp) > TOLERANCE_SECONDS:
return False
expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest().encode()
return any(hmac.compare_digest(expected, value.encode()) for key, value in values if key == "v1")Reading the raw body in your framework
Most frameworks parse JSON bodies before your handler runs. Each handler below reads the body unparsed, verifies it, and only then parses it.
import express from 'express';
import { verifyNexielSignature } from './verify-nexiel-signature.js';
const app = express();
// express.raw keeps the body as the exact bytes Nexiel signed.
app.post('/webhooks/nexiel', express.raw({ type: 'application/json' }), (req, res) => {
const header = req.get('X-Nexiel-Signature') ?? '';
if (!verifyNexielSignature(req.body, header, process.env.NEXIEL_WEBHOOK_SECRET)) {
return res.status(400).send('invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
// Deduplicate on event.id, then hand the event to a queue and answer quickly.
res.sendStatus(200);
});// app/webhooks/nexiel/route.ts
import { verifyNexielSignature } from '@/lib/verify-nexiel-signature';
export async function POST(request: Request): Promise<Response> {
// request.text() returns the body unparsed, exactly as Nexiel signed it.
const rawBody = await request.text();
const header = request.headers.get('x-nexiel-signature') ?? '';
const secret = process.env.NEXIEL_WEBHOOK_SECRET;
if (!secret) throw new Error('NEXIEL_WEBHOOK_SECRET is not set');
if (!verifyNexielSignature(rawBody, header, secret)) {
return new Response('invalid signature', { status: 400 });
}
const event = JSON.parse(rawBody);
// Deduplicate on event.id, then hand the event to a queue and answer quickly.
return new Response(null, { status: 200 });
}import json
import os
from fastapi import FastAPI, HTTPException, Request
from verify_nexiel_signature import verify_nexiel_signature
app = FastAPI()
@app.post("/webhooks/nexiel")
async def nexiel_webhook(request: Request) -> dict[str, bool]:
# request.body() returns the raw bytes Nexiel signed.
raw_body = await request.body()
header = request.headers.get("x-nexiel-signature", "")
if not verify_nexiel_signature(raw_body, header, os.environ["NEXIEL_WEBHOOK_SECRET"]):
raise HTTPException(status_code=400, detail="invalid signature")
event = json.loads(raw_body)
# Deduplicate on event["id"], then hand the event to a queue and answer quickly.
return {"received": True}Keep the signing secret in a secret store or an environment variable, never in source code. Each endpoint has its own secret, shown once when you create the endpoint and readable again from the dashboard or POST .../secret/reveal.
Send yourself a test delivery
Press Send test event on the dashboard's Webhooks page, or call POST .../test on the endpoint. Nexiel sends a signed webhook.test event to that endpoint, and the delivery list shows your endpoint's response code.
curl -s -X POST https://compliance.nexiel.io/v1/verify/webhook-endpoints/{endpointId}/test \
-H "Authorization: Bearer $NEXIEL_ACCESS_TOKEN" \
-H "Idempotency-Key: $(uuidgen)"SDK helpers
The TypeScript and Python SDKs, coming to npm and PyPI, wrap the same check as constructWebhookEvent and construct_webhook_event. See Client SDKs.