Verify the signature

Confirm that every webhook comes from Caibo and wasn't tampered with. Ready-to-use code in Node.js, Python, and Go.

Every webhook includes Psp-Signature:

Psp-Signature: t=1790769600,v1=c0c9eaafdea23b0f8c992b380b286917c6459b0729b2496b8452fa695215e6b8
  • t is the time of the signature, in Unix seconds.
  • v1 is a hex-encoded HMAC-SHA256, keyed with your secret, over t + . + the exact body you received.
  • The key is the full secret, including the whsec_ prefix.
  • There can be more than one v1 (during a rotation). It's enough for one to match.

To accept a webhook:

  1. Compute the HMAC over the untouched body: don't parse or re-serialize it first.
  2. Compare against each v1 in constant time.
  3. Reject it if t differs from your clock by more than 5 minutes: that way nobody can replay an old notification to you.
const crypto = require("crypto");

// rawBody: the exact bytes received (a Buffer).
function verifyCaiboSignature(secret, header, rawBody, toleranceSeconds = 300) {
  let t = null;
  const signatures = [];
  for (const part of String(header || "").split(",")) {
    const [key, value] = part.trim().split("=", 2);
    if (key === "t") {
      if (t !== null || !/^\d+$/.test(value)) return false;
      t = value;
    } else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value)) {
      signatures.push(Buffer.from(value, "hex"));
    }
  }
  if (t === null || signatures.length === 0) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest();
  if (!signatures.some((s) => crypto.timingSafeEqual(s, expected))) return false;
  return Math.abs(Date.now() / 1000 - Number(t)) <= toleranceSeconds;
}

// Express: read the body raw, verify, then parse.
app.post("/webhooks/caibo", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyCaiboSignature(process.env.CAIBO_WEBHOOK_SECRET, req.get("Psp-Signature"), req.body)) {
    return res.sendStatus(400);
  }
  const event = JSON.parse(req.body);
  queue.push(event); // process later; dedupe on event.id
  res.sendStatus(200);
});

Test your code

With these values your function must accept the signature (ignoring the tolerance, because t is a past date):

Secretwhsec_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
Body (exact, no trailing newline){"id":"evt_1","type":"payout.completed","data":{"amount":"10.00"}}
t1790769600
Expected signaturet=1790769600,v1=c0c9eaafdea23b0f8c992b380b286917c6459b0729b2496b8452fa695215e6b8

To test against your real server, use POST/v1/webhook-endpoints/{id}/ping.

The most common mistake

Many frameworks parse the JSON before you see it. If you sign JSON.stringify(req.body) instead of the original body, the signature won't match. Read the raw body.

Sur cette page