Signature verification
Verify the exact raw-body webhook protocol v2 envelope.
Capture exact Buffer bytes before JSON middleware, enforcing a 256 KiB limit while reading. Reject duplicate signing headers using the raw HTTP header list; normalize names to lowercase only afterwards. Select the secret from your trusted key-ID map using X-Key-Id; reject unknown IDs. The unverified ID is only a lookup hint. Keep old uncompromised secrets for existing delivery snapshots. Synchronize your server clock.
Required headers: X-Webhook-Version, X-Event-Id, X-Delivery-Id, X-Event-Type, X-Key-Id, X-Timestamp, X-Attempt, X-Idempotency-Key, X-Signature-SHA256. The signing namespace remains literally vaultless.webhook. Signing input is JSON.stringify of the ordered array below: version is numeric 2, all other envelope values are strings.
The function assumes your HTTP boundary already rejected duplicate headers, bounded raw bytes, and selected the trusted secret.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyBramaPayWebhook(
rawBody: Buffer,
headers: Record<string, string | undefined>,
secret: string,
) {
const required = (name: string) => {
const value = headers[name.toLowerCase()];
if (!value) throw new Error(`Missing ${name}`);
return value;
};
const version = required("x-webhook-version");
const eventId = required("x-event-id");
const deliveryId = required("x-delivery-id");
const eventType = required("x-event-type");
const timestamp = required("x-timestamp");
const keyId = required("x-key-id");
const attempt = required("x-attempt");
const signature = required("x-signature-sha256");
if (version !== "2" || required("x-idempotency-key") !== eventId)
throw new Error("Invalid webhook envelope");
if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300)
throw new Error("Stale webhook");
if (!/^[0-9a-f]{64}$/.test(signature) || !/^[1-9]\d*$/.test(attempt))
throw new Error("Invalid signature encoding or attempt");
const input = JSON.stringify([
"vaultless.webhook",
2,
eventId,
deliveryId,
eventType,
timestamp,
keyId,
attempt,
rawBody.toString("utf8"),
]);
const expected = Buffer.from(createHmac("sha256", secret).update(input).digest("hex"), "hex");
const actual = Buffer.from(signature, "hex");
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
throw new Error("Invalid webhook signature");
return { eventId, eventType, keyId };
}Only after verification succeeds, parse JSON and validate its schema and signed event type. A valid signature alone does not authorize fulfillment: match the saved session, project, mode, external order, currency and pricing against an authenticated PAID read. Reject Test-to-Live mismatches. A connection test may return 2xx after verification but never fulfills an order. On transient lookup/storage failure return non-2xx so delivery can retry. See deduplication and session reference.