Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : packages/sdk-ts/src/signature.ts9 * Module : sdk-ts10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-1914 *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: support@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 : None specified (no license file in this repository)34 *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 signature — `SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw body)>` (docs/API.md §11.4).44// Implemented with WebCrypto only: works unchanged in Node 20+, browsers, Deno, Bun and edge runtimes.45import { SignatureVerificationError } from "./errors.js"46import type { WebhookEvent } from "./types.js"4748export interface VerifySignatureParams {49 /** The RAW request body, exactly as received (string or bytes) — never a re-serialised JSON. */50 payload: string | Uint8Array | ArrayBuffer51 /** Value of the `SPMail-Signature` header. */52 header: string | null | undefined53 /** The webhook secret (`whsec_…`) shown once at creation or rotation. */54 secret: string55 /** Replay window around the local clock, in seconds (default 300). */56 toleranceSec?: number57 /** Clock override for tests (Unix seconds). */58 now?: number59}6061const encoder = new TextEncoder()62const toBytes = (p: string | Uint8Array | ArrayBuffer): Uint8Array => (typeof p === "string" ? encoder.encode(p) : p instanceof Uint8Array ? p : new Uint8Array(p))63const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("")6465async function hmac(secret: string, timestamp: string, payload: Uint8Array): Promise<Uint8Array> {66 const subtle = globalThis.crypto?.subtle67 if (!subtle) throw new Error("WebCrypto (globalThis.crypto.subtle) is not available in this runtime")68 const key = await subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])69 const prefix = encoder.encode(`${timestamp}.`)70 const data = new Uint8Array(prefix.length + payload.length)71 data.set(prefix, 0)72 data.set(payload, prefix.length)73 return new Uint8Array(await subtle.sign("HMAC", key, data))74}75/** Constant-time comparison of two equal-length byte strings. */76function equal(a: Uint8Array, b: Uint8Array): boolean {77 if (a.length !== b.length) return false78 let diff = 079 for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!80 return diff === 081}8283type Check = { ok: true } | { ok: false; reason: string }84async function check(p: VerifySignatureParams): Promise<Check> {85 const m = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/.exec(p.header ?? "")86 if (!m) return { ok: false, reason: "missing or malformed SPMail-Signature header" }87 if (!p.secret) return { ok: false, reason: "no webhook secret given" }88 const now = p.now ?? Date.now() / 100089 if (Math.abs(now - Number(m[1])) > (p.toleranceSec ?? 300)) return { ok: false, reason: "timestamp outside the tolerance window" }90 const expected = await hmac(p.secret, m[1]!, toBytes(p.payload))91 const given = new Uint8Array(32)92 for (let i = 0; i < 32; i++) given[i] = parseInt(m[2]!.slice(i * 2, i * 2 + 2), 16)93 return equal(expected, given) ? { ok: true } : { ok: false, reason: "signature mismatch" }94}9596/** True when the signature matches the raw payload and its timestamp is inside the tolerance window. Never throws on a bad signature. */97export async function verifyWebhookSignature(params: VerifySignatureParams): Promise<boolean> {98 return (await check(params)).ok99}100101/** Verifies the signature, then parses the payload. Throws SignatureVerificationError when it does not verify. */102export async function constructWebhookEvent(params: VerifySignatureParams): Promise<WebhookEvent> {103 const r = await check(params)104 if (!r.ok) throw new SignatureVerificationError(`Webhook signature verification failed: ${r.reason}`)105 const text = typeof params.payload === "string" ? params.payload : new TextDecoder().decode(toBytes(params.payload))106 try {107 return JSON.parse(text) as WebhookEvent108 } catch {109 throw new SignatureVerificationError("Webhook payload is not valid JSON")110 }111}112113/** Builds a valid `SPMail-Signature` header value (for tests of your own receiver). */114export async function signWebhookPayload(params: { payload: string | Uint8Array | ArrayBuffer; secret: string; timestamp?: number }): Promise<string> {115 const t = String(Math.floor(params.timestamp ?? Date.now() / 1000))116 return `t=${t},v1=${hex(await hmac(params.secret, t, toBytes(params.payload)))}`117}118