import { createHmac, timingSafeEqual } from 'node:crypto';

/** `sha256=<hex>` signature over the raw body (GitHub/Stripe style). */
export function hmacSign(body: string, secret: string): string {
  return 'sha256=' + createHmac('sha256', secret).update(body).digest('hex');
}

export function hmacVerify(body: string, secret: string, signature: string | undefined): boolean {
  if (!signature) return false;
  const expected = hmacSign(body, secret);
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}
