25 lines
784 B
JavaScript
25 lines
784 B
JavaScript
const crypto = require("node:crypto");
|
|
|
|
function normalizeSignature(value) {
|
|
return String(value || "").trim().replace(/^sha256=/i, "");
|
|
}
|
|
|
|
function safeEqual(a, b) {
|
|
const ab = Buffer.from(String(a), "utf8");
|
|
const bb = Buffer.from(String(b), "utf8");
|
|
if (ab.length !== bb.length) return false;
|
|
return crypto.timingSafeEqual(ab, bb);
|
|
}
|
|
|
|
function verifySignature(rawBody, headerSignature, botSecret) {
|
|
const headerSig = normalizeSignature(headerSignature);
|
|
if (!headerSig || !botSecret) return false;
|
|
|
|
const payload = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), "utf8");
|
|
const expected = crypto.createHmac("sha256", botSecret).update(payload).digest("base64");
|
|
|
|
return safeEqual(headerSig, expected);
|
|
}
|
|
|
|
module.exports = { verifySignature };
|