const crypto = require('crypto');
class WebhookSecurity {
/**
* Computes an HMAC-SHA512 signature.
*/
static computeSignature(payload, secret) {
return crypto
.createHmac('sha512', secret)
.update(payload, 'utf8')
.digest('hex');
}
/**
* Verifies the signature using timing-safe buffer comparison.
*/
static verifySignature(payload, secret, headerSignature) {
if (!payload || !secret || !headerSignature) {
return false;
}
const computedSignature = this.computeSignature(payload, secret);
const computedBuffer = Buffer.from(computedSignature, 'utf8');
const headerBuffer = Buffer.from(headerSignature.toLowerCase(), 'utf8');
if (computedBuffer.length !== headerBuffer.length) {
return false;
}
return crypto.timingSafeEqual(computedBuffer, headerBuffer);
}
}
module.exports = WebhookSecurity;