Verifying signatures
Add an HMAC secret to a rule and check X-NotifyHook-Signature on your server to verify body integrity and knowledge of the shared key.
How signing works#
When a rule has an HMAC SHA-256 signing secret, every request includes:
X-NotifyHook-Signature: c9da6ec3388eb4838012674003f9d727046875a21bd22403a9c5f05be0a3e2c0- Algorithm: HMAC-SHA256. The key is your secret's UTF-8 bytes.
- Input: the exact raw request body, as UTF-8 bytes. This is the body after placeholders and secrets have been filled in.
- Output: lowercase hex, 64 characters, with no
sha256=prefix. - Only the body is signed. The URL and headers are not part of the signature. There is no separate signing timestamp or built-in freshness check; any timestamps in the body are ordinary template fields.
Set up#
-
Generate a secret#
Use a long random value and keep a copy for your server:
Shellopenssl rand -hex 32 -
Add it to the rule#
Paste it into HMAC SHA-256 signing secret in the rule editor and save. It's stored encrypted and can't be viewed again.
-
Verify on your server#
Compute the HMAC of the raw body and compare it with the header in constant time. Reject the request with
401if they don't match.
Verify the bytes exactly as received, before parsing. If you parse the JSON and serialize it again, whitespace and key order change and the signature won't match.
Examples#
Set NOTIFYHOOK_SECRET in your receiver's environment (a secret binding for Workers), using the exact text saved in the rule. A hex string generated by OpenSSL is used as text, not hex-decoded. The server examples use port 3000 behind HTTPS; see runtime setup. Save the signing key in the app before using Test webhook.
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.NOTIFYHOOK_SECRET;
if (!SECRET) throw new Error("Set NOTIFYHOOK_SECRET");
const app = express();
// Keep the raw bytes: use express.raw, not express.json.
app.post("/hooks/notify", express.raw({ type: "application/json" }), (req, res) => {
if (!Buffer.isBuffer(req.body)) return res.status(415).send("expected application/json");
const expected = crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
const received = req.get("X-NotifyHook-Signature") ?? "";
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(received, "utf8");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.status(401).send("bad signature");
}
let event;
try {
event = JSON.parse(req.body.toString("utf8"));
} catch {
return res.status(400).send("invalid JSON");
}
if (!event || typeof event !== "object" || Array.isArray(event)) {
return res.status(400).send("expected a JSON object");
}
console.log(event.title);
res.sendStatus(204);
});
app.listen(3000);import hashlib
import hmac
import json
import os
from flask import Flask, abort, request
SECRET = os.environ["NOTIFYHOOK_SECRET"].encode()
if not SECRET:
raise RuntimeError("Set NOTIFYHOOK_SECRET")
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
@app.post("/hooks/notify")
def notify():
raw = request.get_data() # raw bytes, before any parsing
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
received = request.headers.get("X-NotifyHook-Signature", "")
if not received.isascii() or not hmac.compare_digest(expected, received):
abort(401)
try:
event = json.loads(raw)
except (ValueError, UnicodeDecodeError):
abort(400)
if not isinstance(event, dict):
abort(400)
print(event.get("title", ""))
return "", 204package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"log"
"net/http"
"os"
)
var secret = []byte(os.Getenv("NOTIFYHOOK_SECRET"))
func verify(body []byte, signature string) bool {
mac := hmac.New(sha256.New, secret)
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(signature))
}
func notify(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
} else {
http.Error(w, "could not read body", http.StatusBadRequest)
}
return
}
if !verify(body, r.Header.Get("X-NotifyHook-Signature")) {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
// json.Unmarshal(body, &event) ...
w.WriteHeader(http.StatusNoContent)
}
func main() {
if len(secret) == 0 {
log.Fatal("Set NOTIFYHOOK_SECRET")
}
http.HandleFunc("POST /hooks/notify", notify)
log.Fatal(http.ListenAndServe(":3000", nil))
}export default {
async fetch(request, env) {
if (request.method !== "POST") return new Response(null, { status: 405 });
if (!env.NOTIFYHOOK_SECRET) return new Response("signing not configured", { status: 500 });
const body = await request.arrayBuffer();
const signature = request.headers.get("X-NotifyHook-Signature") ?? "";
if (!/^[0-9a-f]{64}$/.test(signature)) return new Response("bad signature", { status: 401 });
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(env.NOTIFYHOOK_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"],
);
const sigBytes = new Uint8Array(signature.match(/../g).map((h) => parseInt(h, 16)));
// crypto.subtle.verify compares in constant time.
const ok = await crypto.subtle.verify("HMAC", key, sigBytes, body);
if (!ok) return new Response("bad signature", { status: 401 });
let event;
try {
event = JSON.parse(new TextDecoder().decode(body));
} catch {
return new Response("invalid JSON", { status: 400 });
}
if (!event || typeof event !== "object" || Array.isArray(event)) {
return new Response("expected a JSON object", { status: 400 });
}
console.log(event.title);
return new Response(null, { status: 204 });
},
};# Check a captured request by hand.
BODY='{"rule":"Test","title":"Hello"}'
SECRET='my-signing-secret'
printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}'
# c9da6ec3388eb4838012674003f9d727046875a21bd22403a9c5f05be0a3e2c0Test vector#
Use this to check your implementation:
| Secret | my-signing-secret |
|---|---|
| Body | {"rule":"Test","title":"Hello"} |
| Signature | c9da6ec3388eb4838012674003f9d727046875a21bd22403a9c5f05be0a3e2c0 |
Replay protection#
The signature proves the body came from someone who knows the secret and wasn't changed. It doesn't stop someone who captured a request from sending it again. To protect against replays, include a unique ID in the template. Because it's in the body, it's covered by the signature:
{
"id": "{{event.uuid}}",
"sentAt": {{time.epochMs}},
"title": "{{title}}"
}- After verifying the signature, atomically record accepted
idvalues and skip repeated side effects. Return2xxfor an already processed ID so legitimate retries stop. This also removes duplicate deliveries. - Be careful with a strict time window on
sentAt. It records the initial render time, not each request's send time. Retries can be hours later, and offline waiting or pause can last longer without using attempts.
These are minimal verification examples, not complete production servers. Add appropriate request-size limits (including at the edge for Workers), JSON/schema validation before acting, durable deduplication and operational monitoring. The Node raw parser defaults to a 100 KB limit; the Python and Go examples cap bodies at 1 MiB. Choose limits that fit your own templates.
Signature doesn't match?#
- Are you hashing the raw bytes, not re-serialized JSON? Frameworks often parse the body before your code runs.
- Is the secret exactly the same? Watch for trailing newlines, which are easy to add when copying from a terminal or
.envfile. - Are you comparing lowercase hex, without a
sha256=prefix? - Is a proxy changing the body, for example by re-encoding or pretty-printing it?