import * as hmac from "starship/crypto/hmac";
import * as hex from "starship/encoding/hex";
import * as utf8 from "starship/encoding/utf8";

/** Verify a raw webhook body; use `await verify(secret, body, signature)`. */
export async function verify(
  secret: string,
  body: string,
  signature: string,
  now = Math.floor(Date.now() / 1000),
): Promise<boolean> {
  let match = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(signature);
  if (!match?.[1] || !match[2]) return false;
  let timestamp = Number(match[1]);
  if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > 300)
    return false;
  return hmac
    .SHA256(utf8.parse(secret))
    .verify(utf8.parse(`${match[1]}.${body}`), hex.parse(match[2]).buffer);
}
