// Borrou Partner API: webhook signature verification for Node 20+. v0.1 DRAFT. // // Every delivery carries `Borrou-Signature: t=,v1=`, the MAC of // `.` keyed with the subscription's whole signing secret (`whsec_...`, from // GET /v1/webhooks/subscriptions/{id}/signing-secret). Borrou signs with one secret today, but a // header may carry more than one v1 entry (as it would while a signing secret rotates): accept the // delivery if any one matches. // // Verify the raw bytes exactly as received, before any JSON parsing; reject a timestamp more than // five minutes from your clock; then de-duplicate on the event's `id` (also `Borrou-Event-Id`). import { createHmac, timingSafeEqual } from "node:crypto"; export const SIGNATURE_HEADER = "Borrou-Signature"; export const DEFAULT_TOLERANCE_SECONDS = 300; export type VerifyResult = | { ok: true; timestamp: number } | { ok: false; reason: "missing" | "malformed" | "stale" | "mismatch" }; export function verifyBorrouSignature( header: string | null | undefined, rawBody: Buffer | Uint8Array | string, secret: string, options: { toleranceSeconds?: number; nowSeconds?: number } = {}, ): VerifyResult { if (!header) return { ok: false, reason: "missing" }; let timestamp: number | null = null; const candidates: Buffer[] = []; for (const part of header.split(",")) { const [key, value, ...rest] = part.trim().split("="); if (!key || value === undefined || rest.length > 0) return { ok: false, reason: "malformed" }; if (key === "t") timestamp = /^[0-9]{1,12}$/.test(value) ? Number(value) : null; else if (key === "v1" && /^[0-9a-f]{64}$/.test(value)) candidates.push(Buffer.from(value, "hex")); } if (timestamp === null || candidates.length === 0) return { ok: false, reason: "malformed" }; const now = options.nowSeconds ?? Math.floor(Date.now() / 1000); if (Math.abs(now - timestamp) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return { ok: false, reason: "stale" }; const body = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody; const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest(); // Constant time, and every candidate compared, so the answer's timing says nothing about which. let matched = false; for (const candidate of candidates) matched = timingSafeEqual(candidate, expected) || matched; return matched ? { ok: true, timestamp } : { ok: false, reason: "mismatch" }; } // Express, keeping the body raw for this route: // // app.post("/borrou/webhooks", express.raw({ type: "application/json" }), (req, res) => { // const verified = verifyBorrouSignature(req.get(SIGNATURE_HEADER), req.body, process.env.BORROU_WEBHOOK_SECRET!); // if (!verified.ok) return res.sendStatus(400); // const event = JSON.parse(req.body.toString("utf8")); // // Answer quickly; process asynchronously, de-duplicating on event.id. // res.sendStatus(200); // });