From 7dfdab2f2c57ebad831474a73820f1efe52e577e Mon Sep 17 00:00:00 2001 From: Georgy Butaev <41178744+g-but@users.noreply.github.com> Date: Wed, 3 Jun 2026 23:27:26 +0200 Subject: [PATCH] feat(webhooks): HMAC-SHA-256 signing util + 25 contract tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The webhook persistence layer in 211188a3 stores secrets but had no way to actually sign payloads. This commit lands the signing util so the next commit (event firing) has something to call. Header format mirrors Stripe so customers can copy familiar patterns: X-OrangeCat-Signature: t=,v1= Signed string is `${timestamp}.${rawRequestBody}` HMAC-SHA-256 with the endpoint's plaintext secret. The timestamp is inside the signed material so an attacker who captures a delivery can't bump it past the receiver's tolerance window (default 300s). Receive-side uses crypto.timingSafeEqual — string === leaks bytewise differences via timing side channels. Multiple v1= values are accepted so future key rotation needs no changes here. 25 tests lock the contract: - signing is deterministic, changes on body/secret/timestamp mutation - verify accepts within tolerance, custom tolerance windows - rejects tampered body / signature / wrong secret with signature_mismatch - rejects beyond-tolerance timestamps in both directions - rejects malformed headers (5 shapes) with named reasons - multi-value v1= accepts when ANY matches (rotation support) - timing-safe comparison never throws on length or non-hex input Suite: 46 suites · 604 tests · 0 failures. tsc clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/services/webhooks/signing.ts | 163 ++++++++++++++++++ tests/unit/services/webhooks/signing.test.ts | 172 +++++++++++++++++++ 2 files changed, 335 insertions(+) create mode 100644 src/services/webhooks/signing.ts create mode 100644 tests/unit/services/webhooks/signing.test.ts diff --git a/src/services/webhooks/signing.ts b/src/services/webhooks/signing.ts new file mode 100644 index 000000000..beb5d409e --- /dev/null +++ b/src/services/webhooks/signing.ts @@ -0,0 +1,163 @@ +/** + * Webhook signing — HMAC-SHA-256, Stripe-style header. + * + * Header format: t=,v1= + * Signed string: `${timestamp}.${rawRequestBody}` + * Algorithm: HMAC-SHA-256 with the endpoint's plaintext secret. + * + * Why the timestamp is part of the signed payload: + * An attacker who captures a delivery cannot replay it forever — + * the receiver enforces a tolerance window (default 5 minutes). + * The timestamp is signed so the attacker can't just bump it. + * + * Why timing-safe equality: + * Plain string `===` leaks bytewise differences via timing side + * channels. `crypto.timingSafeEqual` runs in constant time. + * + * Compatibility: + * The receive-side function is exported for the @orangecat/sdk to + * re-export, so customers can verify with one import. The signing + * side is server-only — we never sign on the client. + * + * Created: 2026-06-03 + */ + +import { createHmac, timingSafeEqual } from 'crypto'; + +const SCHEME = 'v1' as const; +const DEFAULT_TOLERANCE_SECONDS = 300; + +export interface VerifySignatureOpts { + /** Max age of the signed timestamp in seconds. Default 300 (5 minutes). */ + toleranceSeconds?: number; + /** Override "now" for tests. */ + now?: Date; +} + +export type VerifyReason = + | 'malformed_header' + | 'unknown_scheme' + | 'timestamp_outside_tolerance' + | 'signature_mismatch'; + +export type VerifyResult = { valid: true } | { valid: false; reason: VerifyReason }; + +function computeSignature(timestamp: number, rawBody: string, secret: string): string { + return createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex'); +} + +/** + * Sign a delivery payload. Returns the value to put in the + * `X-OrangeCat-Signature` header. + */ +export function signWebhookPayload( + rawBody: string, + secret: string, + now: Date = new Date() +): string { + const timestamp = Math.floor(now.getTime() / 1000); + const signature = computeSignature(timestamp, rawBody, secret); + return `t=${timestamp},${SCHEME}=${signature}`; +} + +/** + * Verify a delivery the integration just received. The raw HTTP body + * string MUST be passed exactly as received — parsing then re-serialising + * the JSON will change byte-for-byte content and the signature will + * fail, which is correct behaviour. + * + * Returns a discriminated union so callers can distinguish the four + * failure reasons for logging / debugging — never branch user-facing + * behaviour on the reason (don't leak the failure mode to attackers). + */ +export function verifyWebhookSignature( + rawBody: string, + secret: string, + signatureHeader: string | null | undefined, + opts: VerifySignatureOpts = {} +): VerifyResult { + if (!signatureHeader || typeof signatureHeader !== 'string') { + return { valid: false, reason: 'malformed_header' }; + } + + const parsed = parseHeader(signatureHeader); + if (!parsed) { + return { valid: false, reason: 'malformed_header' }; + } + if (!parsed.signatures.length) { + return { valid: false, reason: 'unknown_scheme' }; + } + + const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS; + const now = opts.now ?? new Date(); + const nowSeconds = Math.floor(now.getTime() / 1000); + if (Math.abs(nowSeconds - parsed.timestamp) > tolerance) { + return { valid: false, reason: 'timestamp_outside_tolerance' }; + } + + const expected = computeSignature(parsed.timestamp, rawBody, secret); + + // Try each provided v1= signature so receivers can support multi-secret + // key rotation later without touching this code. + for (const candidate of parsed.signatures) { + if (safeHexEqual(candidate, expected)) { + return { valid: true }; + } + } + + return { valid: false, reason: 'signature_mismatch' }; +} + +interface ParsedHeader { + timestamp: number; + signatures: string[]; +} + +function parseHeader(header: string): ParsedHeader | null { + let timestamp: number | null = null; + const signatures: string[] = []; + + for (const segment of header.split(',')) { + const eqIdx = segment.indexOf('='); + if (eqIdx < 1) { + continue; + } + const key = segment.slice(0, eqIdx).trim(); + const value = segment.slice(eqIdx + 1).trim(); + if (!key || !value) { + continue; + } + + if (key === 't') { + const parsedTs = Number.parseInt(value, 10); + if (!Number.isFinite(parsedTs) || parsedTs <= 0) { + return null; + } + timestamp = parsedTs; + } else if (key === SCHEME) { + signatures.push(value); + } + } + + if (timestamp === null) { + return null; + } + return { timestamp, signatures }; +} + +/** Constant-time hex comparison. Returns false if lengths differ. */ +function safeHexEqual(a: string, b: string): boolean { + if (a.length !== b.length) { + return false; + } + try { + const ab = Buffer.from(a, 'hex'); + const bb = Buffer.from(b, 'hex'); + if (ab.length !== bb.length) { + return false; + } + return timingSafeEqual(ab, bb); + } catch { + return false; + } +} diff --git a/tests/unit/services/webhooks/signing.test.ts b/tests/unit/services/webhooks/signing.test.ts new file mode 100644 index 000000000..5bcc0d7cb --- /dev/null +++ b/tests/unit/services/webhooks/signing.test.ts @@ -0,0 +1,172 @@ +/** + * Webhook signing — contract tests. + * + * The signing functions are the foundation customers verify against. + * Any silent regression here ships unverifiable deliveries, which is + * worse than no webhooks — integrations would *think* they're + * authenticating and act on attacker-controlled payloads. + * + * Created: 2026-06-03 + */ + +import { signWebhookPayload, verifyWebhookSignature } from '@/services/webhooks/signing'; + +const SECRET = 'ock_whk_a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6'; +const BODY = JSON.stringify({ event_type: 'product.created', data: { id: 'p-1' } }); + +describe('signWebhookPayload', () => { + it('produces a Stripe-style header with t= and v1=', () => { + const header = signWebhookPayload(BODY, SECRET, new Date(1_700_000_000_000)); + expect(header).toMatch(/^t=1700000000,v1=[a-f0-9]{64}$/); + }); + + it('is deterministic for the same (body, secret, timestamp)', () => { + const now = new Date(1_700_000_000_000); + expect(signWebhookPayload(BODY, SECRET, now)).toBe(signWebhookPayload(BODY, SECRET, now)); + }); + + it('changes when the body changes', () => { + const now = new Date(1_700_000_000_000); + expect(signWebhookPayload(BODY, SECRET, now)).not.toBe( + signWebhookPayload(BODY + ' ', SECRET, now) + ); + }); + + it('changes when the secret changes', () => { + const now = new Date(1_700_000_000_000); + expect(signWebhookPayload(BODY, SECRET, now)).not.toBe( + signWebhookPayload(BODY, SECRET + 'x', now) + ); + }); + + it('changes when the timestamp changes (replay protection)', () => { + const t1 = new Date(1_700_000_000_000); + const t2 = new Date(1_700_000_001_000); + expect(signWebhookPayload(BODY, SECRET, t1)).not.toBe(signWebhookPayload(BODY, SECRET, t2)); + }); +}); + +describe('verifyWebhookSignature', () => { + const NOW = new Date(1_700_000_000_000); + + function freshHeader() { + return signWebhookPayload(BODY, SECRET, NOW); + } + + describe('happy path', () => { + it('accepts a signature produced by signWebhookPayload', () => { + const header = freshHeader(); + expect(verifyWebhookSignature(BODY, SECRET, header, { now: NOW })).toEqual({ valid: true }); + }); + + it('accepts within tolerance window (default 300s)', () => { + const header = signWebhookPayload(BODY, SECRET, NOW); + const later = new Date(NOW.getTime() + 299_000); + expect(verifyWebhookSignature(BODY, SECRET, header, { now: later })).toEqual({ valid: true }); + }); + + it('honours a custom tolerance window', () => { + const header = signWebhookPayload(BODY, SECRET, NOW); + const later = new Date(NOW.getTime() + 600_000); + // 600s elapsed, tolerance 700s → still valid + expect( + verifyWebhookSignature(BODY, SECRET, header, { now: later, toleranceSeconds: 700 }) + ).toEqual({ valid: true }); + }); + }); + + describe('tampering detection', () => { + it('rejects a tampered body', () => { + const header = freshHeader(); + const tampered = BODY.replace('p-1', 'p-2'); + const result = verifyWebhookSignature(tampered, SECRET, header, { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'signature_mismatch' }); + }); + + it('rejects a tampered signature hex digit', () => { + const header = freshHeader(); + // Flip the last hex character + const tampered = header.replace(/.$/, c => (c === '0' ? '1' : '0')); + const result = verifyWebhookSignature(BODY, SECRET, tampered, { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'signature_mismatch' }); + }); + + it('rejects the wrong secret', () => { + const header = freshHeader(); + const result = verifyWebhookSignature(BODY, SECRET + 'x', header, { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'signature_mismatch' }); + }); + }); + + describe('replay protection', () => { + it('rejects a signature older than tolerance', () => { + const header = signWebhookPayload(BODY, SECRET, NOW); + const muchLater = new Date(NOW.getTime() + 301_000); // 1s past default 300s tolerance + const result = verifyWebhookSignature(BODY, SECRET, header, { now: muchLater }); + expect(result).toEqual({ valid: false, reason: 'timestamp_outside_tolerance' }); + }); + + it('rejects a signature from the future beyond tolerance', () => { + const header = signWebhookPayload(BODY, SECRET, new Date(NOW.getTime() + 400_000)); + const result = verifyWebhookSignature(BODY, SECRET, header, { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'timestamp_outside_tolerance' }); + }); + }); + + describe('malformed input', () => { + it.each([null, undefined, '', ' '])('rejects missing/empty header (%p)', value => { + const result = verifyWebhookSignature(BODY, SECRET, value as string | null, { now: NOW }); + expect(result.valid).toBe(false); + }); + + it('rejects header with no timestamp', () => { + const result = verifyWebhookSignature(BODY, SECRET, 'v1=abc', { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'malformed_header' }); + }); + + it('rejects header with no signature (unknown scheme)', () => { + const result = verifyWebhookSignature(BODY, SECRET, 't=1700000000,v9=abc', { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'unknown_scheme' }); + }); + + it('rejects header with non-numeric timestamp', () => { + const result = verifyWebhookSignature(BODY, SECRET, 't=notanumber,v1=abc', { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'malformed_header' }); + }); + + it('rejects header with non-positive timestamp', () => { + const result = verifyWebhookSignature(BODY, SECRET, 't=0,v1=abc', { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'malformed_header' }); + }); + }); + + describe('key rotation', () => { + it('accepts when ANY v1= value matches (multi-value header for rotation)', () => { + const real = freshHeader(); + const realSig = real.split(',v1=')[1]; + const withFake = `t=1700000000,v1=deadbeef${'0'.repeat(56)},v1=${realSig}`; + expect(verifyWebhookSignature(BODY, SECRET, withFake, { now: NOW })).toEqual({ valid: true }); + }); + + it('rejects when all v1= values fail', () => { + const withFakes = `t=1700000000,v1=deadbeef${'0'.repeat(56)},v1=cafebabe${'0'.repeat(56)}`; + const result = verifyWebhookSignature(BODY, SECRET, withFakes, { now: NOW }); + expect(result).toEqual({ valid: false, reason: 'signature_mismatch' }); + }); + }); + + describe('timing-safe comparison', () => { + it('rejects shorter signatures without throwing on Buffer length mismatch', () => { + const result = verifyWebhookSignature(BODY, SECRET, 't=1700000000,v1=abc', { now: NOW }); + expect(result.valid).toBe(false); + }); + + it('rejects non-hex signatures without throwing', () => { + const nonHex = 'g'.repeat(64); + const result = verifyWebhookSignature(BODY, SECRET, `t=1700000000,v1=${nonHex}`, { + now: NOW, + }); + expect(result.valid).toBe(false); + }); + }); +});