Files
gruperly/apps/backend/src/modules/billing/providers/stripe/webhook-signature.ts
Jose Selesan 9617447e05 feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:01:07 -03:00

42 lines
1.5 KiB
TypeScript

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=<ts>,v1=<hex>[,v1=<hex>…]`).
*
* Stripe signs `<ts>.<raw body>` 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);
});
}