SPB Git

Repository Public

webhooks.test.mjs 7.3 KB 145 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPIDER — Universal Web Intelligence Engine8 * File             : sdk/typescript/test/webhooks.test.mjs9 * Module           : Tests10 * 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// Webhook verification. Expected signatures do not come from the SDK: a constant computed with44// `openssl dgst -sha256 -hmac`, an HMAC built here from SHA-256 alone (RFC 2104), and a live openssl run.45import assert from "node:assert/strict";46import { execFileSync, spawnSync } from "node:child_process";47import { createHash } from "node:crypto";48import { test } from "node:test";4950import { WebhookVerificationError, computeSignature, parseWebhook, verifyWebhook } from "../dist/index.js";5152const SECRET = "whsec_test_4f1c2d3e";53const TS = "1796400000";54const DELIVERY = "5b0c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3";55const BODY = '{"event":"change.detected","change_id":"c-1","kinds":["price"],"delivery_id":"5b0c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3"}';56// printf '%s' '1796400000.5b0c1d2e-….{"event":…}' | openssl dgst -sha256 -hmac whsec_test_4f1c2d3e57const OPENSSL_VECTOR = "8db0216d6310658217c92eca83f0b774e02468c22f8eb5df2893b351e21b4426";58const NOW = { now: Number(TS) };5960function rfc2104(key, msg) {61  let k = Buffer.from(key);62  if (k.length > 64) k = createHash("sha256").update(k).digest();63  k = Buffer.concat([k, Buffer.alloc(64 - k.length)]);64  const inner = createHash("sha256").update(Buffer.from(k.map((b) => b ^ 0x36))).update(msg).digest();65  return createHash("sha256").update(Buffer.from(k.map((b) => b ^ 0x5c))).update(inner).digest("hex");66}6768const headers = (sig, ts = TS, delivery = DELIVERY) => ({69  "X-Spider-Timestamp": ts, "X-Spider-Delivery": delivery, "X-Spider-Signature": `v1=${sig}`, "Content-Type": "application/json",70});71const reason = (fn) => {72  try {73    fn();74  } catch (e) {75    assert.ok(e instanceof WebhookVerificationError, String(e));76    return e.reason;77  }78  return "accepted";79};8081test("the openssl vector is accepted", () => {82  assert.equal(rfc2104(SECRET, `${TS}.${DELIVERY}.${BODY}`), OPENSSL_VECTOR);83  assert.equal(computeSignature(SECRET, TS, DELIVERY, BODY), OPENSSL_VECTOR);84  assert.equal(verifyWebhook(SECRET, headers(OPENSSL_VECTOR), BODY, 300, { now: Number(TS) + 10 }), DELIVERY);85  assert.deepEqual(parseWebhook(SECRET, headers(OPENSSL_VECTOR), BODY, 300, NOW).kinds, ["price"]);86});8788test("a live openssl signature is accepted", (t) => {89  if (spawnSync("openssl", ["version"]).status !== 0) return t.skip("openssl not installed");90  const body = Buffer.from(JSON.stringify({ event: "job.finished", n: 1, accent: "é" }), "utf8");91  const out = execFileSync("openssl", ["dgst", "-sha256", "-hmac", SECRET], { input: Buffer.concat([Buffer.from(`${TS}.d-2.`), body]) });92  const sig = out.toString().trim().split(/\s+/).pop();93  assert.equal(verifyWebhook(SECRET, headers(sig, TS, "d-2"), body, 300, NOW), "d-2");94});9596test("header names are case-insensitive; Headers, arrays and bytes are accepted", () => {97  const lower = Object.fromEntries(Object.entries(headers(OPENSSL_VECTOR)).map(([k, v]) => [k.toLowerCase(), [v]]));98  assert.equal(verifyWebhook(new TextEncoder().encode(SECRET), lower, new TextEncoder().encode(BODY), 300, NOW), DELIVERY);99  assert.equal(verifyWebhook(SECRET, new Headers(headers(OPENSSL_VECTOR.toUpperCase())), BODY, 300, NOW), DELIVERY);100});101102test("tampering is rejected", () => {103  const h = headers(OPENSSL_VECTOR);104  const cases = [105    [h, BODY + " ", "bad_signature"],106    [{ ...h, "X-Spider-Delivery": "other" }, BODY, "bad_signature"],107    [{ ...h, "X-Spider-Timestamp": String(Number(TS) + 1) }, BODY, "bad_signature"],108    [{ ...h, "X-Spider-Signature": "v1=" + "0".repeat(64) }, BODY, "bad_signature"],109    [{ ...h, "X-Spider-Signature": "v1=" + OPENSSL_VECTOR.slice(0, -2) }, BODY, "bad_signature"],110    [{ ...h, "X-Spider-Signature": "v1=é" }, BODY, "bad_signature"],111    [{ ...h, "X-Spider-Signature": "v1=" }, BODY, "bad_signature"],112    [{ ...h, "X-Spider-Signature": OPENSSL_VECTOR }, BODY, "unsupported_version"],113    [{ ...h, "X-Spider-Signature": "v2=" + OPENSSL_VECTOR }, BODY, "unsupported_version"],114    [{ ...h, "X-Spider-Timestamp": "yesterday" }, BODY, "bad_timestamp"],115    [{ ...h, "X-Spider-Timestamp": "-5" }, BODY, "bad_timestamp"],116    [{ ...h, "X-Spider-Delivery": undefined }, BODY, "missing_header"],117    [{ "X-Spider-Timestamp": TS, "X-Spider-Delivery": DELIVERY }, BODY, "missing_header"],118    [{}, BODY, "missing_header"],119  ];120  for (const [hh, body, expected] of cases) assert.equal(reason(() => verifyWebhook(SECRET, hh, body, 300, NOW)), expected);121  assert.equal(reason(() => verifyWebhook(SECRET + "x", h, BODY, 300, NOW)), "bad_signature");122});123124test("the timestamp tolerance protects against replay", () => {125  for (const [skew, tolerance, accepted] of [[0, 300, true], [300, 300, true], [301, 300, false], [-301, 300, false], [-300, 300, true], [30, 10, false], [86400, 300, false]]) {126    const got = reason(() => verifyWebhook(SECRET, headers(OPENSSL_VECTOR), BODY, tolerance, { now: Number(TS) + skew }));127    assert.equal(got, accepted ? "accepted" : "timestamp_out_of_tolerance", `skew ${skew}, tolerance ${tolerance}`);128  }129  // default clock: the wall clock, default tolerance: 300 s (the vector is from the past)130  assert.equal(reason(() => verifyWebhook(SECRET, headers(OPENSSL_VECTOR), BODY)), "timestamp_out_of_tolerance");131  const ts = String(Math.floor(Date.now() / 1000));132  assert.equal(verifyWebhook(SECRET, headers(rfc2104(SECRET, `${ts}.d-3.${BODY}`), ts, "d-3"), BODY), "d-3");133});134135test("several signatures, one valid", () => {136  const h = { ...headers(OPENSSL_VECTOR), "X-Spider-Signature": `v1=${"0".repeat(64)}, v1=${OPENSSL_VECTOR}` };137  assert.equal(verifyWebhook(SECRET, h, BODY, 300, NOW), DELIVERY);138});139140test("parseWebhook refuses a verified body that is not a JSON object", () => {141  for (const body of ["[1]", "not json"]) {142    assert.equal(reason(() => parseWebhook(SECRET, headers(rfc2104(SECRET, `${TS}.${DELIVERY}.${body}`)), body, 300, NOW)), "bad_payload");143  }144});145
Files main
Menu

Theme