import { timingSafeEqual, createHmac } from "node:crypto";
import { parseWebhookSecret } from "./secrets.js";
const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 5 * 60;
function isWebhookTimestampWithinTolerance(timestamp, toleranceSeconds = WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, nowSeconds = Math.floor(Date.now() / 1e3)) {
  const normalizedTimestamp = timestamp.trim();
  if (!/^\d+$/.test(normalizedTimestamp)) {
    return false;
  }
  const timestampNum = Number.parseInt(normalizedTimestamp, 10);
  return Math.abs(nowSeconds - timestampNum) <= toleranceSeconds;
}
function verifyWebhookSignature(msgId, timestamp, body, signatureHeader, secrets, toleranceSeconds = WEBHOOK_SIGNATURE_TOLERANCE_SECONDS) {
  if (!isWebhookTimestampWithinTolerance(timestamp, toleranceSeconds)) {
    return { valid: false };
  }
  const signedContent = `${msgId}.${timestamp}.${body}`;
  const providedSignatures = signatureHeader.split(" ");
  for (let keyIndex = 0; keyIndex < secrets.length; keyIndex++) {
    const key = parseWebhookSecret(secrets[keyIndex]);
    const expectedSig = createHmac("sha256", key).update(signedContent).digest("base64");
    for (const sig of providedSignatures) {
      const parts = sig.split(",");
      if (parts.length !== 2 || parts[0] !== "v1") continue;
      const sigBytes = Buffer.from(parts[1], "base64");
      const expectedBytes = Buffer.from(expectedSig, "base64");
      if (sigBytes.length !== expectedBytes.length) continue;
      if (timingSafeEqual(sigBytes, expectedBytes)) {
        return { valid: true, matchedKeyIndex: keyIndex };
      }
    }
  }
  return { valid: false };
}
export {
  WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
  isWebhookTimestampWithinTolerance,
  verifyWebhookSignature
};
//# sourceMappingURL=verify.js.map
