Verify signatures
Anyone can send a request to your endpoint. The Supportaka-Signature header proves a delivery came from Supportaka and wasn’t changed on the way:
Supportaka-Signature: t=1795681200,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdtis when it was signed (Unix seconds).v1is the hex HMAC-SHA256 of"<t>.<raw body>", keyed with your endpoint’s secret (whsec_…).- Right after you rotate the secret there are two
v1values, one per secret. Accept the delivery if any of them matches.
The steps
Section titled “The steps”- Read the raw request body, exactly as received. Don’t parse it and re-serialise it first: any change in spacing breaks the signature.
- Split the header on
,and taketand everyv1. - Compute
HMAC-SHA256(secret, t + "." + rawBody)as lowercase hex. - Compare it with each
v1using a constant-time comparison. - Check
tis recent (within 5 minutes) to stop old deliveries being replayed at you.
import crypto from 'node:crypto';import express from 'express';
const secret = process.env.SUPPORTAKA_WEBHOOK_SECRET;
function verify(rawBody, header, toleranceSeconds = 300) { const parts = Object.groupBy(header.split(','), (p) => p.split('=')[0]); const t = parts.t?.[0]?.slice(2); const signatures = (parts.v1 ?? []).map((p) => p.slice(3)); if (!t || !signatures.length) return false; if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex'); return signatures.some( (s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)), );}
const app = express();
// Keep the raw body for this route.app.post('/webhooks/supportaka', express.raw({ type: 'application/json' }), (req, res) => { if (!verify(req.body, req.get('Supportaka-Signature') ?? '')) return res.status(400).send('bad signature');
const event = JSON.parse(req.body); res.sendStatus(200); // answer first… handle(event).catch(console.error); // …then do the work (better: put it on a queue)});import hashlib, hmac, json, os, timefrom flask import Flask, request, abort
secret = os.environ["SUPPORTAKA_WEBHOOK_SECRET"].encode()app = Flask(__name__)
def verify(raw_body: bytes, header: str, tolerance=300) -> bool: parts = [p.split("=", 1) for p in header.split(",") if "=" in p] t = next((v for k, v in parts if k == "t"), None) signatures = [v for k, v in parts if k == "v1"] if not t or not signatures or abs(time.time() - int(t)) > tolerance: return False expected = hmac.new(secret, f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return any(hmac.compare_digest(expected, s) for s in signatures)
@app.post("/webhooks/supportaka")def supportaka_webhook(): raw = request.get_data() # the raw bytes, before any parsing if not verify(raw, request.headers.get("Supportaka-Signature", "")): abort(400) event = json.loads(raw) queue.enqueue(handle, event) # do the work later return "", 200<?php$secret = getenv('SUPPORTAKA_WEBHOOK_SECRET');$raw = file_get_contents('php://input'); // the raw body$header = $_SERVER['HTTP_SUPPORTAKA_SIGNATURE'] ?? '';
function supportaka_verify(string $raw, string $header, string $secret, int $tolerance = 300): bool { $t = null; $signatures = []; foreach (explode(',', $header) as $part) { [$k, $v] = array_pad(explode('=', $part, 2), 2, ''); if ($k === 't') $t = $v; if ($k === 'v1') $signatures[] = $v; } if (!$t || !$signatures || abs(time() - (int) $t) > $tolerance) return false; $expected = hash_hmac('sha256', $t . '.' . $raw, $secret); foreach ($signatures as $s) { if (hash_equals($expected, $s)) return true; } return false;}
if (!supportaka_verify($raw, $header, $secret)) { http_response_code(400); exit('bad signature');}$event = json_decode($raw, true);http_response_code(200);// …queue $event for processingpackage webhooks
import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "io" "math" "net/http" "os" "strconv" "strings" "time")
var secret = []byte(os.Getenv("SUPPORTAKA_WEBHOOK_SECRET"))
func Verify(body []byte, header string, tolerance time.Duration) bool { var t string var sigs []string for _, part := range strings.Split(header, ",") { k, v, _ := strings.Cut(part, "=") switch k { case "t": t = v case "v1": sigs = append(sigs, v) } } ts, err := strconv.ParseInt(t, 10, 64) if err != nil || len(sigs) == 0 || math.Abs(time.Since(time.Unix(ts, 0)).Seconds()) > tolerance.Seconds() { return false } mac := hmac.New(sha256.New, secret) mac.Write([]byte(t + ".")) mac.Write(body) expected := hex.EncodeToString(mac.Sum(nil)) for _, s := range sigs { if hmac.Equal([]byte(expected), []byte(s)) { return true } } return false}
func Handler(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil || !Verify(body, r.Header.Get("Supportaka-Signature"), 5*time.Minute) { http.Error(w, "bad signature", http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) go handle(body) // better: put it on a queue}When it doesn’t verify
Section titled “When it doesn’t verify”- Using the parsed body. Frameworks often parse JSON before your code runs. Use the raw bytes (
express.raw,request.get_data(),php://input). - Wrong secret. Each endpoint has its own secret, and rotating it shows a new one. Check you deployed the right one.
- Clock skew. If your server’s clock is off by minutes, the time check fails. Keep it synced (NTP).