Verify webhook signatures
What you need.
Sign the timestamp and the raw body.
Every delivery carries one signature header, Terania-Signature:
Build the signed string: the timestamp
t, a full stop, then the raw body bytes.t + "." + rawBody.Compute HMAC-SHA256 of that string with the endpoint secret as the key.
Write the digest as lower-case hex. That is the
v1value.Compare in constant time. Accept if any
v1matches.Reject if the difference between
tand your clock is more than 300 seconds.
t=<unix seconds>,v1=<hex>Node 18 or later.
This reads the raw body with express.raw, so the bytes are untouched.
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.TERANIA_WEBHOOK_SECRET; // base64url text, as shown once
const SIGNATURE_HEADER = "terania-signature"; // Terania-Signature, lower-case
const TOLERANCE_SECONDS = 300;
export function verify(rawBody, header, secret = SECRET) {
let t = null;
const sigs = [];
for (const part of String(header || "").split(",")) {
const i = part.indexOf("=");
if (i < 0) continue;
const k = part.slice(0, i).trim();
const v = part.slice(i + 1).trim();
if (k === "t") t = v;
if (k === "v1") sigs.push(v);
}
if (!t || !/^\d+$/.test(t) || sigs.length === 0) return false;
if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false;
const key = Buffer.from(secret, "base64url"); // decode the displayed secret to its 32 bytes first
const expected = crypto
.createHmac("sha256", key)
.update(Buffer.concat([Buffer.from(t + "."), rawBody]))
.digest("hex");
return sigs.some(
(s) =>
s.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)),
);
}
const app = express();
app.post("/terania-webhook", express.raw({ type: "application/json" }), (req, res) => {
if (!verify(req.body, req.headers[SIGNATURE_HEADER])) return res.sendStatus(400);
const event = JSON.parse(req.body.toString("utf8"));
// Dedupe on the delivery ID, store it, then do the work.
res.sendStatus(200);
});Python 3, standard library.
The same check. Pass the raw bytes of the request, not a parsed object.
import base64, hashlib, hmac, time
TOLERANCE_SECONDS = 300
def verify(raw_body: bytes, header: str, secret: str) -> bool:
t, sigs = None, []
for part in (header or "").split(","):
k, _, v = part.strip().partition("=")
if k == "t":
t = v
elif k == "v1":
sigs.append(v)
if t is None or not t.isdigit() or not sigs:
return False
if abs(time.time() - int(t)) > TOLERANCE_SECONDS:
return False
key = base64.urlsafe_b64decode(secret + "=" * (-len(secret) % 4)) # decode the displayed secret to its 32 bytes first
expected = hmac.new(key, t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, s) for s in sigs)Return fast. Dedupe.
Verify first. Reject with 4xx if the check fails. Note that any 4xx other than 408 and 429 makes the delivery dead at once, so only reject what you mean to reject.
Store the delivery ID before you act. A delivery can arrive twice.
Answer with any 2xx inside 10 seconds. Do slow work after you answer.
Fetch the record by ID through the API for detail. The body carries IDs only.
Five minutes of two signatures.
When you rotate a secret in the app, each delivery carries two v1 values for 5 minutes: one from the new secret and one from the previous. Update your receiver within that window. An option stops signing with the old secret at once. Rotating again ends the earlier window.
What happens when you fail.
Retried. A 408, a 429, any 5xx or a blocked answer: after 1 minute, 5 minutes, 30 minutes and 2 hours: five attempts in all. After the fifth failure the delivery is
dead.Ambiguous. A timeout retries and may deliver twice.
Disabled. After 20 consecutive failures the endpoint is disabled with the reason
failing. Owners and admins are told in the app and by email.Replay. Only a dead delivery can be replayed, from the delivery log, and only on an enabled endpoint. It is sent again under the same event ID.
No test button. Not built. Trigger a real event instead.
Three tests.
A real delivery verifies and your endpoint answers 2xx. The log shows Delivered.
Change one byte of the body and verification fails.
Set your clock ten minutes wrong and verification fails on the timestamp.