Verify webhook signatures
Prove a delivery came from Kvali, answer fast and handle retries once.
20 minAny keyWhat you get
- A receiver that refuses anything not signed by Kvali, or older than 5 minutes.
- Retries handled once, by the delivery id.
- A way to test it before you have a key.
Add your endpoint
In Settings → API → Webhooks, add your public
https://address and choose the events. Copy the signing secret (whsec_…): it is shown once. Keep it in an environment variable.export KVALI_WEBHOOK_SECRET="whsec_…"Check the signature on the raw body
Each delivery carries
Kvali-Signature: t=<unix seconds>,v1=<hex>. Compute HMAC-SHA256 of<t>.<raw body>with your secret and compare it withv1in constant time. Use the body exactly as it arrived: parsing and re-serialising the JSON changes the bytes and breaks the check. Refuse atmore than 5 minutes from your clock.import { createHmac, timingSafeEqual } from "node:crypto"; // rawBody: the request body exactly as received (before JSON parsing). function isFromKvali(rawBody, header, secret, nowSeconds = Date.now() / 1000) { const parts = Object.fromEntries(String(header ?? "").split(",").map((p) => p.split("="))); const t = Number(parts.t); if (!Number.isFinite(t) || !parts.v1 || Math.abs(nowSeconds - t) > 300) return false; // missing, or older than 5 minutes const expected = createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest(); const given = Buffer.from(parts.v1, "hex"); return given.length === expected.length && timingSafeEqual(given, expected); }import hashlib, hmac, time def is_from_kvali(raw_body: bytes, header: str, secret: str, now=None) -> bool: """raw_body: the request body exactly as received, before JSON parsing.""" parts = dict(p.split("=", 1) for p in (header or "").split(",") if "=" in p) try: t = int(parts["t"]) except (KeyError, ValueError): return False if "v1" not in parts or abs((now or time.time()) - t) > 300: return False # missing, or older than 5 minutes signed = parts["t"].encode() + b"." + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, parts["v1"])# Check one delivery by hand: body.json holds the raw body, T is the header's t T=1762596000 printf '%s.%s' "$T" "$(cat body.json)" | openssl dgst -sha256 -hmac "$KVALI_WEBHOOK_SECRET" # the hex must equal the header's v1Answer at once, then work
Answer any
2xxwithin 10 seconds and do the real work afterwards. Anything else is retried after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h, then marked failed. A retry carries the sameid(also in theKvali-Deliveryheader): keep the ids you handled, with a unique index, and skip a repeat.import { createServer } from "node:http"; const secret = process.env.KVALI_WEBHOOK_SECRET; const handled = new Set(); // in production: a table with a unique index on the delivery id createServer((req, res) => { const chunks = []; req.on("data", (c) => chunks.push(c)); req.on("end", () => { const raw = Buffer.concat(chunks).toString("utf8"); if (!isFromKvali(raw, req.headers["kvali-signature"], secret)) return res.writeHead(401).end(); const delivery = JSON.parse(raw); res.writeHead(200).end(); // answer first if (handled.has(delivery.id)) return; // a retry you already handled handled.add(delivery.id); setImmediate(() => handle(delivery)); // e.g. on review.ready: GET /reviews/{id} }); }).listen(8080);import json, os from flask import Flask, request app = Flask(__name__) SECRET = os.environ["KVALI_WEBHOOK_SECRET"] handled = set() # in production: a table with a unique index on the delivery id @app.post("/kvali") def kvali(): raw = request.get_data() # the raw bytes, before parsing if not is_from_kvali(raw, request.headers.get("Kvali-Signature", ""), SECRET): return "", 401 delivery = json.loads(raw) if delivery["id"] not in handled: handled.add(delivery["id"]) queue_work(delivery) # do the work after answering, e.g. in a job queue return "", 200Test before you have a key
GET /webhook-examples.json(no key) returns a signed sample of every event with its exactraw_body, its headers and the test secret it was signed with. Check each with your clock set to the sample'st, then change one byte and make sure your check refuses it. The full receiver is in the reference under "A receiver to start from".curl "https://aikvali.com/api/v1/webhook-examples.json"const res = await fetch("https://aikvali.com/api/v1/webhook-examples.json"); const { secret, examples } = await res.json(); for (const e of examples) { const ok = isFromKvali(e.raw_body, e.headers["Kvali-Signature"], secret, e.t); const tampered = isFromKvali(e.raw_body + " ", e.headers["Kvali-Signature"], secret, e.t); console.log(e.event, ok && !tampered ? "ok" : "FAILED"); }import requests samples = requests.get("https://aikvali.com/api/v1/webhook-examples.json", timeout=30).json() for e in samples["examples"]: raw = e["raw_body"].encode() ok = is_from_kvali(raw, e["headers"]["Kvali-Signature"], samples["secret"], now=e["t"]) tampered = is_from_kvali(raw + b" ", e["headers"]["Kvali-Signature"], samples["secret"], now=e["t"]) print(e["event"], "ok" if ok and not tampered else "FAILED")See what was sent, and send one again
GET /webhooks/deliverieslists what Kvali sent and how your receiver answered (status=failedfor the ones that gave up). After fixing your receiver,POST /webhooks/deliveries/{id}/replaysends one again with the same id and body.curl "https://aikvali.com/api/v1/webhooks/deliveries?status=failed&limit=25" \ -H "Authorization: Bearer $KVALI_KEY"const res = await fetch("https://aikvali.com/api/v1/webhooks/deliveries?status=failed&limit=25", { headers: { Authorization: `Bearer ${process.env.KVALI_KEY}` }, }); if (!res.ok) throw new Error((await res.json()).error.message); const { data } = await res.json();import os import requests res = requests.get( "https://aikvali.com/api/v1/webhooks/deliveries?status=failed&limit=25", headers={"Authorization": f"Bearer {os.environ['KVALI_KEY']}"}, timeout=30, ) if not res.ok: raise RuntimeError(res.json()["error"]["message"]) data = res.json()["data"]