SPB Git

Repository Public

signature.ts 7.9 KB 189 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : sdk/typescript/src/signature.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/maclustr-identity11 * Project Website  : https://identity.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *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: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Webhook signature verification.44 *45 * Header: `MLID-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>]`46 * Each v1 is HMAC-SHA256(secret, "<t>." + raw body). Several v1 values are sent while a secret is being rotated:47 * the payload is authentic as soon as one of them matches.48 *49 * Works with WebCrypto (browsers, edge runtimes, Deno, Bun, Node >= 19) and falls back to node:crypto (Node 18).50 */51import { SignatureVerificationError } from "./errors";52import type { WebhookEvent } from "./types";5354export const DEFAULT_TOLERANCE_SEC = 300;55export const SIGNATURE_HEADER = "MLID-Signature";5657export type RawBody = string | Uint8Array | ArrayBuffer;5859const encoder = new TextEncoder();6061function toBytes(body: RawBody): Uint8Array {62  if (typeof body === "string") return encoder.encode(body);63  if (body instanceof Uint8Array) return body;64  if (body instanceof ArrayBuffer) return new Uint8Array(body);65  throw new SignatureVerificationError(66    "The webhook payload must be the raw request body (string, Buffer/Uint8Array or ArrayBuffer), not a parsed object.",67    { code: "payload_not_raw" },68  );69}7071function toHex(bytes: Uint8Array): string {72  let out = "";73  for (let i = 0; i < bytes.length; i++) out += (bytes[i] as number).toString(16).padStart(2, "0");74  return out;75}7677/** Constant-time comparison of two strings (time depends on the length of `a` only). */78export function timingSafeEqual(a: string, b: string): boolean {79  const x = encoder.encode(a);80  const y = encoder.encode(b);81  let diff = x.length ^ y.length;82  for (let i = 0; i < x.length; i++) diff |= (x[i] as number) ^ (y[i % (y.length || 1)] ?? 0);83  return diff === 0;84}8586async function hmacSha256Hex(secret: string, message: Uint8Array): Promise<string> {87  const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;88  if (subtle) {89    const key = await subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);90    // Copy into a fresh ArrayBuffer: WebCrypto rejects views over SharedArrayBuffer and some typings reject Uint8Array<ArrayBufferLike>.91    const data = message.buffer.slice(message.byteOffset, message.byteOffset + message.byteLength) as ArrayBuffer;92    return toHex(new Uint8Array(await subtle.sign("HMAC", key, data)));93  }94  // Node 18 without the global WebCrypto object. The specifier is a variable so browser bundlers do not try to resolve it.95  const specifier = "node:crypto";96  const nodeCrypto = (await import(/* @vite-ignore */ /* webpackIgnore: true */ specifier)) as typeof import("node:crypto");97  return nodeCrypto.createHmac("sha256", secret).update(message).digest("hex");98}99100export interface ParsedSignatureHeader {101  timestamp: number;102  signatures: string[];103}104105/** Parses the header; returns null when it is malformed. */106export function parseSignatureHeader(header: string | null | undefined): ParsedSignatureHeader | null {107  if (typeof header !== "string" || !header) return null;108  let timestamp: number | undefined;109  const signatures: string[] = [];110  for (const part of header.split(",")) {111    const i = part.indexOf("=");112    if (i < 0) continue;113    const key = part.slice(0, i).trim();114    const value = part.slice(i + 1).trim();115    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);116    else if (key === "v1" && value) signatures.push(value);117  }118  if (timestamp === undefined || signatures.length === 0) return null;119  return { timestamp, signatures };120}121122/** Computes the `MLID-Signature` header value. Useful to build test fixtures. */123export async function signPayload(payload: RawBody, secret: string, timestamp: number = Math.floor(Date.now() / 1000)): Promise<string> {124  const body = toBytes(payload);125  const prefix = encoder.encode(`${timestamp}.`);126  const message = new Uint8Array(prefix.length + body.length);127  message.set(prefix, 0);128  message.set(body, prefix.length);129  return `t=${timestamp},v1=${await hmacSha256Hex(secret, message)}`;130}131132/**133 * Verifies the signature and throws `SignatureVerificationError` when it is not valid.134 * `toleranceSec` bounds the accepted clock difference in both directions (default 300 s).135 */136export async function verifySignature(137  rawBody: RawBody,138  signatureHeader: string | null | undefined,139  secret: string,140  toleranceSec: number = DEFAULT_TOLERANCE_SEC,141  nowMs: number = Date.now(),142): Promise<void> {143  if (!secret) throw new SignatureVerificationError("No webhook signing secret was provided.", { code: "secret_missing" });144  const parsed = parseSignatureHeader(signatureHeader);145  if (!parsed) {146    throw new SignatureVerificationError(`Missing or malformed ${SIGNATURE_HEADER} header.`, { code: "signature_header_invalid" });147  }148  const body = toBytes(rawBody);149  const expected = (await signPayload(body, secret, parsed.timestamp)).split("v1=")[1] as string;150  // Every candidate is compared, without stopping at the first match.151  let match = false;152  for (const candidate of parsed.signatures) {153    if (timingSafeEqual(expected, candidate)) match = true;154  }155  if (!match) {156    throw new SignatureVerificationError(157      "No signature matches the payload. Check that you pass the raw body and the secret of this endpoint.",158      { code: "signature_mismatch" },159    );160  }161  if (Math.abs(nowMs / 1000 - parsed.timestamp) > toleranceSec) {162    throw new SignatureVerificationError("The signature timestamp is outside the tolerance window.", { code: "signature_expired" });163  }164}165166/**167 * Verifies the signature of a webhook delivery then parses it.168 * Always pass the raw body exactly as received: re-serialized JSON does not verify.169 */170export async function constructEvent(171  rawBody: RawBody,172  signatureHeader: string | null | undefined,173  secret: string,174  toleranceSec: number = DEFAULT_TOLERANCE_SEC,175): Promise<WebhookEvent> {176  await verifySignature(rawBody, signatureHeader, secret, toleranceSec);177  const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(toBytes(rawBody));178  let event: unknown;179  try {180    event = JSON.parse(text);181  } catch (cause) {182    throw new SignatureVerificationError("The webhook payload is not valid JSON.", { code: "payload_invalid", cause });183  }184  if (!event || typeof event !== "object" || (event as { object?: unknown }).object !== "event") {185    throw new SignatureVerificationError("The webhook payload is not an event object.", { code: "payload_invalid" });186  }187  return event as WebhookEvent;188}189
Files main
Menu

Theme