Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(integration): host-side standard-webhooks ingress signature scheme (#700)
Yudhi Armyndharis7f74aa8a0b8c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d007c036..704c3d74d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0value is deprecated in favor of `response` (kept for SDK v1 additive-only compatibility). Routes with no`response` are byte-identical to today's default fast-ack.+- **`standard-webhooks` ingress signature scheme.** A route may now declare+ `signature.scheme: "standard-webhooks"` to verify [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks)+ payloads host-side (Supabase Auth's Send SMS hook, and any Svix-routed provider). The wire format is+ fixed by the spec, so only `toleranceSec` (default 300s) and `dedupHeader` apply. The operator pastes+ the provider's Svix secret (`v1,whsec_<base64>`) as the instance secret. This surfaces a bad signature+ as a synchronous 401 and — because the `session-alive` preflight runs after verify — makes that preflight+ safe to use (an unauthenticated caller can no longer probe liveness). Additive; existing+ `hmac-sha256`/`shared-secret`/`none` behavior is unchanged.+## [0.8.15] - 2026-07-11- **WhatsApp Web sessions no longer wedge silently in `INITIALIZING` forever.** `engine.initialize()` was awaited with no timeout, and neither whatsapp-web.js nor Puppeteer bounds the initial browser launch/navigation (`page.goto` is called with `timeout: 0` and the web-version-cache fetch carries no timeout). If Chromium stalled under container memory pressure — realistic at the documented 2 GB Standard profile — the await never resolved or rejected: the session sat in `INITIALIZING` indefinitely, `GET /sessions/:id/qr` 400'd forever, and nothing was logged. The #635 abandoned-engine reaper is reactive (terminal `onError` / rejected re-init only), so nothing recovered it. `initializeEngine()` now races `engine.initialize()` against a deadline derived from the configured auth wait (floor 60 s, or `WWEBJS_AUTH_TIMEOUT_MS` + 30 s when an operator has raised that for slow first boots) so a legitimate slow init is never cut short; on timeout it force-kills the wedged browser, marks the session `DISCONNECTED` (retryable, so the existing reconnect backoff picks it up), and rethrows — surfacing the failure to a manual `POST /start` caller instead of hanging. The race's catch is scoped to the timeout only (`EngineInitTimeoutError`): a real init rejection (e.g. Chromium can't launch) propagates untouched so `start()`'s existing `FAILED`+reason diagnostics are preserved — handling both in one catch would downgrade real failures to `DISCONNECTED` and hide their reason. Thanks @INAPA-desarrolloTIC. [#667]diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 85b071e0d..09bce60a7 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -176,6 +176,19 @@ major, and the surface is **additive-only** within a major. The worker-facing AP`ctx.registerWebhook(...)` (claim an inbound route), `ctx.conversations.send(...)` (normalized reply), andper-instance mapping and handover helpers.+The `signature.scheme` field enumerates `hmac-sha256` (HMAC over a `contentTemplate`), `shared-secret`+(constant-time header compare), `standard-webhooks`, and `none` (unauthenticated — see §25.6). The+`standard-webhooks` scheme verifies a [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks)+payload host-side — Supabase Auth's Send-SMS hook and any Svix-routed provider speak it natively. Its wire+format is fixed by the spec (the `webhook-id` / `webhook-timestamp` / `webhook-signature` header triple,+signed over `${id}.${timestamp}.${rawBody}`), so only `toleranceSec` (default 300) and `dedupHeader`+apply; `header`, `contentTemplate`, `encoding`, `prefix`, and `timestampHeader` are ignored, and the+operator pastes the provider's Svix secret (`v1,whsec_<base64>`) as the instance secret. It is the+recommended scheme for Standard-Webhooks providers: because the `session-alive` preflight (§25.4) runs+*after* signature verification, an unauthenticated caller can no longer use that preflight as a liveness+oracle on a route that previously declared `scheme: "none"`. The existing `hmac-sha256`/`shared-secret`/+`none` behavior is unchanged.+Within major 1 the surface grows additively. A route's optional `response` contract — `preflight[]`(host-side checks such as `session-alive`, evaluated after signature verify), `ack{}` (`status`/`body`/`headers`, rendered host-side with `{rawBody}`/`{timestamp}`/`{id}` templates from the verified request),diff --git a/src/core/plugins/plugin-manifest-ingress.spec.ts b/src/core/plugins/plugin-manifest-ingress.spec.tsindex d6df0d85b..a5594d92e 100644--- a/src/core/plugins/plugin-manifest-ingress.spec.ts+++ b/src/core/plugins/plugin-manifest-ingress.spec.ts@@ -138,3 +138,21 @@ describe('validateIngressManifest: response contract', () => {).toThrow(/'bad header'/);});});++describe('validateIngressManifest: standard-webhooks scheme', () => {+ it('loads a standard-webhooks route without header/contentTemplate', () => {+ expect(() =>+ validateIngressManifest(+ manifestWithRoute({ signature: { scheme: 'standard-webhooks', dedupHeader: 'webhook-id' } }),+ ),+ ).not.toThrow();+ });++ it('rejects a standard-webhooks route with a non-positive toleranceSec', () => {+ expect(() =>+ validateIngressManifest(+ manifestWithRoute({ signature: { scheme: 'standard-webhooks', dedupHeader: 'webhook-id', toleranceSec: 0 } }),+ ),+ ).toThrow(/toleranceSec/);+ });+});diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 4bd2a405f..366a286b7 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -179,7 +179,18 @@ export type PluginCapabilityPermission = (typeof PluginCapabilityPermission)[key/** How an inbound webhook's authenticity is established before the plugin sees it. */export interface IngressSignatureSpec {- scheme: 'hmac-sha256' | 'shared-secret' | 'none';+ /**+ * - `hmac-sha256`: HMAC over a `contentTemplate` (tokens `{rawBody}`/`{timestamp}`/`{id}`).+ * - `shared-secret`: constant-time compare of a header value against `instance.secret`.+ * - `standard-webhooks`: host-side [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks)+ * verify. The wire format is fixed by the spec (headers `webhook-id`/`webhook-timestamp`/+ * `webhook-signature`, signed content `${webhook-id}.${webhook-timestamp}.${rawBody}`, base64+ * HMAC-SHA256 with the base64-decoded Svix key, `v1,` prefix, space-separated candidate list), so+ * `header`/`contentTemplate`/`encoding`/`prefix`/`timestampHeader` are IGNORED — only+ * `toleranceSec` (default 300) and `dedupHeader` apply. The operator pastes the Svix secret+ * (`v1,whsec_<base64>`) as `instance.secret`.+ */+ scheme: 'hmac-sha256' | 'shared-secret' | 'standard-webhooks' | 'none';header?: string;// Template over which the HMAC is computed. `{rawBody}` `{timestamp}` `{id}` placeholders.contentTemplate?: string;diff --git a/src/modules/integration/ingress-signature.spec.ts b/src/modules/integration/ingress-signature.spec.tsindex 389f27450..78f6429a1 100644--- a/src/modules/integration/ingress-signature.spec.ts+++ b/src/modules/integration/ingress-signature.spec.ts@@ -150,4 +150,146 @@ describe('verifyIngressSignature', () => {});expect(r2.ok).toBe(false);});++ // --- standard-webhooks (Standard Webhooks spec; ported from supabase-otp-hook/verify.ts) ---+ const swRawKey = Buffer.from('0123456789abcdef0123456789abcdef', 'hex'); // 32 raw bytes+ const swSecret = 'v1,whsec_' + swRawKey.toString('base64');+ const swSign = (id: string, ts: number, body: string) =>+ 'v1,' + createHmac('sha256', swRawKey).update(`${id}.${ts}.${body}`).digest('base64');+ const swSpec = { scheme: 'standard-webhooks' as const };++ it('standard-webhooks: accepts a correctly-signed request', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: swSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(true);+ });++ it('standard-webhooks: rejects a tampered body', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody: rawBody + ' ',+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: swSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ });++ it('standard-webhooks: rejects a wrong key (different secret)', () => {+ const otherKey = Buffer.alloc(32, 1);+ const otherSecret = 'v1,whsec_' + otherKey.toString('base64');+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: otherSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ });++ it('standard-webhooks: rejects a wrong webhook-id', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: {+ 'webhook-id': 'msg_2',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: swSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ });++ it('standard-webhooks: rejects a stale timestamp beyond tolerance (default 300s)', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: swSecret,+ now: (1000 + 301) * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/replay|tolerance/i);+ });++ it('standard-webhooks: honors a declared toleranceSec', () => {+ const r = verifyIngressSignature(+ { scheme: 'standard-webhooks' as const, toleranceSec: 10 },+ {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: swSecret,+ now: (1000 + 11) * 1000,+ instanceId,+ },+ );+ expect(r.ok).toBe(false);+ });++ it('standard-webhooks: accepts a candidate list with a bogus and a valid v1, candidate', () => {+ const good = swSign('msg_1', 1000, rawBody);+ const sigHeader = `v1,deadbeef= v1,${good.slice(3)}`; // bogus candidate first, then the valid one+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: { 'webhook-id': 'msg_1', 'webhook-timestamp': '1000', 'webhook-signature': sigHeader },+ secret: swSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(true);+ });++ it('standard-webhooks: rejects when the secret is prefix-only (decodes to an empty key)', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: {+ 'webhook-id': 'msg_1',+ 'webhook-timestamp': '1000',+ 'webhook-signature': swSign('msg_1', 1000, rawBody),+ },+ secret: 'v1,whsec_',+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ });++ it('standard-webhooks: rejects when a required header is missing', () => {+ const r = verifyIngressSignature(swSpec, {+ rawBody,+ headers: { 'webhook-id': 'msg_1', 'webhook-timestamp': '1000' }, // no webhook-signature+ secret: swSecret,+ now: 1000 * 1000,+ instanceId,+ });+ expect(r.ok).toBe(false);+ });});diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.tsindex 4460651b6..ebbf48636 100644--- a/src/modules/integration/ingress-signature.ts+++ b/src/modules/integration/ingress-signature.ts@@ -17,6 +17,62 @@ function header(headers: Record<string, string>, name?: string): string | undefireturn headers[name.toLowerCase()];}+/**+ * Parse a Standard Webhooks secret to its raw base64 key material: 'v1,whsec_<b64>' → '<b64>',+ * 'whsec_<b64>' → '<b64>', '<b64>' → '<b64>'. Returns undefined when the secret is empty or prefix-only.+ * Ported from supabase-otp-hook/verify.ts (do not diverge). Idiomatic change vs the reference: no try/catch+ * around Buffer.from — Node's base64 decode is lenient and never throws; the key.length===0 guard is the check.+ */+function parseWebhookSecret(secret: string): string | undefined {+ let s = secret.trim();+ if (s.startsWith('v1,')) s = s.slice(3); // secret version tag (may be absent)+ if (s.startsWith('whsec_')) s = s.slice(6); // symmetric-key marker+ return s.length > 0 ? s : undefined;+}++/**+ * Verify a Standard Webhooks signature. The wire format is fixed by the spec, so only `toleranceSec`+ * (default 300) applies — header/contentTemplate/encoding/prefix/timestampHeader are ignored. The+ * signature header may carry multiple space-separated `v1,` candidates (key rotation); any match passes.+ * Pure and total: never throws. Ported from supabase-otp-hook/verify.ts; idiomatic changes: reuse the+ * existing safeEqualStr (identical to the reference's safeEqual) and the lowercasing `header()` helper+ * (the reference lowercases separately — OpenWA already delivers lowercased keys).+ */+function verifyStandardWebhooks(spec: IngressSignatureSpec, input: VerifyInput): { ok: boolean; reason?: string } {+ const keyB64 = parseWebhookSecret(input.secret);+ if (!keyB64) return { ok: false, reason: 'empty standard-webhooks secret' };++ const key = Buffer.from(keyB64, 'base64');+ if (key.length === 0) return { ok: false, reason: 'standard-webhooks secret decodes to empty key' };++ const id = header(input.headers, 'webhook-id');+ const tsRaw = header(input.headers, 'webhook-timestamp');+ const sigHeader = header(input.headers, 'webhook-signature');+ if (!id || !tsRaw || !sigHeader) {+ return { ok: false, reason: 'missing webhook-id/webhook-timestamp/webhook-signature header' };+ }++ const ts = Number.parseInt(tsRaw, 10);+ if (!Number.isFinite(ts)) return { ok: false, reason: 'invalid webhook-timestamp' };++ const tolerance = spec.toleranceSec ?? 300;+ const skewSec = Math.abs(input.now / 1000 - ts);+ if (skewSec > tolerance) return { ok: false, reason: 'replay: timestamp outside tolerance' };++ // Standard Webhooks signs `${webhook-id}.${webhook-timestamp}.${rawBody}` with the base64-decoded key.+ const signed = `${id}.${tsRaw}.${input.rawBody}`;+ const expected = createHmac('sha256', key).update(signed).digest('base64');++ // The signature header is a space-separated list of `version,signature` candidates; accept the first v1 match.+ for (const candidate of sigHeader.split(' ')) {+ const comma = candidate.indexOf(',');+ if (comma < 0) continue;+ if (candidate.slice(0, comma) !== 'v1') continue;+ if (safeEqualStr(candidate.slice(comma + 1), expected)) return { ok: true };+ }+ return { ok: false, reason: 'webhook-signature mismatch' };+}+/*** Inverts the outbound signer (webhook.service.ts:527-531) — but over the provider's declared* contentTemplate applied to the RAW request bytes, and with a constant-time compare. `now` is@@ -29,6 +85,8 @@ export function verifyIngressSignature(if (spec.scheme === 'none') return { ok: true };if (!input.secret) return { ok: false, reason: 'empty ingress secret' };+ if (spec.scheme === 'standard-webhooks') return verifyStandardWebhooks(spec, input);+if (spec.timestampHeader) {const tsRaw = header(input.headers, spec.timestampHeader);const ts = Number.parseInt(tsRaw ?? '', 10);