// Verifying a Baatzo status webhook (API v1). Node.js 18 or later, no packages. // // Baatzo sends Baatzo-Signature: t=1801123456,v1=[,v1=] // where each v1 is the HMAC-SHA256 of "." keyed with your signing secret (whsec_...). // During a secret rotation the header carries two v1 values for 24 hours; accept the request if any matches. // Check the RAW body, byte for byte, before parsing it as JSON. const { createHmac, timingSafeEqual } = require('crypto'); const TOLERANCE_SECONDS = 5 * 60; /** * True when the header is a valid Baatzo signature of rawBody under secret, made at most 5 minutes * from now. rawBody is a Buffer or string, exactly as received. */ function verifyBaatzoSignature(rawBody, header, secret, now = Date.now()) { if (typeof header !== 'string' || typeof secret !== 'string') return false; let t = null; const signatures = []; for (const part of header.split(',')) { const i = part.indexOf('='); const k = part.slice(0, i).trim(); const v = part.slice(i + 1).trim(); if (k === 't' && /^\d{1,12}$/.test(v)) t = Number(v); if (k === 'v1' && /^[0-9a-f]{64}$/.test(v)) signatures.push(Buffer.from(v, 'hex')); } if (t === null || !signatures.length) return false; if (Math.abs(Math.floor(now / 1000) - t) > TOLERANCE_SECONDS) return false; const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), 'utf8'); const expected = createHmac('sha256', secret).update(`${t}.`).update(body).digest(); return signatures.some((s) => s.length === expected.length && timingSafeEqual(s, expected)); } module.exports = { verifyBaatzoSignature }; // Express example: keep the raw body for the check. // // app.post('/baatzo-webhook', express.raw({ type: 'application/json' }), (req, res) => { // if (!verifyBaatzoSignature(req.body, req.get('Baatzo-Signature'), process.env.BAATZO_WEBHOOK_SECRET)) { // return res.status(400).end(); // } // const event = JSON.parse(req.body.toString('utf8')); // // Drop a repeat by event.id; ignore a status older than one you already have (event.data.status_rank). // res.status(200).end(); // answer within 5 seconds, then do the work // });