SocialBoost

Vérifier la signature

Validez l'authenticité des webhooks reçus avec HMAC-SHA256.

Principe

Calculez HMAC-SHA256(secret, "{timestamp}.{raw_body}") et comparez-le àv1 via une comparaison constante. N'utilisez jamais le body parsé — utilisez le body brut.

Node.js

import { createHmac, timingSafeEqual } from "crypto";

function verify(req, secret) {
  const sig = req.headers["x-socialboost-signature"]; // "t=..,v1=.."
  const ts = req.headers["x-socialboost-timestamp"];
  const body = req.rawBody; // raw string, NOT JSON.parse'd
  const v1 = sig.split(",").find(p => p.startsWith("v1="))?.slice(3);
  const expected = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");
  return v1 && timingSafeEqual(Buffer.from(v1, "hex"), Buffer.from(expected, "hex"));
}

Python

import hmac, hashlib

def verify(headers, raw_body: bytes, secret: str) -> bool:
    sig = headers["x-socialboost-signature"]  # "t=..,v1=.."
    ts = headers["x-socialboost-timestamp"]
    v1 = next((p[3:] for p in sig.split(",") if p.startswith("v1=")), None)
    expected = hmac.new(secret.encode(), f"{ts}.{raw_body.decode()}".encode(), hashlib.sha256).hexdigest()
    return v1 is not None and hmac.compare_digest(v1, expected)