Verify webhook signatures
Compute HMAC-SHA256(secret, timestamp + "." + rawBody), compare in constant time, and reject timestamps older than five minutes. During secret rotation the header can carry two comma-separated v1= values; accept either.
Node.js
const crypto = require("crypto");
function verify(secret, rawBody, headers) {
const ts = headers["mailerowl-timestamp"];
if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
const mac = "v1=" + crypto.createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
return headers["mailerowl-signature"].split(",").some(s =>
s.trim().length === mac.length && crypto.timingSafeEqual(Buffer.from(s.trim()), Buffer.from(mac)));
}
Python
import hmac, hashlib, time
def verify(secret: str, raw_body: bytes, headers) -> bool:
ts = headers["MailerOwl-Timestamp"]
if abs(time.time() - int(ts)) > 300:
return False
mac = "v1=" + hmac.new(secret.encode(), ts.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(s.strip(), mac) for s in headers["MailerOwl-Signature"].split(","))
Go
func verify(secret string, body []byte, ts, sig string) bool {
t, _ := strconv.ParseInt(ts, 10, 64)
if math.Abs(float64(time.Now().Unix()-t)) > 300 {
return false
}
m := hmac.New(sha256.New, []byte(secret))
m.Write([]byte(ts + "."))
m.Write(body)
want := "v1=" + hex.EncodeToString(m.Sum(nil))
for _, s := range strings.Split(sig, ",") {
if hmac.Equal([]byte(strings.TrimSpace(s)), []byte(want)) {
return true
}
}
return false
}
PHP
function verify($secret, $rawBody, $ts, $sig) {
if (abs(time() - (int)$ts) > 300) return false;
$mac = 'v1=' . hash_hmac('sha256', $ts . '.' . $rawBody, $secret);
foreach (explode(',', $sig) as $s) if (hash_equals(trim($s), $mac)) return true;
return false;
}