Verify signatures
Every webhook request is signed with your subscription’s signing secret (whsec_..., shown once when you create the
subscription or rotate the secret). Verify every request before you trust it.
The scheme
Section titled “The scheme”signed_payload = X-AD80-Timestamp + "." + X-AD80-Delivery + "." + raw_bodysignature = hex( HMAC-SHA256( secret, signed_payload ) )X-AD80-Signature: v1=<signature>[,v1=<signature of the second secret>]To verify:
- Read the raw request body as bytes, exactly as received. Do not parse and re-serialize the JSON first.
- Read
X-AD80-Timestamp,X-AD80-DeliveryandX-AD80-Signature. - Reject the request if the timestamp is more than 5 minutes away from your clock (in either direction). This is the replay window.
- Compute the HMAC-SHA256 of
timestamp + "." + deliveryId + "." + rawBodywith your secret, as lowercase hex. - Accept if it equals any
v1=entry ofX-AD80-Signature(compare in constant time). During a secret rotation the header has two entries, and you may hold two secrets: accept a match of any entry with any of your secrets. - Answer
2xxquickly, then process. De-duplicate onX-AD80-Delivery(see Delivery, retries and idempotency).
// Node 18+, Express 4 or 5. npm install expressimport crypto from 'node:crypto';import express from 'express';
// During a rotation, list both secrets until you have called retire-secrets.const SECRETS = [process.env.AD80_WEBHOOK_SECRET];const REPLAY_WINDOW_S = 300;
function verifyAd80(rawBody, timestamp, deliveryId, signatureHeader) { const ts = Number(timestamp); if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > REPLAY_WINDOW_S) return false; const given = (signatureHeader || '') .split(',') .map((s) => s.trim()) .filter((s) => s.startsWith('v1=')) .map((s) => Buffer.from(s.slice(3), 'hex')); for (const secret of SECRETS) { const want = crypto .createHmac('sha256', secret) .update(`${timestamp}.${deliveryId}.`) .update(rawBody) .digest(); if (given.some((g) => g.length === want.length && crypto.timingSafeEqual(g, want))) return true; } return false;}
const app = express();// express.raw keeps the exact bytes; do not use express.json() on this route.app.post('/webhooks/ad80', express.raw({ type: 'application/json' }), (req, res) => { const ok = verifyAd80( req.body, req.get('X-AD80-Timestamp'), req.get('X-AD80-Delivery'), req.get('X-AD80-Signature'), ); if (!ok) return res.status(401).send('bad signature');
const deliveryId = req.get('X-AD80-Delivery'); const event = JSON.parse(req.body.toString('utf8')); // TODO: skip if deliveryId was already processed, else store it and queue the work. console.log(deliveryId, event.type); res.sendStatus(204);});
app.listen(3000);# Python 3.9+, Flask. pip install flaskimport hashlibimport hmacimport jsonimport osimport time
from flask import Flask, abort, request
# During a rotation, list both secrets until you have called retire-secrets.SECRETS = [os.environ["AD80_WEBHOOK_SECRET"]]REPLAY_WINDOW_S = 300
def verify_ad80(raw_body: bytes, timestamp: str, delivery_id: str, signature_header: str) -> bool: try: ts = int(timestamp) except (TypeError, ValueError): return False if abs(time.time() - ts) > REPLAY_WINDOW_S: return False given = [e.strip()[3:] for e in (signature_header or "").split(",") if e.strip().startswith("v1=")] for secret in SECRETS: msg = f"{timestamp}.{delivery_id}.".encode() + raw_body want = hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest() if any(hmac.compare_digest(want, g.lower()) for g in given): return True return False
app = Flask(__name__)
@app.post("/webhooks/ad80")def ad80_webhook(): raw = request.get_data() # the exact bytes received if not verify_ad80(raw, request.headers.get("X-AD80-Timestamp", ""), request.headers.get("X-AD80-Delivery", ""), request.headers.get("X-AD80-Signature", "")): abort(401) delivery_id = request.headers["X-AD80-Delivery"] event = json.loads(raw) # TODO: skip if delivery_id was already processed, else store it and queue the work. print(delivery_id, event["type"]) return "", 204package main
import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "io" "log" "math" "net/http" "os" "strconv" "strings" "time")
// During a rotation, list both secrets until you have called retire-secrets.var secrets = []string{os.Getenv("AD80_WEBHOOK_SECRET")}
const replayWindow = 5 * time.Minute
func verifyAD80(body []byte, timestamp, deliveryID, sigHeader string) bool { ts, err := strconv.ParseInt(timestamp, 10, 64) if err != nil || math.Abs(time.Since(time.Unix(ts, 0)).Seconds()) > replayWindow.Seconds() { return false } for _, entry := range strings.Split(sigHeader, ",") { v, ok := strings.CutPrefix(strings.TrimSpace(entry), "v1=") if !ok { continue } got, err := hex.DecodeString(v) if err != nil { continue } for _, s := range secrets { mac := hmac.New(sha256.New, []byte(s)) mac.Write([]byte(timestamp + "." + deliveryID + ".")) mac.Write(body) if hmac.Equal(got, mac.Sum(nil)) { return true } } } return false}
func main() { http.HandleFunc("POST /webhooks/ad80", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, 10<<20)) if err != nil { http.Error(w, "unreadable body", http.StatusBadRequest) return } if !verifyAD80(body, r.Header.Get("X-AD80-Timestamp"), r.Header.Get("X-AD80-Delivery"), r.Header.Get("X-AD80-Signature")) { http.Error(w, "bad signature", http.StatusUnauthorized) return } var event struct { Type string `json:"type"` } _ = json.Unmarshal(body, &event) // TODO: skip if the delivery id was already processed, else store it and queue the work. log.Println(r.Header.Get("X-AD80-Delivery"), event.Type) w.WriteHeader(http.StatusNoContent) }) log.Fatal(http.ListenAndServe(":3000", nil)) // Go 1.22+ for method patterns}<?php// PHP 7.4+. During a rotation, list both secrets until you have called retire-secrets.$secrets = [getenv('AD80_WEBHOOK_SECRET')];
function ad80_verify(string $raw, string $ts, string $deliveryId, string $header, array $secrets): bool{ if (!ctype_digit($ts) || abs(time() - (int) $ts) > 300) { return false; } foreach (explode(',', $header) as $entry) { $entry = trim($entry); if (strpos($entry, 'v1=') !== 0) { continue; } $given = strtolower(substr($entry, 3)); foreach ($secrets as $secret) { $want = hash_hmac('sha256', $ts . '.' . $deliveryId . '.' . $raw, $secret); if (hash_equals($want, $given)) { return true; } } } return false;}
$raw = file_get_contents('php://input'); // the exact bytes received$ts = $_SERVER['HTTP_X_AD80_TIMESTAMP'] ?? '';$deliveryId = $_SERVER['HTTP_X_AD80_DELIVERY'] ?? '';$signature = $_SERVER['HTTP_X_AD80_SIGNATURE'] ?? '';
if (!ad80_verify($raw, $ts, $deliveryId, $signature, $secrets)) { http_response_code(401); exit('bad signature');}
$event = json_decode($raw, true);// TODO: skip if $deliveryId was already processed, else store it and queue the work.error_log($deliveryId . ' ' . $event['type']);http_response_code(204);Common mistakes
Section titled “Common mistakes”- Verifying parsed JSON. Frameworks that parse the body for you change spacing and key order. Always sign the raw bytes.
- Forgetting the delivery id. The signed text is
timestamp.deliveryId.body, nottimestamp.body. - Only checking the first
v1=entry. During a rotation the header carries two signatures. - Comparing with
==. Use a constant-time comparison. - A skewed server clock. Keep your clock in sync (NTP); otherwise valid requests fall outside the 5-minute window.