Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPIDER — Universal Web Intelligence Engine8 * File : sdk/typescript/src/webhooks.ts9 * Module : Sdk10 * Repository : https://git.spboucher.ai/spider11 * Project Website : Not specified12 * Created : 2026-12-0413 * Last Modified : 2026-12-0414 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : ISC34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Verification of SPIDER webhook deliveries.45 *46 * SPIDER signs every delivery with HMAC-SHA256 over `<X-Spider-Timestamp>.<X-Spider-Delivery>.<raw body>`47 * and sends `X-Spider-Signature: v1=<hex>`. The secret is per tenant: `GET /v1/webhook-secret`.48 */49import { createHmac, timingSafeEqual } from "node:crypto";5051import { WebhookVerificationError } from "./errors.js";5253export type HeaderBag = Headers | Record<string, string | string[] | undefined>;54export type RawBody = string | Uint8Array;5556const bytes = (v: RawBody): Uint8Array => (typeof v === "string" ? new TextEncoder().encode(v) : v);5758/** Hex HMAC-SHA256 of `timestamp.deliveryId.rawBody` (the value after `v1=`). */59export function computeSignature(secret: RawBody, timestamp: string, deliveryId: string, rawBody: RawBody): string {60 return createHmac("sha256", bytes(secret)).update(`${timestamp}.${deliveryId}.`).update(bytes(rawBody)).digest("hex");61}6263function header(headers: HeaderBag, name: string): string {64 if (headers instanceof Headers) return (headers.get(name) ?? "").trim();65 for (const [k, v] of Object.entries(headers)) {66 if (k.toLowerCase() === name) return (Array.isArray(v) ? (v[0] ?? "") : (v ?? "")).trim();67 }68 return "";69}7071export interface VerifyOptions {72 /** Current time in seconds since the epoch (tests). */73 now?: number;74}7576/**77 * Check the signature and the age of a delivery; returns its delivery id, throws78 * `WebhookVerificationError` otherwise. Pass the body exactly as received, not a re-serialised79 * JSON document. The comparison is constant-time. The timestamp check rejects replays older than80 * `toleranceSeconds`; to reject replays inside the window, remember the returned delivery id.81 */82export function verifyWebhook(secret: RawBody, headers: HeaderBag, rawBody: RawBody, toleranceSeconds = 300,83 options: VerifyOptions = {}): string {84 const ts = header(headers, "x-spider-timestamp");85 const delivery = header(headers, "x-spider-delivery");86 const sig = header(headers, "x-spider-signature");87 if (!ts || !delivery || !sig) {88 throw new WebhookVerificationError("missing_header",89 "X-Spider-Timestamp, X-Spider-Delivery and X-Spider-Signature are required");90 }91 if (!/^\d+$/.test(ts)) throw new WebhookVerificationError("bad_timestamp", "X-Spider-Timestamp is not a Unix timestamp");92 const now = options.now ?? Date.now() / 1000;93 if (Math.abs(now - Number(ts)) > toleranceSeconds) {94 throw new WebhookVerificationError("timestamp_out_of_tolerance", "delivery timestamp is outside the tolerance");95 }96 const candidates = sig.split(",").map((p) => p.trim()).filter((p) => p.startsWith("v1=")).map((p) => p.slice(3));97 if (candidates.length === 0) {98 throw new WebhookVerificationError("unsupported_version", "no v1 signature in X-Spider-Signature");99 }100 const expected = Buffer.from(computeSignature(secret, ts, delivery, rawBody), "utf8");101 let ok = false;102 for (const c of candidates) {103 const got = Buffer.from(c.toLowerCase(), "utf8");104 // timingSafeEqual needs equal lengths; a wrong length is compared against the expected value itself105 const same = got.length === expected.length;106 ok = timingSafeEqual(same ? got : expected, expected) && same ? true : ok;107 }108 if (!ok) throw new WebhookVerificationError("bad_signature", "signature does not match");109 return delivery;110}111112/** Verify a delivery, then decode its JSON payload (`event`, `delivery_id`, …). */113export function parseWebhook<T extends Record<string, unknown> = Record<string, unknown>>(114 secret: RawBody, headers: HeaderBag, rawBody: RawBody, toleranceSeconds = 300, options: VerifyOptions = {}): T {115 verifyWebhook(secret, headers, rawBody, toleranceSeconds, options);116 const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody);117 let payload: unknown;118 try {119 payload = JSON.parse(text);120 } catch {121 throw new WebhookVerificationError("bad_payload", "webhook payload is not JSON");122 }123 if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {124 throw new WebhookVerificationError("bad_payload", "webhook payload is not a JSON object");125 }126 return payload as T;127}128