import { createHmac, timingSafeEqual } from 'node:crypto'; /** Stripe's own default: older deliveries are treated as replays. */ const DEFAULT_TOLERANCE_SECONDS = 5 * 60; /** * Checks Stripe's `Stripe-Signature` header (`t=,v1=[,v1=…]`). * * Stripe signs `.` with the endpoint secret (HMAC-SHA256). There * can be several `v1` while a secret is being rolled; any of them may match. */ export function verifyStripeSignature(params: { signature: string | null; rawBody: string; secret: string; now?: Date; toleranceSeconds?: number; }): boolean { if (!params.signature) return false; let timestamp: string | null = null; const candidates: string[] = []; for (const part of params.signature.split(',')) { const [key, value] = part.split('=', 2).map((piece) => piece.trim()); if (key === 't') timestamp = value ?? null; if (key === 'v1' && value) candidates.push(value); } if (!timestamp || !/^\d+$/.test(timestamp) || candidates.length === 0) return false; const nowSeconds = Math.floor((params.now ?? new Date()).getTime() / 1000); const tolerance = params.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS; if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) return false; const expected = Buffer.from( createHmac('sha256', params.secret).update(`${timestamp}.${params.rawBody}`).digest('hex'), ); return candidates.some((candidate) => { const received = Buffer.from(candidate); return received.length === expected.length && timingSafeEqual(received, expected); }); }