import crypto from "node:crypto"; export function verifyFakturaAPIWebhook({ secret, timestamp, signature, rawBody, now = Date.now() }) { if (typeof timestamp !== "string" || typeof signature !== "string" || typeof secret !== "string" || !/^\d+$/.test(timestamp) || !Buffer.isBuffer(rawBody) || !Number.isFinite(now)) return false; const timestampNumber = Number(timestamp); const ageSeconds = Math.abs(Math.floor(now / 1000) - timestampNumber); if (!Number.isSafeInteger(timestampNumber) || ageSeconds > 300) return false; const digest = crypto .createHmac("sha256", secret) .update(timestamp, "utf8") .update(".", "utf8") .update(rawBody) .digest("hex"); const expected = Buffer.from(`t=${timestamp},v1=${digest}`, "utf8"); const received = Buffer.from(signature ?? "", "utf8"); return expected.length === received.length && crypto.timingSafeEqual(expected, received); }