Verifying inbound webhook signatures
Your webhook URL is public. Without a signature check, anyone who learns the URL can create support tickets, trigger agent replies, or burn your LLM budget with garbage. Every provider solves this differently — or in one case, not at all — and the differences are the reason the same handler copied between them tends to fail closed.
What each provider actually signs
| Provider | Scheme | Header / field |
|---|---|---|
| MailKite | HMAC-SHA256 of t.rawBody | x-mailkite-signature: t=…,v1=… |
| Mailgun | HMAC-SHA256 of timestamp + token | Form fields signature, timestamp, token |
| Resend (inbound) | Svix: HMAC-SHA256 of id.timestamp.payload | svix-id, svix-timestamp, svix-signature |
| SendGrid Inbound Parse | ECDSA (Ed25519) over timestamp + payload | x-twilio-email-event-webhook-signature + timestamp header — must be enabled in settings |
| AWS SES → SNS | X.509 signature over the SNS envelope | Signature, SignatureVersion, SigningCertURL |
| Postmark | None | — put HTTP basic auth in the webhook URL, or allowlist their IPs |
Mailgun
import crypto from "node:crypto";
// Mailgun signs: HMAC-SHA256(signingKey, timestamp + token)
function verifyMailgun(body, signature, timestamp, token, signingKey) {
const expected = crypto
.createHmac("sha256", signingKey)
.update(timestamp + token)
.digest("hex");
// Constant-time compare.
const a = Buffer.from(expected, "hex");
const b = Buffer.from(signature, "hex");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return false;
// Replay window — Mailgun allows 15 minutes at most.
return Math.abs(Date.now() / 1000 - Number(timestamp)) < 300;
} Svix-style (Resend)
import crypto from "node:crypto";
// Svix-style (used by Resend): HMAC-SHA256 of `${id}.${timestamp}.${payload}`
// keyed with the base64-decoded secret ("whsec_…").
function verifySvix({ id, timestamp, signatureHeader, payload, secret }) {
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const expected = crypto
.createHmac("sha256", key)
.update(`${id}.${timestamp}.${payload}`)
.digest("base64");
// The header can carry several signatures, space-separated, each "v1,<sig>".
return signatureHeader
.split(" ")
.map((part) => part.split(",")[1])
.some((sig) => sig && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)));
} SendGrid
SendGrid uses asymmetric signing, not a shared secret: they hold the private
key and publish the public one, so verification needs no secret on your side —
but it only works if “Signed webhook” is enabled for the Inbound Parse
setting, and it verifies ECDSA over timestamp + payload. Use their
verification library rather than reimplementing Ed25519 by hand.
Postmark
There is no signature. The supported pattern is credentials in the URL
(https://user:pass@yourdomain.com/hooks/postmark) plus their
published IP ranges if you want a second factor. Treat an unauthenticated
Postmark endpoint as world-writable.
MailKite
import { MailKite } from "mailkite";
// MailKite signs: x-mailkite-signature: t=<ms>,v1=<hex hmac of "t.rawBody">
if (!MailKite.verifyWebhook(
req.headers["x-mailkite-signature"],
req.body, // the RAW bytes
process.env.MAILKITE_WEBHOOK_SECRET,
)) return res.sendStatus(401); Full detail, including the by-hand HMAC in every language, is in verifying signatures.
Four rules that matter more than the snippet
- Sign the raw bytes. The most common failure by far: a framework parses JSON, you re-serialize it, key order or whitespace changes, and the signature never matches. Capture the raw body on the webhook route only.
- Compare in constant time.
===on a MAC leaks timing information. Every language has a primitive (crypto.timingSafeEqual,hmac.compare_digest,hash_equals) — use it. - Reject stale timestamps. A signature is valid forever unless you bound it. Five minutes is the usual window; a captured request replayed an hour later is a new ticket, a new agent reply, a new charge.
- Fail closed, ack fast. No signature header, or one that
does not verify, is a
401— never “process it anyway”. Then return2xximmediately and do the work in a queue; slow handlers trigger retries, and retries are duplicate work.
// Express — raw bodies only on the webhook routes.
// A re-serialized JSON object has different bytes and will never verify.
app.use("/hooks/*", express.raw({ type: "*/*" }));
// Next.js App Router
export async function POST(req: Request) {
const raw = await req.text(); // NOT await req.json()
}
A verified webhook proves the sender of the webhook is genuine. It
says nothing about the email inside it — the From: header is still
whatever the sender typed. Check the SPF/DKIM/DMARC verdict in the payload
before you trust an address, especially when an agent will act on the contents.