23 lines
650 B
TypeScript
23 lines
650 B
TypeScript
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
|
|
export function verifySupportWebhook(
|
|
raw: string,
|
|
signature: string | null,
|
|
secret: string,
|
|
now = Date.now(),
|
|
) {
|
|
if (!secret || !signature || !/^[a-f0-9]{64}$/i.test(signature)) return false;
|
|
const expected = createHmac("sha256", secret).update(raw).digest();
|
|
if (!timingSafeEqual(expected, Buffer.from(signature, "hex"))) return false;
|
|
try {
|
|
const timestamp = JSON.parse(raw).webhookTimestamp;
|
|
return (
|
|
typeof timestamp === "number" &&
|
|
Number.isFinite(timestamp) &&
|
|
Math.abs(now - timestamp) <= 60_000
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|