/** * SendPier webhooks — a receiver that verifies the signature. * * Requirements: Node.js 18 or newer. Built-in node:http and node:crypto, no * packages -- so no Express either; the interesting part is the raw body, and * that is what a framework tends to take away from you. * * Try it out: * export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page * node webhook-receiver.mjs * * In production this listens behind your own https address; we refuse a plain * http address when you enter it. * * USING EXPRESS INSTEAD? Ask for the raw body on this one route: * app.post('/hooks/sendpier', express.raw({ type: 'application/json' }), handler) * and verify over `req.body.toString('utf8')`. A JSON parser hands you an * object, and re-serialising that object shifts a space or a key order -- after * which the signature no longer matches. * * THE ORDER MATTERS * 1. read the RAW body; * 2. verify the signature -- if it does not match: 400, and process nothing; * 3. check whether you already know this id; if so: 200 and stop; * 4. put the event on your own queue; * 5. answer 200; * 6. process it afterwards, outside the request. * * Step 5 before step 6 is the whole point: the timeout is ten seconds, and * every timeout earns you the same event again. */ import { createHmac, timingSafeEqual } from 'node:crypto'; import { createServer } from 'node:http'; /** How far the timestamp may be off, in seconds. */ const TOLERANCE_SECONDS = 300; const PORT = Number.parseInt(process.env.PORT ?? '8080', 10); /** * Is this request really ours? * * The `X-SendPier-Signature` header reads `t=,v1=`. The hex is * HMAC-SHA256 over the literal text ".", keyed with the secret * of that endpoint. Node lowercases header names, hence the lookup below. * * For 24 hours after you renew the secret the header carries TWO signatures: * `t=,v1=,v1=`. * Collect every `v1` and accept the request if any one of them matches. This * is what lets you switch to the new secret at your own pace. */ function signatureIsValid(secret, header, body, tolerance = TOLERANCE_SECONDS) { let timestamp = null; const candidates = []; for (const part of header.split(',')) { const index = part.indexOf('='); if (index === -1) { continue; } const key = part.slice(0, index).trim(); const value = part.slice(index + 1); if (key === 't') { timestamp = value; } else if (key === 'v1') { candidates.push(value); } } if (!timestamp || candidates.length === 0) { return false; } // Without the age check an intercepted request stays replayable for as long // as the secret lives: the signature itself never expires. if (!(Math.abs(Date.now() / 1000 - Number(timestamp)) <= tolerance)) { return false; } const expected = Buffer.from( createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex'), 'utf8' ); // timingSafeEqual throws on a length mismatch, so compare the lengths first. // A plain === would leak, through its own running time, how many leading // characters of a guess were right. Check every value and do not stop at the // first match, so the running time does not tell which signature was right. let valid = false; for (const candidate of candidates) { const given = Buffer.from(candidate, 'utf8'); if (given.length === expected.length && timingSafeEqual(expected, given)) { valid = true; } } return valid; } const secret = process.env.SENDPIER_WEBHOOK_SECRET; if (!secret) { console.error('SENDPIER_WEBHOOK_SECRET is not set'); process.exit(78); } createServer((request, response) => { if (request.method !== 'POST') { response.writeHead(405).end(); return; } // Collect the bytes ourselves: this is the body we signed. const chunks = []; request.on('data', (chunk) => chunks.push(chunk)); request.on('end', () => { const body = Buffer.concat(chunks).toString('utf8'); const header = request.headers['x-sendpier-signature'] ?? ''; if (!signatureIsValid(secret, String(header), body)) { console.error('refused a webhook delivery with an invalid signature'); response.writeHead(400).end(); return; } let event; try { event = JSON.parse(body); } catch { response.writeHead(400).end(); return; } if (!event?.id || !event?.event) { response.writeHead(400).end(); return; } /* | Deduplicate on `id` (the same number as the X-SendPier-Delivery header) | and order on `occurred_at`. We queue every event once, but a delivery | that answers too late gets it again, and a retry from yesterday can | arrive after a fresh event. Process an event you already know silently | and answer 200: | | if (await store.hasEvent(event.id)) { response.writeHead(200).end(); return; } | await store.queue(event); */ response.writeHead(200).end(); // Everything below runs after the answer is on its way. In a real // application this is where you hand the event to your queue worker. console.log(`webhook ${event.id}: ${event.event} for ${event.data?.to ?? event.data?.domain ?? 'unknown'}`); }); }).listen(PORT, () => console.error(`listening for SendPier webhooks on port ${PORT}`));