import {createHmac, timingSafeEqual} from 'node:crypto'; function headerValue(headers, name) { if (headers instanceof Headers) return headers.get(name); const value = headers?.[name]; return typeof value === 'string' ? value : null; } function decodeDigest(encoded) { if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(encoded)) return null; const decoded = Buffer.from(encoded, 'base64'); return decoded.length === 32 && decoded.toString('base64') === encoded ? decoded : null; } /** * Verify the request bytes before JSON parsing. * Supply the current signing secret and any previous secrets still in overlap. * * After verification, atomically persist the destination/account and webhook-id * in a durable inbox with a uniqueness constraint before acknowledging HTTP 2xx. * A repeated ID can be acknowledged after confirming that prior durable commit. * The ACK confirms receipt. Track business processing and downstream effects * separately, with their own idempotency and outcome reconciliation. * This function performs verification only and never logs request data or keys. */ export function verifyWebhook({ body, headers, secrets, now = Date.now(), toleranceSeconds = 300 } = {}) { if (!Buffer.isBuffer(body) || !Number.isFinite(now) || now < 0 || !Number.isFinite(toleranceSeconds) || toleranceSeconds < 0 || !Array.isArray(secrets) || secrets.length < 1 || secrets.length > 8) return false; const id = headerValue(headers, 'webhook-id'); const timestamp = headerValue(headers, 'webhook-timestamp'); const signature = headerValue(headers, 'webhook-signature'); if (!id || id.length > 128 || /[^\x21-\x7e]/.test(id) || !timestamp || !/^[1-9][0-9]{0,15}$/.test(timestamp) || !signature || signature.length > 512 || /[\r\n\t]/.test(signature)) return false; const timestampSeconds = Number(timestamp); if (!Number.isSafeInteger(timestampSeconds) || Math.abs(now / 1000 - timestampSeconds) > toleranceSeconds) return false; const keys = []; for (const secret of secrets) { if (typeof secret !== 'string' || !secret.startsWith('whsec_')) return false; const key = decodeDigest(secret.slice(6)); if (!key) return false; keys.push(key); } const tokens = signature.trim().split(' '); if (tokens.length < 1 || tokens.length > 8) return false; const candidates = []; for (const token of tokens) { const match = /^v([1-9][0-9]*),([^,]+)$/.exec(token); if (!match) return false; if (match[1] !== '1') continue; const candidate = decodeDigest(match[2]); if (!candidate) return false; candidates.push(candidate); } if (candidates.length === 0) return false; for (const key of keys) { const expected = createHmac('sha256', key) .update(id + '.' + timestamp + '.') .update(body) .digest(); if (candidates.some(candidate => timingSafeEqual(candidate, expected))) return true; } return false; }