feat(sdk): export verifyWebhookSignature in @orangecat/sdk@0.3.0

7dfdab2f shipped the server-side signing util but the receive side
lived only in src/services/. Customers consuming @orangecat/sdk could
not verify deliveries without hand-porting the algorithm — which is
exactly the kind of "every customer rolls their own crypto" footgun
the SDK exists to avoid.

This commit ports the verify-only path to packages/sdk/src/webhooks.ts
(no signing — server-only), re-exports it from index.ts, and bumps
0.2.0 → 0.3.0 (minor: additive). Build emits dist/webhooks.{js,d.ts}
alongside the existing client surface; npm install + one import is
now enough to verify any X-OrangeCat-Signature header.

Implementation notes preserved from the server-side util:
  - timing-safe hex comparison (no `===` on signatures)
  - tolerance window default 300s
  - multi-value v1= accepted (future key rotation needs no code change)
  - parsed reasons (malformed_header / unknown_scheme /
    timestamp_outside_tolerance / signature_mismatch) for logs only,
    never branch user-facing behaviour on them

The SDK and server-side functions diverged ONLY at the API surface
(SDK accepts Node 18 http header arrays, collapses to first element).
The hashing rules are byte-for-byte identical so they verify each
other's outputs.

App suite still: 46 suites · 604 tests · 0 failures.
SDK tsc + build clean (dist/webhooks.js + .d.ts emitted, index re-export verified).

Next: FleetCrown vendor tarball repack at vendor/orangecat-sdk-0.3.0.tgz
(separate FleetCrown-side commit; OrangeCat does not vendor its own SDK).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-03 23:33:49 +02:00
1 parent 7dfdab2f2c
commit 6cc7e4ba3f
3 files changed
+150 -1

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@orangecat/sdk",
"version": "0.2.0",
"version": "0.3.0",
"description": "Official TypeScript SDK for the OrangeCat platform API (v1).",
"license": "UNLICENSED",
"private": false,
+6
View File
@@ -10,6 +10,12 @@ export type { ListParams } from './client.js';
export { OrangeCatError } from './errors.js';
export type { OrangeCatErrorCode } from './errors.js';
export type { ClientOptions, RequestOptions } from './http.js';
export { verifyWebhookSignature } from './webhooks.js';
export type {
VerifyWebhookSignatureOpts,
WebhookVerifyReason,
WebhookVerifyResult,
} from './webhooks.js';
export type {
BaseEntityResponse,
CreateOptions,
+143
View File
@@ -0,0 +1,143 @@
/**
* Verify a signed webhook delivery from OrangeCat.
*
* Header format (X-OrangeCat-Signature):
* t=<unix_seconds>,v1=<hex_signature>
*
* Algorithm: HMAC-SHA-256 over `${timestamp}.${rawRequestBody}` keyed by
* the endpoint's signing secret. The timestamp is inside the signed
* material so a captured delivery can't be replayed past the tolerance
* window.
*
* Usage (Node 18+):
*
* import { verifyWebhookSignature } from '@orangecat/sdk';
*
* app.post('/webhooks/orangecat', (req, res) => {
* // IMPORTANT: pass the raw HTTP body string, not the parsed JSON.
* // Parsing + re-serialising changes byte-for-byte content and the
* // signature will (correctly) fail.
* const result = verifyWebhookSignature(
* req.rawBody,
* process.env.WEBHOOK_SECRET,
* req.headers['x-orangecat-signature']
* );
* if (!result.valid) return res.status(401).end();
* // ... handle delivery
* });
*
* Never branch user-facing behaviour on `result.reason` — it's for
* logging and debugging only.
*/
import { createHmac, timingSafeEqual } from 'node:crypto';
const SCHEME = 'v1' as const;
const DEFAULT_TOLERANCE_SECONDS = 300;
export interface VerifyWebhookSignatureOpts {
/** Max age of the signed timestamp in seconds. Default 300 (5 minutes). */
toleranceSeconds?: number;
/** Override "now" for tests. */
now?: Date;
}
export type WebhookVerifyReason =
| 'malformed_header'
| 'unknown_scheme'
| 'timestamp_outside_tolerance'
| 'signature_mismatch';
export type WebhookVerifyResult = { valid: true } | { valid: false; reason: WebhookVerifyReason };
export function verifyWebhookSignature(
rawBody: string,
secret: string,
signatureHeader: string | string[] | null | undefined,
opts: VerifyWebhookSignatureOpts = {}
): WebhookVerifyResult {
// Node 18 http headers may surface as string[] when repeated — collapse.
const header = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
if (!header || typeof header !== 'string') {
return { valid: false, reason: 'malformed_header' };
}
const parsed = parseHeader(header);
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 = createHmac('sha256', secret)
.update(`${parsed.timestamp}.${rawBody}`)
.digest('hex');
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 };
}
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;
}
}