Verifica delle firme
Come viene firmato
Il contenuto firmato è l’header webhook-id, l’header webhook-timestamp e il corpo grezzo della richiesta uniti da punti: <id>.<timestamp>.<body>. La chiave è il tuo segreto senza il prefisso whsec_, decodificato da base64. webhook-signature contiene v1, seguito dall’HMAC-SHA256 in base64 di quel contenuto.
Mentre un segreto ruotato è nel periodo di tolleranza, webhook-signature contiene due firme separate da spazio, una per segreto; accetta la consegna se ne corrisponde una qualsiasi.
- Verifica il corpo grezzo esattamente come ricevuto, prima di analizzare il JSON: risserializzarlo cambia i byte.
- Rifiuta un webhook-timestamp che dista più di 5 minuti dal tuo orologio, così una richiesta catturata non può essere riprodotta in seguito.
- Confronta le firme in tempo costante.
- Rispondi 2xx subito e fai il lavoro lento dopo: aspettiamo 10 secondi.
Con una libreria Standard Webhooks
I pacchetti standardwebhooks su npm e PyPI (e le librerie per la maggior parte degli altri linguaggi) controllano firma e timestamp in una sola chiamata e lanciano un errore quando uno dei due è sbagliato.
// npm install standardwebhooksimport { Webhook } from "standardwebhooks";const wh = new Webhook(process.env.DOTWICK_WEBHOOK_SECRET); // whsec_…// Express: app.post("/dotwick", express.raw({ type: "application/json" }), handler)function handler(req, res) { let event; try { event = wh.verify(req.body.toString("utf8"), { "webhook-id": req.header("webhook-id"), "webhook-timestamp": req.header("webhook-timestamp"), "webhook-signature": req.header("webhook-signature"), }); } catch { return res.status(400).end(); } res.status(204).end(); // answer first, then work queue.add(event.type, event);}A mano
Nessuna dipendenza: l’intero controllo sono poche righe della libreria standard.
import { createHmac, timingSafeEqual } from "node:crypto";function verifyDotwick(secret, headers, rawBody) { const id = headers["webhook-id"]; const timestamp = headers["webhook-timestamp"]; const signatures = headers["webhook-signature"] ?? ""; if (!id || !timestamp) return false; if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64"); const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest(); return signatures.split(" ").some((entry) => { const [version, signature] = entry.split(","); const received = Buffer.from(signature ?? "", "base64"); return ( version === "v1" && received.length === expected.length && timingSafeEqual(received, expected) ); });}