Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): say when a smart filter suppresses a delivery
Yudhi Armyndharis63bc421c7b80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb16017b6..ec3a1ed80 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **The published OpenAPI document is schema-valid again** — `@nestjs/swagger` expands an `@All()` route over its own method list, which includes `search`, and the 3.0 Path Item Object has no field for it, so the ingress route contributed a key that made strict validators reject the whole 150-path document rather than just that route; the export now drops operations the specification cannot express, and nothing in the repository validated the document to catch it.- ⚠️ **Breaking (SDK types only, no gateway change). Three response shapes the SDKs decoded into the wrong type** — the four group membership writes answer with a per-participant `results` array that a partial refusal is reported in, and all four typed SDKs declared only `{success, message}`, so a rejected member was indistinguishable from a fully applied batch; `ContactRecord` declared `pushname` where both engines emit `pushName` (which left Java's case-sensitive binder returning null for every contact), carried an `isBusiness` the API never sends, and omitted `isBlocked` and `profilePicUrl`; and `send-product` answers with `id` while the SDKs decoded `messageId`.**Migration.** `addParticipants`/`removeParticipants`/`promoteParticipants`/`demoteParticipants` now return `ParticipantsResult` — a superset of the old type, so existing reads of `success`/`message` keep compiling. `ContactRecord.pushname` becomes `pushName` and `isBusiness` is gone; both were always empty. `sendProduct` returns `ProductMessageResponse { id }`.+- **A webhook a smart filter drops now leaves a trace** — a condition on a field the event's payload does not carry cannot match, so a `sender` filter suppressed every `message.ack`, `message.failed` and `message.reaction` while the dispatch logged nothing, emitted no metric and recorded nothing in the delivery-failure table, which only tracks deliveries that were attempted; suppression is now logged at debug with the payload fields that were actually available, and the interaction is documented.+- **Two webhook payload descriptions did not match what is sent** — `session.qr` was documented as carrying the raw QR string when both engines render it to a PNG data URL before the event is dispatched, and the filter field list did not say that its fields exist on only some message events.## [0.14.5] - 2026-08-08diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 43490a037..2c79114f7 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4053,14 +4053,14 @@ Create a webhook for the session.**Request body** — `CreateWebhookDto`-| Field | Type | Required | Constraints | Description |-| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |-| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |-| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |-| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned. Used for `X-OpenWA-Signature`. Defaults to `null`. |-| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned. At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |-| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. |-| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |+| Field | Type | Required | Constraints | Description |+| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |+| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |+| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned. Used for `X-OpenWA-Signature`. Defaults to `null`. |+| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned. At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |+| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is absent from an event's payload cannot match, so it suppresses that event entirely — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |+| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |```json{@@ -6116,7 +6116,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `message.revoked` | A message is deleted/recalled | `{ id, revokedId?, chatId, from, to, type: "revoked", body: "", timestamp }` — **reconcile on `revokedId`** (the original deleted message's id), falling back to `id`. On whatsapp-web.js `id` is the _revocation notification_ (a distinct message that won't match a stored id) and `revokedId` may be absent when the original isn't cached locally; on Baileys the two coincide || `message.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions? }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot, omitted when the gateway holds no stored copy of the message to compute it from (an ephemeral message, or one predating the session going live); treat it as unknown rather than empty and keep the map you already hold. `reaction` is empty when removed || `message.edited` | A message body or media caption is edited | `{ messageId, chatId, body, senderId, from, to, fromMe, isGroup, type, hasMedia, author?, mentionedIds?, timestamp }` — `messageId` is the original message id, `body` is the latest text/caption, and `timestamp` is the edit occurrence time in epoch **seconds** (not the original creation time) |-| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` (raw QR string) |+| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` — `qr` is a **PNG data URL** (`data:image/png;base64,…`), the same rendered value `GET /api/sessions/{id}/qr` returns as `qrCode`, not the raw `2@…` linking ref. Render it directly in an `<img src>`; the raw ref never leaves the engine adapter || `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` || `session.disconnected` | The session disconnects on the engine or WhatsApp side (drop, conflict, or a phone-initiated unlink). Not fired for API-initiated stop/logout/delete — those are acknowledged by the API response and the `session.status` transition | `{ sessionId, reason }` || `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 80b24db34..d08421cda 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -1119,6 +1119,44 @@ describe('WebhookService', () => {return mockFetch.mock.calls.length;}+ // A condition names a field the event's payload does not carry — `sender` resolves from+ // author/from, and message.ack dispatches { id, messageId, status, ack }. The condition cannot+ // match, so the delivery is dropped. That is the filter working as specified; what was missing+ // was any way to find out it had happened.+ it('logs when a filter suppresses a subscribed webhook', async () => {+ const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;+ const spy = jest.spyOn(logger, 'debug');++ expect(+ await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.ack', {+ messageId: 'm1',+ status: 'read',+ }),+ ).toBe(0);++ const suppressed = spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'));+ expect(suppressed).toHaveLength(1);+ expect(suppressed[0][1]).toMatchObject({ event: 'message.ack', subscribed: 1, suppressed: 1 });+ // The payload's own fields are recorded, because the usual cause is a condition on a field+ // this event does not have — that list is the answer to "why did nothing fire?".+ expect((suppressed[0][1] as { payloadFields: string }).payloadFields).toBe('messageId,status');+ spy.mockRestore();+ });++ it('stays quiet when nothing is suppressed', async () => {+ const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;+ const spy = jest.spyOn(logger, 'debug');++ expect(+ await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.received', {+ from: '[email protected]',+ }),+ ).toBe(1);++ expect(spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'))).toHaveLength(0);+ spy.mockRestore();+ });+it('fires with no filters (additive: zero-config behaviour is unchanged)', async () => {expect(await deliveries(null, 'message.received', { from: '[email protected]' })).toBe(1);expect(await deliveries(conds(), 'message.received', { from: '[email protected]' })).toBe(1);diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex aa7f29daf..0c9cf2b3f 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -448,9 +448,25 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Resolve a lid actor to its phone through the persistent table so a phone filter matches a// lid-addressed sender (e.g. an unresolved @lid group participant). Absent store -> no resolution.const resolveLid = (jid: string): string | null => this.lidMappingStore?.getCached(userPart(jid)) ?? null;- return webhooks.filter(- w => (w.events.includes(event) || w.events.includes('*')) && evaluateFilters(w.filters, event, data, resolveLid),- );+ const subscribed = webhooks.filter(w => w.events.includes(event) || w.events.includes('*'));+ const matching = subscribed.filter(w => evaluateFilters(w.filters, event, data, resolveLid));+ // A subscribed webhook that a filter drops leaves no trace otherwise: dispatch() awaits an empty+ // array and returns, and the delivery-failure table only records deliveries that were ATTEMPTED.+ // That is fine when the filter is doing its job, and indistinguishable from it when it is not —+ // a condition on a field the event's payload does not carry resolves to undefined and fails,+ // which is how a `sender` filter silently swallows every message.ack. Debug rather than warn:+ // suppression is the normal outcome of a working filter, so this is a trace to switch on while+ // investigating, not an alarm.+ if (matching.length < subscribed.length) {+ this.logger.debug('Webhook filters suppressed a delivery', {+ action: 'webhook_filter_suppressed',+ event,+ subscribed: subscribed.length,+ suppressed: subscribed.length - matching.length,+ payloadFields: Object.keys(data).sort().join(','),+ });+ }+ return matching;}private async recordUndelivered(