Verify webhooks
1Get the signing secret
Open Settings › Developers › Webhooks in cuil.si and pick the endpoint. The secret starts with
whsec_. Keep it on your server, like a password. For safety it can only be seen in the app, not through the API.2Check it with a library (easiest)
The official Standard Webhooks libraries do the whole check, including the time window, in one call.
// npm install standardwebhooks import { Webhook } from "standardwebhooks"; const webhook = new Webhook(process.env.CUILSI_WEBHOOK_SECRET); // "whsec_..." from Settings > Developers // Express: keep the raw body, the signature is made over the exact bytes we sent. app.post("/cuilsi-webhook", express.raw({ type: "application/json" }), (req, res) => { let event; try { event = webhook.verify(req.body.toString("utf8"), req.headers); // throws if it isn't from cuil.si } catch { return res.status(400).end(); } res.status(204).end(); // answer quickly, then do the work handle(event); // event.id, event.type, event.created_at, event.data });3Or check it yourself
Join the
webhook-id, thewebhook-timestampand the raw body with dots, sign that with HMAC-SHA256 using the secret (withoutwhsec_, decoded from base64), and compare it with the part afterv1,. Refuse timestamps older than 5 minutes.import crypto from "node:crypto"; // Use the raw request body (a string), not parsed JSON. export function isFromCuilsi(rawBody, headers, secret) { const id = headers["webhook-id"]; const timestamp = headers["webhook-timestamp"]; // Ignore requests older than 5 minutes (protects against replays). if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64"); const expected = crypto .createHmac("sha256", key) .update(`${id}.${timestamp}.${rawBody}`) .digest("base64"); return headers["webhook-signature"].split(" ").some((part) => { const [version, signature] = part.split(","); return ( version === "v1" && signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ); }); }4Answer quickly, and handle each event once
Answer with any 2xx within 10 seconds, then do the slow work. A request can come again (same
webhook-id) and requests can arrive out of order, so skip ids you have seen and usecreated_atto keep the newest.