Verify signatures
Check that a webhook really came from Rabbitflare.
3 min read Updated
Anyone who learns your endpoint's URL can send it a request. Every call from Rabbitflare is signed with the endpoint's own secret, so your code can tell that it came from us, that its body wasn't changed on the way, and that it was sent in the last 5 minutes.
The signature header
Each call carries a Rabbitflare-Signature header:
Rabbitflare-Signature: t=1794991609,v1=c9563915328fa744dc29eb537c6372861952b1df9666108a6262514bd15df038 t- When this attempt was sent, in Unix seconds.
v1-
The signature: the HMAC-SHA256 of
t, a dot and the raw body, made with the endpoint's signing secret (the whole of it, with itsrfwhsec_start), in hex. For 24 hours after the secret is rotated, a secondv1follows, made with the old secret.
Other names than t and v1 may appear later, for new ways of signing: skip them.
Check it
-
Read the raw body
Take the body as the bytes that arrived, before any JSON parsing. Parsed and written out again, it isn't the same bytes, and the signature won't match.
-
Read t and every v1
Split the header at the commas, and each part at its first
=. -
Refuse an old time
When
tis more than 5 minutes from your own clock, either way, refuse the call: a request someone recorded can't then be sent to you again later. Keep your server's clock right (NTP). -
Compute and compare
Compute the HMAC-SHA256 of
t, a dot and the raw body with your secret, and compare it with eachv1in constant time. When one matches, the call is ours: parse the body and go on. When none does, answer400and do nothing.
Complete receivers
Each of these is a whole web service, with nothing to install but the SDK for its own tab: it checks the signature, answers
204 at once, then handles each event once. Give it your endpoint's secret in RABBITFLARE_WEBHOOK_SECRET. The JavaScript
and SDK ones listen on port 3000 and the Python one on 8000 (or
PORT), behind your web server's https; the PHP one is a page your web server runs.
// Receives Rabbitflare webhooks: checks each call's signature, answers at once,
// then handles each event once.
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const SECRET = process.env.RABBITFLARE_WEBHOOK_SECRET;
if (!SECRET) throw new Error("Set RABBITFLARE_WEBHOOK_SECRET to the endpoint's secret");
const TOLERANCE_SECONDS = 300;
// The ids of the events handled. Keep them in your database, for a few days at least.
const handled = new Set();
// Whether the Rabbitflare-Signature header was made with your secret,
// over this raw body, in the last 5 minutes.
function isFromRabbitflare(rawBody, header) {
let timestamp = null;
const signatures = [];
for (const part of (header ?? "").split(",")) {
const [name, value = ""] = part.trim().split("=");
if (name === "t" && /^\d+$/.test(value)) timestamp = Number(value);
if (name === "v1" && /^[0-9a-f]{64}$/i.test(value)) {
signatures.push(Buffer.from(value, "hex"));
}
}
if (timestamp === null) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) return false;
const hmac = createHmac("sha256", SECRET).update(`${timestamp}.`).update(rawBody);
const expected = hmac.digest();
// Compared in constant time. For 24 hours after a secret is rotated,
// the header holds two v1 values (new and old secret): either may match.
return signatures.some((signature) => timingSafeEqual(signature, expected));
}
createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
// The raw bytes, as sent: JSON parsed and written out again isn't the same.
const rawBody = Buffer.concat(chunks);
const signature = req.headers["rabbitflare-signature"];
if (req.method !== "POST" || !isFromRabbitflare(rawBody, signature)) {
res.writeHead(400).end();
return;
}
// Answer within 10 seconds, and do the work after answering.
res.writeHead(204).end();
const event = JSON.parse(rawBody.toString("utf8"));
if (handled.has(event.id)) return; // Sent again: handled already.
handled.add(event.id);
handle(event);
});
}).listen(Number(process.env.PORT ?? 3000));
function handle(event) {
// Your work here. New event types can appear: ignore those you don't handle.
console.log(`${event.type} ${event.id}: ${event.data.message}`);
} // Receives Rabbitflare webhooks: checks each call's signature, answers at once,
// then handles each event once.
import { createServer } from "node:http";
import { verifyWebhook, WebhookVerificationError } from "@rabbitflare/api";
const SECRET = process.env.RABBITFLARE_WEBHOOK_SECRET;
if (!SECRET) throw new Error("Set RABBITFLARE_WEBHOOK_SECRET to the endpoint's secret");
// The ids of the events handled. Keep them in your database, for a few days at least.
const handled = new Set();
// The event, if the Rabbitflare-Signature header was made with your secret,
// over this raw body, in the last 5 minutes; else null.
function verified(rawBody, header) {
try {
return verifyWebhook(rawBody, header, SECRET);
} catch (err) {
if (err instanceof WebhookVerificationError) return null;
throw err;
}
}
createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
// The raw bytes, as sent: JSON parsed and written out again isn't the same.
const rawBody = Buffer.concat(chunks);
const event = req.method === "POST" ? verified(rawBody, req.headers["rabbitflare-signature"]) : null;
if (!event) {
res.writeHead(400).end();
return;
}
// Answer within 10 seconds, and do the work after answering.
res.writeHead(204).end();
if (handled.has(event.id)) return; // Sent again: handled already.
handled.add(event.id);
handle(event);
});
}).listen(Number(process.env.PORT ?? 3000));
function handle(event) {
// Your work here. New event types can appear: ignore those you don't handle.
console.log(`${event.type} ${event.id}: ${event.data.message}`);
} <?php
// Receives Rabbitflare webhooks: checks each call's signature, answers at once,
// then handles each event once.
// Served by PHP-FPM (or any PHP web server) at the URL of your endpoint.
/**
* Whether the Rabbitflare-Signature header was made with your secret,
* over this raw body, in the last 5 minutes.
*/
function isFromRabbitflare(string $rawBody, string $header, string $secret): bool
{
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$name, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($name === 't' && ctype_digit($value)) {
$timestamp = (int) $value;
} elseif ($name === 'v1' && preg_match('/^[0-9a-f]{64}$/i', $value)) {
$signatures[] = strtolower($value);
}
}
if ($timestamp === null || abs(time() - $timestamp) > 300) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
// Compared in constant time. For 24 hours after a secret is rotated,
// the header holds two v1 values (new and old secret): either may match.
if (hash_equals($expected, $signature)) {
return true;
}
}
return false;
}
$secret = getenv('RABBITFLARE_WEBHOOK_SECRET');
if (!$secret) {
http_response_code(500);
exit("Set RABBITFLARE_WEBHOOK_SECRET to the endpoint's secret");
}
// The raw bytes, as sent: JSON parsed and written out again isn't the same.
$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_RABBITFLARE_SIGNATURE'] ?? '';
$isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
if (!$isPost || !isFromRabbitflare($rawBody, $signature, $secret)) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
// Each event once: fopen's x mode makes the file only if it isn't there yet.
// With a database, use the event id as a unique key instead.
$marker = sys_get_temp_dir() . '/rabbitflare-event-' . hash('sha256', $event['id']);
$first = @fopen($marker, 'x');
// Answer within 10 seconds, and do the work after answering.
http_response_code(204);
if ($first === false) {
exit; // Sent again: handled already.
}
fclose($first);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // PHP-FPM sends the answer now.
}
handle($event);
function handle(array $event): void
{
// Your work here. New event types can appear: ignore those you don't handle.
error_log("{$event['type']} {$event['id']}: {$event['data']['message']}");
} # Receives Rabbitflare webhooks: checks each call's signature, answers at once,
# then handles each event once.
import hashlib
import hmac
import json
import os
import re
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
SECRET = os.environ["RABBITFLARE_WEBHOOK_SECRET"].encode()
TOLERANCE_SECONDS = 300
# The ids of the events handled. Keep them in your database, for a few days at least.
handled = set()
def is_from_rabbitflare(raw_body, header):
"""Whether the Rabbitflare-Signature header was made with your secret,
over this raw body, in the last 5 minutes."""
timestamp, signatures = None, []
for part in (header or "").split(","):
name, _, value = part.strip().partition("=")
if name == "t" and re.fullmatch(r"[0-9]+", value):
timestamp = int(value)
elif name == "v1" and re.fullmatch(r"[0-9a-fA-F]{64}", value):
signatures.append(value.lower())
if timestamp is None or abs(time.time() - timestamp) > TOLERANCE_SECONDS:
return False
signed = f"{timestamp}.".encode() + raw_body
expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
# Compared in constant time. For 24 hours after a secret is rotated,
# the header holds two v1 values (new and old secret): either may match.
return any(hmac.compare_digest(expected, signature) for signature in signatures)
class Receiver(BaseHTTPRequestHandler):
def do_POST(self):
# The raw bytes, as sent: JSON parsed and written out again isn't the same.
raw_body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
signature = self.headers.get("Rabbitflare-Signature")
if not is_from_rabbitflare(raw_body, signature):
self.send_response(400)
self.end_headers()
return
# Answer within 10 seconds, and do the work after answering.
self.send_response(204)
self.end_headers()
event = json.loads(raw_body)
if event["id"] in handled:
return # Sent again: handled already.
handled.add(event["id"])
handle(event)
def handle(event):
# Your work here. New event types can appear: ignore those you don't handle.
print(f'{event["type"]} {event["id"]}: {event["data"]["message"]}', flush=True)
port = int(os.environ.get("PORT", "8000"))
ThreadingHTTPServer(("", port), Receiver).serve_forever() They keep the ids they've handled in memory, or in files for PHP, to stay short: keep them in your database instead, with the id as a unique key, so a restart forgets nothing.
With a framework
Check the signature before the framework parses the JSON, on the raw body: express.raw({ type: "application/json" }) in
Express, request.get_data() in Flask, request.body in Django, and $request->getContent() in Laravel.
For WordPress, see Receive webhooks in WordPress.
Test your code
This secret, time and body sign to this v1. Compute the HMAC-SHA256 of t, a dot and the body with the secret: you
should get the same value. The message holds curly quotes, so code that signs re-encoded text instead of the bytes gets another one.
secret: rfwhsec_8xKq2LmT5vRj9WbN3cYh7PzD4gFs6AeU
t: 1794991609
body: {"id":"5f0d2a7c-8e1b-4c3d-9a6f-2b7e1d4c8a90","type":"site.ready","apiVersion":"v1","createdAt":"2026-11-18T08:46:49.000Z","accountId":"0b9f2c1e-7d4a-4f6b-8c2e-1a3d5f7b9c0e","data":{"level":"success","message":"“Blog” is live","actor":{"type":"system","name":null},"server":{"id":"3c6e9a1f-2b4d-4e8a-9f0c-5d7b1e3a6c2f","name":"web-1"},"site":{"id":"9e2f4a6c-1d3b-4f5e-8a7c-0b2d4f6e8a1c","name":"Blog"},"mailDomain":null,"resource":{"type":"site","id":"9e2f4a6c-1d3b-4f5e-8a7c-0b2d4f6e8a1c","url":"https://api.rabbitflare.com/v1/sites/9e2f4a6c-1d3b-4f5e-8a7c-0b2d4f6e8a1c"}}}
v1: c9563915328fa744dc29eb537c6372861952b1df9666108a6262514bd15df038 Then send a test event to your endpoint: it's signed like every other call.
Rotating the secret
Rotate an endpoint's secret if it may have leaked, or on a schedule. The new secret signs every call at once, and for 24 hours
each call also carries a v1 made with the old one, so a receiver still on the old secret keeps accepting calls while you switch:
-
Rotate it
In the panel (with your authenticator code), or with
POST /v1/webhooks/endpoints/{endpointId}/actions/rotate-secretfor an endpoint added with the same token. The new secret is shown once. -
Give your receiver the new secret
Within 24 hours. Calls carry both signatures until then, so it doesn't matter when in that time.
Rotating again within the 24 hours ends the first old secret at once. Keep the secret as safe as an API token, and see Webhooks for what else your endpoint must do.
Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.