Verifying signatures
Check the X-Duun-Signature header on every webhook delivery with HMAC-SHA256, with working Node.js, Python and Go handlers and a test vector.
On this page
Anyone who learns your endpoint’s URL can send it requests. Duun signs every delivery with your endpoint’s signing secret so your handler can prove a request came from Duun and wasn’t changed or replayed. Verify the signature before you parse or act on the body.
The same scheme applies to requests you send to a workflow Webhook trigger: sign them with the secret you picked for the trigger, and Duun verifies them the same way.
The signature header
Each delivery carries an X-Duun-Signature header:
X-Duun-Signature: t=1763208000,v1=ec8ba1c0a8062bb8c2bc0ae03677a8420a81e55f3b945e289c240555008f7bbdtis the Unix time, in seconds, when Duun signed the request.v1is the hex-encoded HMAC-SHA256 of the signed payload, keyed with the endpoint’s signing secret (the full string, including thewhsec_prefix).- During a secret rotation the header has two
v1values, one per secret:t=…,v1=<new>,v1=<old>.
Verify in five steps
- Read the raw request body as bytes, before any JSON parsing.
- Split the header on commas, then each part on the first
=, and collecttand everyv1value. - Reject the request if
tis more than 300 seconds away from your server’s clock, in either direction. - Compute HMAC-SHA256 over the string
<t>.<raw body>(the timestamp, a full stop, then the body) with your signing secret, and hex-encode it. - Compare your result with each
v1value in constant time, and accept the request if any of them match.
If verification fails, answer 400 and don’t process the event. Duun treats the 400 as a failed delivery and retries it, which gives you time to fix a misconfigured secret without losing events.
Why the timestamp matters. The timestamp is part of the signed payload, so an attacker can’t change it without breaking the signature. Checking that it is recent stops someone who captured a real request from replaying it later. Keep your server’s clock synced with NTP; a skewed clock is the most common cause of valid requests being rejected.
Why constant time. A normal string comparison returns as soon as two characters differ, and the timing difference can leak how much of a guessed signature was right. Use your language’s constant-time compare: crypto.timingSafeEqual in Node.js, hmac.compare_digest in Python, hmac.Equal in Go.
Handler examples
Each example reads the secret from the DUUN_WEBHOOK_SECRET environment variable, verifies the request, and returns 200 quickly.
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.DUUN_WEBHOOK_SECRET!; // whsec_…
const TOLERANCE_SECONDS = 300;
function verifyDuunSignature(rawBody: Buffer, header: string | undefined, secret: string): boolean {
if (!header) return false;
let timestamp = "";
const signatures: string[] = [];
for (const part of header.split(",")) {
const i = part.indexOf("=");
if (i === -1) continue;
const key = part.slice(0, i).trim();
const value = part.slice(i + 1).trim();
if (key === "t") timestamp = value;
else if (key === "v1") signatures.push(value);
}
const t = Number(timestamp);
if (!Number.isInteger(t) || signatures.length === 0) return false;
if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest();
return signatures.some((sig) => {
const received = Buffer.from(sig, "hex");
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
});
}
const app = express();
// express.raw keeps the body as a Buffer for this route only.
app.post("/webhooks/duun", express.raw({ type: "application/json" }), (req, res) => {
if (!verifyDuunSignature(req.body, req.header("X-Duun-Signature"), SECRET)) {
return res.status(400).send("Invalid signature");
}
const event = JSON.parse(req.body.toString("utf8"));
// Deduplicate on event.id, then hand off to a queue.
console.log(`Received ${event.type} ${event.id}`);
res.sendStatus(200);
});
app.listen(3000);import hashlib
import hmac
import json
import os
import time
from flask import Flask, abort, request
SECRET = os.environ["DUUN_WEBHOOK_SECRET"] # whsec_…
TOLERANCE_SECONDS = 300
app = Flask(__name__)
def verify_duun_signature(raw_body: bytes, header: str | None, secret: str) -> bool:
if not header:
return False
timestamp = ""
signatures: list[str] = []
for part in header.split(","):
key, sep, value = part.partition("=")
if not sep:
continue
key, value = key.strip(), value.strip()
if key == "t":
timestamp = value
elif key == "v1":
signatures.append(value)
if not timestamp.isdigit() or not signatures:
return False
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
return False
signed_payload = timestamp.encode() + b"." + raw_body
expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, sig) for sig in signatures)
@app.post("/webhooks/duun")
def duun_webhook():
raw_body = request.get_data() # bytes, before any JSON parsing
if not verify_duun_signature(raw_body, request.headers.get("X-Duun-Signature"), SECRET):
abort(400, "Invalid signature")
event = json.loads(raw_body)
# Deduplicate on event["id"], then hand off to a queue.
print(f"Received {event['type']} {event['id']}")
return "", 200package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const toleranceSeconds = 300
func verifyDuunSignature(rawBody []byte, header, secret string) bool {
var timestamp string
var signatures []string
for _, part := range strings.Split(header, ",") {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok {
continue
}
switch key {
case "t":
timestamp = value
case "v1":
signatures = append(signatures, value)
}
}
t, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil || len(signatures) == 0 {
return false
}
if math.Abs(float64(time.Now().Unix()-t)) > toleranceSeconds {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp + "."))
mac.Write(rawBody)
expected := mac.Sum(nil)
for _, sig := range signatures {
received, err := hex.DecodeString(sig)
if err == nil && hmac.Equal(received, expected) {
return true
}
}
return false
}
func main() {
secret := os.Getenv("DUUN_WEBHOOK_SECRET") // whsec_…
http.HandleFunc("POST /webhooks/duun", func(w http.ResponseWriter, r *http.Request) {
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Could not read body", http.StatusBadRequest)
return
}
if !verifyDuunSignature(rawBody, r.Header.Get("X-Duun-Signature"), secret) {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
var event struct {
ID string `json:"id"`
Type string `json:"type"`
}
if err := json.Unmarshal(rawBody, &event); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Deduplicate on event.ID, then hand off to a queue.
log.Printf("Received %s %s", event.Type, event.ID)
w.WriteHeader(http.StatusOK)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}Verify with an SDK
The TypeScript and Python SDKs (Preview) implement the same checks, including the 300-second tolerance and multiple v1 values. Both return the parsed event or throw. In TypeScript, constructEvent returns a promise because it uses Web Crypto.
const event = await duun.webhooks.constructEvent(rawBody, request.headers.get("x-duun-signature"), process.env.DUUN_WEBHOOK_SECRET!);event = client.webhooks.construct_event(raw_body, request.headers["X-Duun-Signature"], os.environ["DUUN_WEBHOOK_SECRET"])A failed check raises Duun.WebhookSignatureError in TypeScript and duun.WebhookSignatureError in Python.
Test vector
Use these values to check your implementation offline. Skip the timestamp check while testing, since the timestamp is in the past.
| Input | Value |
|---|---|
| Secret | whsec_test_5f2c8a1e9b3d4f6a |
Timestamp t | 1763208000 |
| Body | the single line of JSON below, with no trailing newline |
{"id":"evt_9xYtest01","object":"event","type":"run.succeeded","created_at":"2026-11-15T12:00:00Z","api_version":"2026-11-01","workspace_id":"ws_acme","data":{"object":{"id":"run_7f3aK2pQ","object":"run","status":"succeeded"}}}The signed payload is 1763208000. followed by the body, and the expected signature is:
v1=ec8ba1c0a8062bb8c2bc0ae03677a8420a81e55f3b945e289c240555008f7bbdYou can reproduce it from a shell:
printf '%s' '1763208000.{"id":"evt_9xYtest01","object":"event","type":"run.succeeded","created_at":"2026-11-15T12:00:00Z","api_version":"2026-11-01","workspace_id":"ws_acme","data":{"object":{"id":"run_7f3aK2pQ","object":"run","status":"succeeded"}}}' \
| openssl dgst -sha256 -hmac 'whsec_test_5f2c8a1e9b3d4f6a' -hexRotating the signing secret
Rotate a secret when someone who had access leaves, or if it may have leaked. In Settings → Webhooks, open the endpoint menu and choose Rotate signing secret…, or call POST /webhook_endpoints/{endpoint_id}/rotate_secret. You choose when the old secret stops working:
- Now: deliveries are signed with the new secret only. Use this if the old secret leaked.
- 1 hour or 24 hours: each delivery carries two
v1values, one signed with the new secret and one with the old, until the window ends.
With a grace window, a zero-downtime rotation looks like this:
- Rotate with a 24-hour window and copy the new secret.
- Deploy your handler with the new secret. The examples above accept a request if any
v1matches, so they keep working with either secret during the window. - After the window ends, remove the old secret from your secret manager.
Troubleshooting
| Symptom | Likely cause |
|---|---|
| Every request fails, including Send test event | Wrong secret (each endpoint has its own), or the body was parsed and re-serialized before hashing. |
| Requests fail only sometimes | Server clock drift beyond 300 seconds, or a proxy that rewrites bodies (compression, re-encoding). |
Local requests fail with duun webhooks listen | Use the temporary secret the CLI prints, not the endpoint’s secret. |
| Requests fail right after rotating | The new secret isn’t deployed yet and you chose Now. Rotate again with a grace window. |
For delivery problems that aren’t about signatures, see Webhook deliveries are failing.