Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): add webhook signature verification helpers
Yudhi Armyndhariseb53990fcc13
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 61e38738c..f660a6aa9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -7116,7 +7116,7 @@ function verify(rawBody, header, secret) {}```-Complete Express and FastAPI receivers are in [`examples/webhook-signature-verification.md`](examples/webhook-signature-verification.md).+Complete Express and FastAPI receivers are in [`examples/webhook-signature-verification.md`](examples/webhook-signature-verification.md). From the next SDK release (after 0.5.0), the SDKs ship this check: `verifyWebhookSignature` (JavaScript), `verify_webhook_signature` (Python), `VerifyWebhookSignature` (Go), `WebhookSignature.verify` (Java) and `WebhookSignature::verify` (PHP).If no `secret` is configured the `X-OpenWA-Signature` header is omitted entirely.diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 327b60d7f..b686ae37a 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -17,7 +17,7 @@ OpenWA ships five official, hand-written client libraries for the REST API. They### Design Principles- **One client, fluent resources.** A single client object (`OpenWAClient` / `OpenWA\Client`) exposes every resource as a property — `client.messages.sendText(...)`, `client.sessions.start(...)`. All five SDKs expose the **same** resource surface; only the language idioms differ (camelCase methods + objects in JS/PHP/Java, snake_case methods + dicts in Python, exported fields + structs in Go).-- **It is a request/response client, not an event SDK.** There is no WebSocket, EventEmitter, or `client.on(...)`. To receive inbound messages and acks, register a webhook (the `webhooks` resource) and host your own receiver, or connect to the real-time Socket.IO API directly (see [API Specification §6.5](./06-api-specification.md)).+- **It is a request/response client, not an event SDK.** There is no WebSocket, EventEmitter, or `client.on(...)`. To receive inbound messages and acks, register a webhook (the `webhooks` resource) and host your own receiver, checking `X-OpenWA-Signature` with the SDK helper (`verifyWebhookSignature` in JavaScript, `verify_webhook_signature` in Python, `VerifyWebhookSignature` in Go, `WebhookSignature.verify` in Java, `WebhookSignature::verify` in PHP), or connect to the real-time Socket.IO API directly (see [API Specification §6.5](./06-api-specification.md)).- **Typed errors.** Non-2xx responses raise/throw a typed error mapped from the HTTP status (`401/403/404/409/429/501/503`), plus a timeout error — all `instanceof`/`catch`-checkable. See each language's Error Handling subsection.- **Injectable transport.** The HTTP layer is replaceable (`fetch` in JS, an `httpx` transport in Python, a Guzzle client in PHP) — the extension point for retry/observability middleware and for testing without the network.- **Safe by default.** Redirects are never followed (so the API key is never re-sent to a redirect target), the auth/JSON headers always take precedence over caller-supplied defaults, path segments are percent-encoded, a base-URL path prefix (e.g. behind a reverse proxy at `/v1`) is preserved, and there is a default 30s per-request timeout. **No automatic retries by default** — in JS, Python, PHP, and Java wrap calls in your own backoff if you need them (especially for `429`); the Go SDK additionally ships an opt-in `WithRetry(RetryPolicy)` that never replays a `POST` or `PATCH` after a network error and limits their retries to `429`/`503`.@@ -45,13 +45,13 @@ All five SDKs expose the same fluent surface:| `media` | conversionStatus, convertVoice, convertVideo _(OPERATOR)_ || `health` | check, live, ready |-The tables describe `main`. The 0.5.0 registry builds do not include `sessions.getProxy`, `sessions.updateProxy` or `messages.clickButton` (`get_proxy`, `update_proxy` and `click_button` in Python; `GetProxy`, `UpdateProxy` and `ClickButton` in Go); they ship with the next SDK release. Nor is the Java fallback to `UNKNOWN`: 0.5.0 decodes a response enum value it does not recognise to `null` (`MessageType` and `ChatKind` included), and `SessionStatus`, `DeliveryStatus` and the other response enums that lack an `unknown` wire value have no `UNKNOWN` constant there.+The tables describe `main`. The 0.5.0 registry builds do not include `sessions.getProxy`, `sessions.updateProxy` or `messages.clickButton` (`get_proxy`, `update_proxy` and `click_button` in Python; `GetProxy`, `UpdateProxy` and `ClickButton` in Go); they ship with the next SDK release. The webhook signature helpers (`verifyWebhookSignature`, `verify_webhook_signature`, `VerifyWebhookSignature`, `WebhookSignature.verify`, `WebhookSignature::verify`), the `WebhookDelivery` types and the API error code, retry-delay and headers accessors are not in 0.5.0 either; they also ship with the next SDK release. Nor is the Java fallback to `UNKNOWN`: 0.5.0 decodes a response enum value it does not recognise to `null` (`MessageType` and `ChatKind` included), and `SessionStatus`, `DeliveryStatus` and the other response enums that lack an `unknown` wire value have no `UNKNOWN` constant there.> The SDKs cover the user-facing resources above and stop there. The administrative and operational surfaces are deliberately left out — `auth/api-keys`, `audit`, `settings`, `stats`, `automation`, `infra`, `plugins` and the `integration` management routes are predominantly `ADMIN`-gated; `metrics` is a `@Public()` Prometheus scrape gated by `METRICS_TOKEN` rather than by role; `mcp` is a Streamable-HTTP transport mounted straight onto the Express adapter; and `ingress` is the `@Public()` receiver that integration providers post into. `docker` has no HTTP surface at all — it is an internal service module. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.## 18.2 TypeScript / JavaScript SDK-The official JavaScript/TypeScript SDK is published as **`@rmyndharis/openwa`**. It is a pure promise-based HTTP client: a single `OpenWAClient` exposes every API resource as a typed property. There is no event model — the SDK does not open WebSockets, emit events, or expose `client.on(...)`. To receive inbound messages and acks, configure a webhook (see the `webhooks` resource) and host your own HTTP receiver.+The official JavaScript/TypeScript SDK is published as **`@rmyndharis/openwa`**. It is a pure promise-based HTTP client: a single `OpenWAClient` exposes every API resource as a typed property. There is no event model — the SDK does not open WebSockets, emit events, or expose `client.on(...)`. To receive inbound messages and acks, configure a webhook (see the `webhooks` resource) and host your own HTTP receiver, checking each delivery with `await verifyWebhookSignature(rawBody, signature, secret)` and typing its parsed body as `WebhookDelivery`.The package ships **dual CJS + ESM** with bundled `.d.ts` types, so it is consumable from both `require()` and `import`.diff --git a/docs/examples/webhook-signature-verification.md b/docs/examples/webhook-signature-verification.mdindex 2212e0b30..4f66660bd 100644--- a/docs/examples/webhook-signature-verification.md+++ b/docs/examples/webhook-signature-verification.md@@ -22,6 +22,20 @@ sha256=<hex digest>The digest is computed over the exact raw request body bytes using the webhook secret.+## With an OpenWA SDK++From the next SDK release (after 0.5.0), each SDK ships this check. Pass the raw body, the `X-OpenWA-Signature` header value and the secret; the helper returns false for a missing, malformed or wrong signature and compares in constant time.++| SDK | Call |+| ---------- | ------------------------------------------------------- |+| JavaScript | `await verifyWebhookSignature(rawBody, header, secret)` |+| Python | `verify_webhook_signature(raw_body, header, secret)` |+| Go | `openwa.VerifyWebhookSignature(body, header, secret)` |+| Java | `WebhookSignature.verify(body, header, secret)` |+| PHP | `WebhookSignature::verify($rawBody, $header, $secret)` |++The raw-body rule below still applies: parse the JSON only after the check passes. The receivers below show the same check without an SDK.+## Node.js / ExpressUse `express.raw()` for the webhook route so the signature is checked against the raw body. Parse JSON only after verification succeeds.diff --git a/sdk/README.md b/sdk/README.mdindex ae745c54d..b23600824 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -45,6 +45,11 @@ The table describes `main`. The 0.5.0 registry builds do not include`sessions.getProxy`, `sessions.updateProxy` or `messages.clickButton`(`get_proxy`, `update_proxy` and `click_button` in Python; `GetProxy`,`UpdateProxy` and `ClickButton` in Go); they ship with the next SDK release.+The webhook signature helpers (`verifyWebhookSignature`,+`verify_webhook_signature`, `VerifyWebhookSignature`, `WebhookSignature.verify`,+`WebhookSignature::verify`), the `WebhookDelivery` types and the API error code,+retry-delay and headers accessors are not in 0.5.0 either; they also ship with+the next SDK release.Nor is the Java fallback to `UNKNOWN`: 0.5.0 decodes a response enum value itdoes not recognise to `null` (`MessageType` and `ChatKind` included), and`SessionStatus`, `DeliveryStatus` and the other response enums that lack an@@ -254,6 +259,12 @@ testing, retry, tracing, or metrics. See [`go/README.md`](go/README.md).retries a send-pacing `429` (`code: "SEND_PACING_LIMITED"`), honors`Retry-After`, and rewinds request bodies —still off unless you ask for it.+- **Webhook signatures.** Every SDK verifies a delivery's `X-OpenWA-Signature`+ against the raw request body: `verifyWebhookSignature` (JavaScript),+ `verify_webhook_signature` (Python), `VerifyWebhookSignature` (Go),+ `WebhookSignature.verify` (Java) and `WebhookSignature::verify` (PHP). The+ JavaScript, Python, Go and Java SDKs also type the delivery body as+ `WebhookDelivery`.- **Redirects are never followed.** A `3xx` surfaces to the caller rather thanbeing followed, so the API key is never re-sent to a redirect target.- **Default per-request timeout** is 30s (configurable). Path segments (chat /diff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.goindex e627e1ecb..ced4070ad 100644--- a/sdk/go/types_webhook.go+++ b/sdk/go/types_webhook.go@@ -186,3 +186,15 @@ type WebhookDeliveryFailure struct {// CreatedAt is the ISO timestamp of when the delivery was finally abandoned.CreatedAt string `json:"createdAt"`}++// WebhookDelivery is the JSON body of a webhook delivery (docs/06 section+// 6.6). Event is "test" for a delivery sent by the test endpoint. Check the+// raw body with VerifyWebhookSignature before decoding it.+type WebhookDelivery struct {+ Event WebhookEvent `json:"event"`+ Timestamp string `json:"timestamp"`+ SessionID string `json:"sessionId"`+ IdempotencyKey string `json:"idempotencyKey"`+ DeliveryID string `json:"deliveryId"`+ Data json.RawMessage `json:"data"`+}diff --git a/sdk/go/webhook_signature.go b/sdk/go/webhook_signature.gonew file mode 100644index 000000000..52f74826d--- /dev/null+++ b/sdk/go/webhook_signature.go@@ -0,0 +1,27 @@+package openwa++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "strings"+)++// VerifyWebhookSignature checks a delivery's X-OpenWA-Signature header+// ("sha256=<hex HMAC-SHA256>") against the webhook secret. Pass the raw request+// body exactly as received; a re-serialized decode can differ byte for byte and+// will not verify. It returns false for a missing, malformed or non-matching+// signature and for an empty secret.+func VerifyWebhookSignature(body []byte, signature, secret string) bool {+ given, ok := strings.CutPrefix(signature, "sha256=")+ if !ok || len(given) != sha256.Size*2 || secret == "" {+ return false+ }+ want, err := hex.DecodeString(given)+ if err != nil {+ return false+ }+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write(body)+ return hmac.Equal(mac.Sum(nil), want)+}diff --git a/sdk/go/webhook_signature_test.go b/sdk/go/webhook_signature_test.gonew file mode 100644index 000000000..fd2150613--- /dev/null+++ b/sdk/go/webhook_signature_test.go@@ -0,0 +1,53 @@+package openwa++import (+ "encoding/json"+ "strings"+ "testing"+)++// Shared across the SDK suites; the gateway's generateSignature produces this+// header for this body.+const (+ webhookSecret = "test-secret-0123456789"+ webhookBody = `{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1","idempotencyKey":"k",` ++ `"deliveryId":"dlv_1","data":{"text":"h` + "éllo \U0001F44B" + `"}}`+ webhookHex = "d74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70"+)++func TestVerifyWebhookSignature(t *testing.T) {+ sig := "sha256=" + webhookHex+ if !VerifyWebhookSignature([]byte(webhookBody), sig, webhookSecret) {+ t.Fatal("valid signature rejected")+ }+ if !VerifyWebhookSignature([]byte(webhookBody), "sha256="+strings.ToUpper(webhookHex), webhookSecret) {+ t.Fatal("uppercase hex rejected")+ }++ tampered := []byte(webhookBody)+ tampered[10] ^= 1+ if VerifyWebhookSignature(tampered, sig, webhookSecret) {+ t.Fatal("changed body accepted")+ }+ if VerifyWebhookSignature([]byte(webhookBody), sig, "another-secret-012345") {+ t.Fatal("wrong secret accepted")+ }+ if VerifyWebhookSignature([]byte(webhookBody), sig, "") {+ t.Fatal("empty secret accepted")+ }+ for _, h := range []string{webhookHex, "SHA256=" + webhookHex, "sha256=" + webhookHex[1:], "sha256=" + webhookHex[1:] + "z", ""} {+ if VerifyWebhookSignature([]byte(webhookBody), h, webhookSecret) {+ t.Fatalf("malformed header %q accepted", h)+ }+ }+}++func TestWebhookDeliveryDecodesTestEvent(t *testing.T) {+ var d WebhookDelivery+ if err := json.Unmarshal([]byte(`{"event":"test","sessionId":"s1","deliveryId":"dlv_1","data":{"a":1}}`), &d); err != nil {+ t.Fatal(err)+ }+ if d.Event != "test" || d.SessionID != "s1" || d.DeliveryID != "dlv_1" || string(d.Data) != `{"a":1}` {+ t.Fatalf("decoded %+v", d)+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/WebhookSignature.java b/sdk/java/src/main/java/com/rmyndharis/openwa/WebhookSignature.javanew file mode 100644index 000000000..0ef0fa740--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/WebhookSignature.java@@ -0,0 +1,44 @@+package com.rmyndharis.openwa;++import java.nio.charset.StandardCharsets;+import java.security.GeneralSecurityException;+import java.security.MessageDigest;+import java.util.HexFormat;+import java.util.regex.Pattern;+import javax.crypto.Mac;+import javax.crypto.spec.SecretKeySpec;++/** Checks the {@code X-OpenWA-Signature} header of a webhook delivery. */+public final class WebhookSignature {+ private static final Pattern SIGNATURE = Pattern.compile("sha256=([0-9a-fA-F]{64})");++ private WebhookSignature() {}++ /**+ * Check a delivery's {@code X-OpenWA-Signature} header ({@code sha256=<hex HMAC-SHA256>}) against+ * the webhook secret. Pass the raw request body exactly as received; a re-serialized parse can+ * differ byte for byte and will not verify. Returns {@code false} (never throws) for a missing,+ * malformed or non-matching signature and for an empty secret.+ */+ public static boolean verify(byte[] body, String signature, String secret) {+ if (body == null || signature == null || secret == null || secret.isEmpty()) {+ return false;+ }+ var match = SIGNATURE.matcher(signature);+ if (!match.matches()) {+ return false;+ }+ try {+ Mac mac = Mac.getInstance("HmacSHA256");+ mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));+ return MessageDigest.isEqual(mac.doFinal(body), HexFormat.of().parseHex(match.group(1)));+ } catch (GeneralSecurityException e) {+ return false;+ }+ }++ /** As {@link #verify(byte[], String, String)}, for a body already read as a UTF-8 string. */+ public static boolean verify(String body, String signature, String secret) {+ return body != null && verify(body.getBytes(StandardCharsets.UTF_8), signature, secret);+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookDelivery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookDelivery.javanew file mode 100644index 000000000..a9b9b3fa7--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookDelivery.java@@ -0,0 +1,18 @@+package com.rmyndharis.openwa.model;++import com.google.gson.JsonObject;++/**+ * The JSON body of a webhook delivery (docs/06 section 6.6). {@code event} is a string rather than+ * {@link WebhookEvent} because a delivery from the test endpoint carries {@code "test"}. Check the+ * raw body with {@link com.rmyndharis.openwa.WebhookSignature#verify(byte[], String, String)}+ * before decoding it.+ */+public record WebhookDelivery(+ String event,+ String timestamp,+ String sessionId,+ String idempotencyKey,+ String deliveryId,+ /** The event-specific payload. */+ JsonObject data) {}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/WebhookSignatureTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/WebhookSignatureTest.javanew file mode 100644index 000000000..6f736c79d--- /dev/null+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/WebhookSignatureTest.java@@ -0,0 +1,50 @@+package com.rmyndharis.openwa;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.google.gson.Gson;+import com.rmyndharis.openwa.model.WebhookDelivery;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;+import org.junit.jupiter.api.Test;++class WebhookSignatureTest {+ // Shared across the SDK suites; the gateway's generateSignature produces this header for this body.+ private static final String SECRET = "test-secret-0123456789";+ private static final String BODY =+ "{\"event\":\"message.received\",\"timestamp\":\"2026-02-02T10:00:00.000Z\",\"sessionId\":\"s1\","+ + "\"idempotencyKey\":\"k\",\"deliveryId\":\"dlv_1\",\"data\":{\"text\":\"héllo 👋\"}}";+ private static final String HEX = "d74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70";+ private static final String SIGNATURE = "sha256=" + HEX;++ @Test+ void acceptsTheGatewaySignatureOverTextOrBytes() {+ assertTrue(WebhookSignature.verify(BODY, SIGNATURE, SECRET));+ assertTrue(WebhookSignature.verify(BODY.getBytes(StandardCharsets.UTF_8), SIGNATURE, SECRET));+ assertTrue(WebhookSignature.verify(BODY, "sha256=" + HEX.toUpperCase(), SECRET));+ }++ @Test+ void rejectsAChangedBodyAWrongSecretAndAMalformedHeader() {+ byte[] tampered = BODY.getBytes(StandardCharsets.UTF_8);+ tampered[10] ^= 1;+ assertFalse(WebhookSignature.verify(tampered, SIGNATURE, SECRET));+ assertFalse(WebhookSignature.verify(BODY, SIGNATURE, "another-secret-012345"));+ assertFalse(WebhookSignature.verify(BODY, SIGNATURE, ""));+ for (String header : Arrays.asList(+ HEX, "SHA256=" + HEX, "sha256=" + HEX.substring(1), "sha256=" + HEX.substring(1) + "z", "", null)) {+ assertFalse(WebhookSignature.verify(BODY, header, SECRET), "accepted " + header);+ }+ }++ @Test+ void deliveryDecodesTheTestEvent() {+ WebhookDelivery d = new Gson().fromJson(+ "{\"event\":\"test\",\"sessionId\":\"s1\",\"deliveryId\":\"dlv_1\",\"data\":{\"a\":1}}", WebhookDelivery.class);+ assertEquals("test", d.event());+ assertEquals("s1", d.sessionId());+ assertEquals(1, d.data().get("a").getAsInt());+ }+}diff --git a/sdk/javascript/scripts/smoke.mjs b/sdk/javascript/scripts/smoke.mjsindex 679936bc1..8026fdca8 100644--- a/sdk/javascript/scripts/smoke.mjs+++ b/sdk/javascript/scripts/smoke.mjs@@ -5,6 +5,7 @@* so this guards `npm publish` against shipping an unconsumable package.* Run after `npm run build`.*/+import { createHmac } from 'node:crypto';import { createRequire } from 'node:module';const require = createRequire(import.meta.url);@@ -14,6 +15,20 @@ if (typeof cjs.OpenWAClient !== 'function') throw new Error('CJS: OpenWAClient mconst esm = await import(new URL('../dist/esm/index.js', import.meta.url).href);if (typeof esm.OpenWAClient !== 'function') throw new Error('ESM: OpenWAClient missing');+// The webhook helper is a value export in both builds; on Node 18 this also runs its node:crypto+// fallback through the real CJS require() and ESM import() paths.+const secret = 'test-secret-0123456789';+const body = '{"event":"test"}';+const signature = 'sha256=' + createHmac('sha256', secret).update(body).digest('hex');+for (const [format, mod] of [+ ['CJS', cjs],+ ['ESM', esm],+]) {+ if ((await mod.verifyWebhookSignature(body, signature, secret)) !== true) {+ throw new Error(`${format}: verifyWebhookSignature rejected a valid signature`);+ }+}+// Typings smoke: each runtime condition must carry its OWN types entry pointing at the matching// build. A single top-level "types" condition ahead of "require" makes a node16-family CommonJS// TypeScript consumer resolve the ESM declaration while linking the CJS build, which fails withdiff --git a/sdk/javascript/src/index.ts b/sdk/javascript/src/index.tsindex 063a3ba05..714cebc16 100644--- a/sdk/javascript/src/index.ts+++ b/sdk/javascript/src/index.ts@@ -32,3 +32,4 @@ export * from './errors.js';export type * from './types.js';export type { BinaryResponse, ClientConfig, FetchLike, HttpMethod, RequestOptions } from './http.js';export { buildUrl, warnIfInsecureHttpUrl } from './http.js';+export { verifyWebhookSignature } from './webhook.js';diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 647c3e335..0faa53e59 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -917,6 +917,19 @@ export type WebhookEvent =| 'status.received'| '*';+/**+ * The JSON body of a webhook delivery (docs/06 section 6.6). `event` is `'test'` for a delivery+ * sent by the test endpoint. Verify the raw body with `verifyWebhookSignature` before parsing it.+ */+export interface WebhookDelivery<TData = Record<string, unknown>> {+ event: Exclude<WebhookEvent, '*'> | 'test';+ timestamp: string;+ sessionId: string;+ idempotencyKey: string;+ deliveryId: string;+ data: TData;+}+export interface WebhookFilterCondition {field: string;operator: 'contains' | 'equals' | 'is' | 'isNot';diff --git a/sdk/javascript/src/webhook.ts b/sdk/javascript/src/webhook.tsnew file mode 100644index 000000000..8b3333421--- /dev/null+++ b/sdk/javascript/src/webhook.ts@@ -0,0 +1,38 @@+const encoder = new TextEncoder();++/**+ * Check a webhook delivery's `X-OpenWA-Signature` header (`sha256=<hex HMAC-SHA256>`) against the+ * webhook secret. Pass the raw request body exactly as received; a re-serialized parse can differ+ * byte for byte and will not verify. Resolves `false` (never throws) for a missing, malformed or+ * non-matching signature and for an empty secret.+ *+ * Uses WebCrypto, so it runs in browsers, edge runtimes, Deno, Bun and Node; on Node 18, which has+ * no global `crypto`, it loads `node:crypto`'s WebCrypto instead.+ */+export async function verifyWebhookSignature(+ rawBody: string | Uint8Array,+ signature: string | null | undefined,+ secret: string,+): Promise<boolean> {+ const hex = /^sha256=([0-9a-fA-F]{64})$/.exec(signature ?? '')?.[1];+ if (!hex || !secret) return false;+ const subtle = globalThis.crypto?.subtle ?? (await nodeSubtle());+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [+ 'verify',+ ]);+ const mac = new Uint8Array(32);+ for (let i = 0; i < 32; i++) mac[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);+ const body = typeof rawBody === 'string' ? encoder.encode(rawBody) : new Uint8Array(rawBody);+ // subtle.verify compares in constant time.+ return subtle.verify('HMAC', key, mac, body);+}++async function nodeSubtle(): Promise<SubtleCrypto> {+ // A string-typed specifier keeps TypeScript from resolving Node's types and bundlers from+ // pulling the module into browser builds; only a runtime without global WebCrypto gets here.+ const specifier: string = 'node:crypto';+ const mod = (await import(/* webpackIgnore: true */ /* @vite-ignore */ specifier)) as {+ webcrypto: { subtle: SubtleCrypto };+ };+ return mod.webcrypto.subtle;+}diff --git a/sdk/javascript/test/webhook.test.ts b/sdk/javascript/test/webhook.test.tsnew file mode 100644index 000000000..991edf92c--- /dev/null+++ b/sdk/javascript/test/webhook.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { verifyWebhookSignature } from '../src';+import type { WebhookDelivery } from '../src';++// Shared across the SDK suites; the gateway's generateSignature produces this header for this body.+const SECRET = 'test-secret-0123456789';+const BODY =+ '{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1","idempotencyKey":"k",' ++ '"deliveryId":"dlv_1","data":{"text":"héllo \u{1F44B}"}}';+const HEX = 'd74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70';+const SIGNATURE = `sha256=${HEX}`;++describe('verifyWebhookSignature', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('accepts the signature the gateway sends, over a string or the raw bytes', async () => {+ expect(await verifyWebhookSignature(BODY, SIGNATURE, SECRET)).toBe(true);+ expect(await verifyWebhookSignature(new TextEncoder().encode(BODY), SIGNATURE, SECRET)).toBe(true);+ expect(await verifyWebhookSignature(BODY, `sha256=${HEX.toUpperCase()}`, SECRET)).toBe(true);+ });++ it('rejects a changed body, a wrong secret and a malformed header without throwing', async () => {+ const tampered = new TextEncoder().encode(BODY);+ tampered[10] ^= 1;+ expect(await verifyWebhookSignature(tampered, SIGNATURE, SECRET)).toBe(false);+ expect(await verifyWebhookSignature(BODY, SIGNATURE, 'another-secret-012345')).toBe(false);+ for (const header of [+ HEX,+ `SHA256=${HEX}`,+ `sha256=${HEX.slice(1)}`,+ `sha256=${HEX.slice(1)}z`,+ '',+ null,+ undefined,+ ]) {+ expect(await verifyWebhookSignature(BODY, header, SECRET)).toBe(false);+ }+ expect(await verifyWebhookSignature(BODY, SIGNATURE, '')).toBe(false);+ });++ it('falls back to node:crypto where there is no global WebCrypto (Node 18)', async () => {+ vi.stubGlobal('crypto', undefined);+ expect(globalThis.crypto).toBeUndefined();+ expect(await verifyWebhookSignature(BODY, SIGNATURE, SECRET)).toBe(true);+ expect(await verifyWebhookSignature(BODY, SIGNATURE, 'another-secret-012345')).toBe(false);+ });++ it('types the delivery body, including the test event', () => {+ const test: WebhookDelivery = {+ event: 'test',+ timestamp: '2026-02-02T10:00:00.000Z',+ sessionId: 's1',+ idempotencyKey: 'k',+ deliveryId: 'dlv_1',+ data: {},+ };+ const received: WebhookDelivery<{ text: string }> = { ...test, event: 'message.received', data: { text: 'hi' } };+ expect(received.data.text).toBe('hi');+ });+});diff --git a/sdk/php/src/WebhookSignature.php b/sdk/php/src/WebhookSignature.phpnew file mode 100644index 000000000..24b9889ee--- /dev/null+++ b/sdk/php/src/WebhookSignature.php@@ -0,0 +1,30 @@+<?php++declare(strict_types=1);++namespace OpenWA;++/**+ * Checks the X-OpenWA-Signature header of a webhook delivery.+ */+final class WebhookSignature+{+ private function __construct()+ {+ }++ /**+ * Check a delivery's X-OpenWA-Signature header (`sha256=<hex HMAC-SHA256>`)+ * against the webhook secret. Pass the raw request body exactly as received+ * (e.g. `file_get_contents('php://input')`); a re-encoded json_decode() can+ * differ byte for byte and will not verify. Returns false for a missing,+ * malformed or non-matching signature and for an empty secret.+ */+ public static function verify(string $rawBody, ?string $signature, string $secret): bool+ {+ if ($secret === '' || $signature === null || !preg_match('/^sha256=([0-9a-fA-F]{64})$/D', $signature, $m)) {+ return false;+ }+ return hash_equals(hash_hmac('sha256', $rawBody, $secret), strtolower($m[1]));+ }+}diff --git a/sdk/php/tests/WebhookSignatureTest.php b/sdk/php/tests/WebhookSignatureTest.phpnew file mode 100644index 000000000..eddcecc24--- /dev/null+++ b/sdk/php/tests/WebhookSignatureTest.php@@ -0,0 +1,45 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use OpenWA\WebhookSignature;+use PHPUnit\Framework\TestCase;++class WebhookSignatureTest extends TestCase+{+ // Shared across the SDK suites; the gateway's generateSignature produces this header for this body.+ private const SECRET = 'test-secret-0123456789';+ private const BODY = '{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1",'+ . '"idempotencyKey":"k","deliveryId":"dlv_1","data":{"text":"h' . "\u{00e9}llo \u{1F44B}" . '"}}';+ private const HEX = 'd74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70';++ public function testAcceptsTheGatewaySignature(): void+ {+ $this->assertTrue(WebhookSignature::verify(self::BODY, 'sha256=' . self::HEX, self::SECRET));+ $this->assertTrue(WebhookSignature::verify(self::BODY, 'sha256=' . strtoupper(self::HEX), self::SECRET));+ }++ public function testRejectsAChangedBodyAWrongSecretAndAMalformedHeader(): void+ {+ $signature = 'sha256=' . self::HEX;+ $tampered = self::BODY;+ $tampered[10] = chr(ord($tampered[10]) ^ 1);+ $this->assertFalse(WebhookSignature::verify($tampered, $signature, self::SECRET));+ $this->assertFalse(WebhookSignature::verify(self::BODY, $signature, 'another-secret-012345'));+ $this->assertFalse(WebhookSignature::verify(self::BODY, $signature, ''));+ $headers = [+ self::HEX,+ 'SHA256=' . self::HEX,+ 'sha256=' . substr(self::HEX, 1),+ 'sha256=' . substr(self::HEX, 1) . 'z',+ $signature . "\n",+ '',+ null,+ ];+ foreach ($headers as $header) {+ $this->assertFalse(WebhookSignature::verify(self::BODY, $header, self::SECRET), var_export($header, true));+ }+ }+}diff --git a/sdk/python/openwa/__init__.py b/sdk/python/openwa/__init__.pyindex b41e25bdf..98a016a20 100644--- a/sdk/python/openwa/__init__.py+++ b/sdk/python/openwa/__init__.py@@ -37,6 +37,7 @@ from .errors import (OpenWARateLimitError,OpenWATimeoutError,)+from .webhook import verify_webhook_signature__all__ = ["OpenWAClient",@@ -50,4 +51,5 @@ __all__ = ["OpenWANotImplementedError","OpenWAServiceUnavailableError","OpenWATimeoutError",+ "verify_webhook_signature",]diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex cc7440df6..930186b1d 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -937,6 +937,21 @@ class WebhookTestResult(TypedDict, total=False):error: str+class WebhookDelivery(TypedDict):+ """The JSON body of a webhook delivery (docs/06 section 6.6).++ ``event`` is ``"test"`` for a delivery sent by the test endpoint. Check the raw body with+ :func:`openwa.verify_webhook_signature` before parsing it.+ """++ event: WebhookEvent | Literal["test"]+ timestamp: str+ sessionId: str+ idempotencyKey: str+ deliveryId: str+ data: dict[str, Any]++class WebhookDeliveryFailure(TypedDict):"""A webhook delivery abandoned after every retry, as listed by the delivery-failure log."""diff --git a/sdk/python/openwa/webhook.py b/sdk/python/openwa/webhook.pynew file mode 100644index 000000000..4d8259e89--- /dev/null+++ b/sdk/python/openwa/webhook.py@@ -0,0 +1,25 @@+"""Webhook delivery signature check."""++from __future__ import annotations++import hashlib+import hmac+import re++_SIGNATURE = re.compile(r"sha256=([0-9a-fA-F]{64})")+++def verify_webhook_signature(raw_body: bytes | str, signature: str | None, secret: str) -> bool:+ """Check a delivery's ``X-OpenWA-Signature`` header (``sha256=<hex HMAC-SHA256>``) against the+ webhook secret.++ Pass the raw request body exactly as received; a re-serialized parse can differ byte for byte+ and will not verify. Returns False (never raises) for a missing, malformed or non-matching+ signature and for an empty secret.+ """+ match = _SIGNATURE.fullmatch(signature or "")+ if match is None or not secret:+ return False+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body+ expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()+ return hmac.compare_digest(expected, match.group(1).lower())diff --git a/sdk/python/tests/test_webhook.py b/sdk/python/tests/test_webhook.pynew file mode 100644index 000000000..726ef1433--- /dev/null+++ b/sdk/python/tests/test_webhook.py@@ -0,0 +1,51 @@+"""Webhook signature helper."""++from __future__ import annotations++import pytest++from openwa import verify_webhook_signature+from openwa.types import WebhookDelivery++# Shared across the SDK suites; the gateway's generateSignature produces this header for this body.+SECRET = "test-secret-0123456789"+BODY = (+ '{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1","idempotencyKey":"k",'+ '"deliveryId":"dlv_1","data":{"text":"héllo \U0001F44B"}}'+)+HEX = "d74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70"+SIGNATURE = f"sha256={HEX}"+++def test_accepts_the_gateway_signature_over_text_or_bytes():+ assert verify_webhook_signature(BODY, SIGNATURE, SECRET)+ assert verify_webhook_signature(BODY.encode("utf-8"), SIGNATURE, SECRET)+ assert verify_webhook_signature(BODY, f"sha256={HEX.upper()}", SECRET)+++ "header",+ [HEX, f"SHA256={HEX}", f"sha256={HEX[1:]}", f"sha256={HEX[1:]}z", f"sha256={HEX}\n", "", None],+)+def test_rejects_a_malformed_header(header):+ assert verify_webhook_signature(BODY, header, SECRET) is False+++def test_rejects_a_changed_body_a_wrong_secret_and_an_empty_secret():+ tampered = bytearray(BODY.encode("utf-8"))+ tampered[10] ^= 1+ assert verify_webhook_signature(bytes(tampered), SIGNATURE, SECRET) is False+ assert verify_webhook_signature(BODY, SIGNATURE, "another-secret-012345") is False+ assert verify_webhook_signature(BODY, SIGNATURE, "") is False+++def test_delivery_type_accepts_the_test_event():+ delivery: WebhookDelivery = {+ "event": "test",+ "timestamp": "2026-02-02T10:00:00.000Z",+ "sessionId": "s1",+ "idempotencyKey": "k",+ "deliveryId": "dlv_1",+ "data": {},+ }+ assert delivery["event"] == "test"diff --git a/src/modules/webhook/utils/deliver-once.spec.ts b/src/modules/webhook/utils/deliver-once.spec.tsindex 2e45986d8..32efa5a44 100644--- a/src/modules/webhook/utils/deliver-once.spec.ts+++ b/src/modules/webhook/utils/deliver-once.spec.ts@@ -1,5 +1,11 @@import { Headers } from 'undici';-import { buildDeliveryHeaders, isDeliverableWebhook, postWebhookPayload, sanitizeCustomHeaders } from './deliver-once';+import {+ buildDeliveryHeaders,+ generateSignature,+ isDeliverableWebhook,+ postWebhookPayload,+ sanitizeCustomHeaders,+} from './deliver-once';/*** Direct coverage for the shared delivery core both paths (direct and queued processor) now route@@ -111,3 +117,14 @@ describe('isDeliverableWebhook', () => {expect(isDeliverableWebhook(row, 'message.ack')).toBe(false);});});++describe('generateSignature', () => {+ it('matches the vector the SDK signature helpers are tested against', () => {+ const body =+ '{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1","idempotencyKey":"k",' ++ '"deliveryId":"dlv_1","data":{"text":"h\u00e9llo \u{1F44B}"}}';+ expect(generateSignature(body, 'test-secret-0123456789')).toBe(+ 'sha256=d74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70',+ );+ });+});