Webhooks
Check the signature
On this page
Anyone who knows your endpoint's address could post fake messages to it. Check the signature of every message, and ignore messages that fail.
How the signature works#
Every message carries the header X-GroKeeper-Signature with a time and one or two signatures:
X-GroKeeper-Signature: t=1763719200,v1=3b1d9c0f...- Take the raw body exactly as you received it, before any JSON parsing. Changing even one space breaks the signature.
- Build the text
{t}.{raw body}: the number aftert=, a dot, then the body. - Compute HMAC-SHA256 of that text with your endpoint's signing secret and write the result as lowercase hexadecimal.
- Compare it with each
v1=value using a constant-time comparison. If any one matches, the message is genuine. - Also reject messages whose
tis more than 5 minutes away from your clock. A retry sent hours later still passes, because the time is renewed at every attempt.
There can be two v1= values while you rotate a secret: the old secret keeps signing for 24 hours so you can switch over without losing messages.
Working code#
<?php
// $secret is your endpoint's signing secret. Keep it out of your code: use a setting or an environment variable.
$secret = getenv('GROKEEPER_WEBHOOK_SECRET');
$payload = file_get_contents('php://input'); // the RAW body, exactly as received
$header = $_SERVER['HTTP_X_GROKEEPER_SIGNATURE'] ?? ''; // t=1763719200,v1=3b1d...
// Read the parts by hand, because v1 can appear twice while a secret is being rotated.
$t = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
if ($k === 't') { $t = (int) $v; }
if ($k === 'v1') { $signatures[] = $v; }
}
// Reject anything older (or newer) than 5 minutes.
if (!$t || abs(time() - $t) > 300) {
http_response_code(400);
exit('timestamp too old');
}
$expected = hash_hmac('sha256', $t . '.' . $payload, $secret);
$ok = false;
foreach ($signatures as $s) {
$ok = $ok || hash_equals($expected, $s);
}
if (!$ok) {
http_response_code(400);
exit('bad signature');
}
$event = json_decode($payload, true); // $event['id'], $event['type'], $event['data']
http_response_code(200); // answer with 2xx quickly; do the slow work afterwards// Express. The route must receive the RAW body, so use express.raw() for it:
import express from 'express';
import crypto from 'node:crypto';
const app = express();
app.post('/webhooks/grokeeper', express.raw({ type: 'application/json' }), (req, res) => {
const payload = req.body.toString('utf8'); // the RAW body, exactly as received
const header = req.headers['x-grokeeper-signature'] || ''; // t=1763719200,v1=3b1d...
const parts = header.split(',').map((p) => p.trim().split('='));
const t = Number((parts.find(([k]) => k === 't') || [])[1]);
const signatures = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
// Reject anything older (or newer) than 5 minutes.
if (!t || Math.abs(Date.now() / 1000 - t) > 300) return res.status(400).send('timestamp too old');
const expected = crypto
.createHmac('sha256', process.env.GROKEEPER_WEBHOOK_SECRET)
.update(`${t}.${payload}`)
.digest('hex');
const ok = signatures.some(
(s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected))
);
if (!ok) return res.status(400).send('bad signature');
const event = JSON.parse(payload); // event.id, event.type, event.data
res.sendStatus(200); // answer with 2xx quickly; do the slow work afterwards
});
app.listen(3000);# Flask. Keep the signing secret in an environment variable, not in your code.
import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["GROKEEPER_WEBHOOK_SECRET"].encode()
@app.post("/webhooks/grokeeper")
def grokeeper_webhook():
payload = request.get_data() # the RAW body, exactly as received
header = request.headers.get("X-GroKeeper-Signature", "") # t=1763719200,v1=3b1d...
parts = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
t = next((int(v) for k, v in parts if k == "t" and v.isdigit()), 0)
signatures = [v for k, v in parts if k == "v1"] # v1 can appear twice while a secret is rotated
# Reject anything older (or newer) than 5 minutes.
if not t or abs(time.time() - t) > 300:
abort(400, "timestamp too old")
expected = hmac.new(SECRET, str(t).encode() + b"." + payload, hashlib.sha256).hexdigest()
if not any(hmac.compare_digest(expected, s) for s in signatures):
abort(400, "bad signature")
event = request.get_json(force=True) # event["id"], event["type"], event["data"]
return "", 200 # answer with 2xx quickly; do the slow work afterwardsCheck your code with a test value#
Use these made-up values to confirm your code produces the same signature. The secret is not a real one.
| Item | Value |
|---|---|
| Secret | whsec_example |
Time (t) | 1763719200 |
| Raw body | {"id":"evt_example0001","type":"order.paid"} |
| Expected header | X-GroKeeper-Signature: t=1763719200,v1=3f1ac112b6131d00e3b5311eeb658a24cabfb00fb51f4a0ccb2fe13cd5c7a6e0 |
Important
Never put your real signing secret in a web page, a repository or an email. It is shown once when the endpoint is created or rotated.