Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): describe webhook filters in the contract and conform both clients fully
Yudhi Armyndharisfb94efa8cae7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b86f3d81f..bec86a0d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The OpenAPI contract now describes the webhook smart-filter shape: `filters` on the webhook create, update and read DTOs degraded to a bare `{ "type": "object" }` because the runtime type is a plain interface the scanner cannot introspect. Metadata classes (`WebhookFiltersDto`, `WebhookFilterConditionDto`) now back all three, so generated clients and the dashboard type view see the real `conditions` shape with its bounds (1..20). Runtime validation is unchanged.+- `GET /infra/config` now resolves each field with the boot precedence (host environment, then project `.env`, then `data/.env.generated`) instead of reporting only the dashboard-saved file: a deployment setting `ENGINE_TYPE`/`DATABASE_TYPE`/`REDIS_ENABLED` via Compose `environment:` no longer reads back `whatsapp-web.js`/`sqlite`/disabled defaults that contradict the running process (#1313). Values that only ever lived in the saved file still hydrate the form as before, so the "saved, pending restart" state is unchanged, and the dashboard now omits `engine.type` from a save when the seeded value is an environment pin the operator never chose — the stored engine selection survives until the variable is unset (#1082).### Security@@ -19,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Weekly scheduled security scan (`.github/workflows/security-scan.yml`): the merge-time audit gates re-run against the current dependency trees, and the release image scan re-runs against the published `latest` image on both architectures — a newly published advisory surfaces within days instead of at the next push or release. Also dispatchable on demand.-- Client wire-shape contract gate (`check:contract-shapes`, in the CI lint job): the JavaScript SDK's and the dashboard's hand-written wire types are now checked field-by-field against the OpenAPI schemas — presence, required-vs-optional, and type drift for simple fields — closing the gap where every existing gate verified which routes exist but none verified the body shapes they carry. 37 pairs conform today; the 7 remaining exclusions are recorded inline with reasons — one is deliberate (the dashboard's tri-state `engineLoaded` client model), the rest are a field-by-field adjudication backlog.+- Client wire-shape contract gate (`check:contract-shapes`, in the CI lint job): the JavaScript SDK's and the dashboard's hand-written wire types are now checked field-by-field against the OpenAPI schemas — presence, required-vs-optional, and type drift for simple fields — closing the gap where every existing gate verified which routes exist but none verified the body shapes they carry. 43 pairs conform today; the single remaining exclusion is deliberate (the dashboard's tri-state `engineLoaded` client model, which models client state rather than the wire).## [0.19.0] - 2026-08-15diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex abe2998e3..a0fded4cc 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -284,14 +284,54 @@ export interface EngineHistoryMessage {from: string;to: string;body: string;- type: string;+ type: MessageType;+ /** Unix timestamp in seconds. */timestamp: number;- fromMe?: boolean;- media?: { mimetype: string; filename?: string; data?: string };+ fromMe: boolean;+ isGroup: boolean;+ isStatusBroadcast?: boolean;+ kind: ChatKind;+ /** Disappearing-messages timer on the chat, in seconds. Absent when the chat has none set. */+ ephemeralDuration?: number;/** Sender in a group: `from` is the group JID, so this participant WID is the real poster. */author?: string;- /** Best-effort sender contact (sync cache); its name labels the poster in a group thread. */- contact?: { id?: string; name?: string; pushName?: string };+ mentionedIds?: string[];+ /** Present on `call` messages only. */+ call?: { video: boolean; missed: boolean };+ isLidSender?: boolean;+ senderPhone?: string | null;+ /**+ * Sender contact info, best-effort from the engine's cache. History carries `pushName` only;+ * the richer fields arrive on `message.received` when `WEBHOOK_CONTACT_DETAILS=true`.+ */+ contact?: {+ id?: string;+ number?: string;+ name?: string;+ pushName?: string;+ shortName?: string;+ type?: string;+ isMyContact?: boolean;+ isWAContact?: boolean;+ isBusiness?: boolean;+ isEnterprise?: boolean;+ verifiedName?: string;+ verifiedLevel?: number;+ isBlocked?: boolean;+ labels?: string[];+ };+ /** Status/story styling. Declared by the engine payload; this route never sets either. */+ backgroundColor?: string;+ font?: number;+ media?: {+ mimetype: string;+ filename?: string;+ data?: string;+ omitted?: boolean;+ sizeBytes?: number;+ };+ quotedMessage?: { id: string; body: string };+ location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };}// Mirrors the backend engine Channel / ChannelMessage (GET /sessions/:id/channels[/:id/messages]).diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 7dc6b94c8..e04985b62 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -17,6 +17,8 @@ const hist = (over: Partial<EngineHistoryMessage> = {}): EngineHistoryMessage =>type: 'text',timestamp: 1782053533,fromMe: false,+ isGroup: true,+ kind: 'group',...over,});diff --git a/openapi.json b/openapi.jsonindex d3e7b4702..6ad2bedb8 100644--- a/openapi.json+++ b/openapi.json@@ -10538,6 +10538,71 @@"memoryUsage"]},+ "WebhookFilterConditionDto": {+ "type": "object",+ "properties": {+ "field": {+ "type": "string",+ "example": "sender",+ "description": "Filterable field for the fired event family."+ },+ "operator": {+ "type": "string",+ "enum": [+ "is",+ "isNot",+ "contains",+ "equals"+ ],+ "example": "is"+ },+ "value": {+ "oneOf": [+ {+ "type": "string"+ },+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "boolean"+ }+ ],+ "example": [+ ]+ },+ "caseSensitive": {+ "type": "boolean",+ "description": "Only meaningful for text fields. Defaults to false."+ }+ },+ "required": [+ "field",+ "operator",+ "value"+ ]+ },+ "WebhookFiltersDto": {+ "type": "object",+ "properties": {+ "conditions": {+ "minItems": 1,+ "maxItems": 20,+ "description": "Every condition must match (AND) for the webhook to fire.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/WebhookFilterConditionDto"+ }+ }+ },+ "required": [+ "conditions"+ ]+ },"CreateWebhookDto": {"type": "object","properties": {@@ -10597,7 +10662,6 @@}},"filters": {- "type": "object","description": "Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.","example": {"conditions": [@@ -10615,7 +10679,13 @@}]},- "nullable": true+ "nullable": true,+ "type": "object",+ "allOf": [+ {+ "$ref": "#/components/schemas/WebhookFiltersDto"+ }+ ]},"retryCount": {"type": "number",@@ -10648,7 +10718,6 @@}},"filters": {- "type": "object","description": "Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.","example": {"conditions": [@@ -10666,7 +10735,13 @@}]},- "nullable": true+ "nullable": true,+ "type": "object",+ "allOf": [+ {+ "$ref": "#/components/schemas/WebhookFiltersDto"+ }+ ]},"active": {"type": "boolean"@@ -10749,7 +10824,6 @@"description": "Custom headers"},"filters": {- "type": "object","description": "Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.","example": {"conditions": [@@ -10767,7 +10841,13 @@}]},- "nullable": true+ "nullable": true,+ "type": "object",+ "allOf": [+ {+ "$ref": "#/components/schemas/WebhookFiltersDto"+ }+ ]},"active": {"type": "boolean",diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 5a156cbdf..055a25887 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -95,20 +95,9 @@ const MINIMUM_MAPPED = {/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */const EXCLUDED = {- 'sdk/javascript/src/types.ts': {- ChatHistoryMessage: 'field-level differences across the 20+-field history shape; adjudicate pair-by-pair',- ChatSummary:- 'hand marks every field optional and widens timestamp to string|number; contract requires them, timestamp a number',- GroupInfo: 'nullable-vs-optional and enum differences across 10+ fields; adjudicate pair-by-pair',- SessionResponse: 'field-level differences; adjudicate pair-by-pair',- WebhookResponse:- 'CONTRACT GAP: response schema declares filters as Record<string, never>; fix the backend DTO decorator, then pin',- },'dashboard/src/services/api.ts': {Session:'BY DESIGN, not drift: the wire always carries engineLoaded, but this client clears it to "unknown" after a websocket status event so the action helpers fall back to the status set — the type models client state, not the wire',- EngineHistoryMessage:- 'hand models a subset of the history shape (13 contract fields missing, fromMe optional); mirror the full shape',},};@@ -228,6 +217,15 @@ function baseSchemaToken(node, schemas, depth = 0) {if (nullable && rest.length === 1) return `${rest[0]}|null`;return `union(${rest.sort().join(',')})`;}+ if (node.allOf) {+ // OpenAPI 3.0 composes class-typed fields (and ref+nullable pairs) as allOf members — merge+ // the members' object tokens into one (later members win, matching composition semantics).+ const merged = Object.assign({}, ...node.allOf.map(n => parseObjectToken(schemaToken(n, schemas, depth + 1))));+ return `object(${Object.entries(merged)+ .map(([f, v]) => `${f}${v.optional ? '?' : ''}:${v.token}`)+ .sort()+ .join(',')})`;+ }if (node.type === 'object') {if (depth >= MAX_DEPTH) return 'object';const required = new Set(node.required ?? []);diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 1246acdf7..4e96d5f2b 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -79,7 +79,7 @@ export interface SessionResponse {* `disconnected` covers both a session mid automatic-reconnect (engine present) and one stopped* with no engine. Absent from a gateway that predates the field.*/- engineLoaded?: boolean;+ engineLoaded: boolean;}/**@@ -482,19 +482,40 @@ export interface MessageRecord {* A message read live from WhatsApp by `messages.history()`. This is the engine* payload (richer and differently shaped than the persisted {@link MessageRecord}).*/+/**+ * The engine-normalized message kinds — persisted rows, `message.received`/`message.sent`+ * payloads and the websocket all use these values (raw engine tokens are normalized at the+ * adapter boundary).+ */+export type MessageType =+ | 'text'+ | 'image'+ | 'video'+ | 'audio'+ | 'voice'+ | 'document'+ | 'sticker'+ | 'location'+ | 'contact'+ | 'poll'+ | 'call'+ | 'revoked'+ | 'masked'+ | 'unknown';+export interface ChatHistoryMessage {id: string;from: Jid;to: Jid;chatId: Jid;body: string;- type: string;+ type: MessageType;/** Unix timestamp in seconds. */timestamp: number;fromMe: boolean;isGroup: boolean;isStatusBroadcast?: boolean;- kind?: ChatKind;+ kind: ChatKind;/** Disappearing-messages timer on the chat, in seconds. Absent when the chat has none set. */ephemeralDuration?: number;/** For group messages, the participant who sent it (`from` is the group JID). */@@ -700,7 +721,15 @@ export interface GroupSummary {export interface GroupInfo {id: Jid;name: string;- description?: string | null;+ description?: string;+ /** Only admins may send messages. */+ announce?: boolean;+ /** Disappearing-messages timer in seconds; 0 or absent means off. */+ ephemeralSeconds?: number;+ /** Only admins may edit subject, description and picture. */+ locked?: boolean;+ /** Who may add participants. Absent when the engine did not report it. */+ memberAddMode?: 'all' | 'admins';owner?: Jid | null;/** Unix timestamp in seconds. */createdAt?: number;@@ -869,7 +898,7 @@ export interface WebhookResponse {filters?: WebhookFilters | null;retryCount: number;/** ISO timestamp of the last delivery attempt, or null if never triggered. */- lastTriggeredAt: string | null;+ lastTriggeredAt?: string | null;createdAt: string;updatedAt: string;// NOTE: the server deliberately omits `secret` and `headers` from read responses.@@ -885,13 +914,14 @@ export interface WebhookTestResult {export interface ChatSummary {id: Jid;- name?: string | null;- isGroup?: boolean;- unreadCount?: number;+ name: string;+ isGroup: boolean;+ unreadCount: number;/** Preview text of the last message (the server returns a plain string, not an object). */lastMessage?: string;- timestamp?: string | number;- kind?: ChatKind;+ /** Unix seconds of the last activity. */+ timestamp: number;+ kind: ChatKind;}/** Body for {@link SessionsResource.setOnlinePresence}. */diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex fec309f3b..07e23d63e 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -14,11 +14,46 @@ import {} from 'class-validator';import { Expose, plainToInstance } from 'class-transformer';import { Webhook } from '../entities/webhook.entity';-import { WebhookFilters } from '../filters/filter-types';+import { MAX_CONDITIONS } from '../filters/filter-types';+import type { FilterOperator, WebhookFilters } from '../filters/filter-types';import { IsValidWebhookFilters } from '../filters/filter-validation';import { IsHeaderMap } from './is-header-map.validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';+/**+ * Swagger metadata for the smart-filter shape — `WebhookFilters` in filters/filter-types.ts is a+ * plain interface (validated at runtime by @IsValidWebhookFilters), which the scanner cannot+ * introspect: without these classes the `filters` field on every webhook DTO degraded to a bare+ * `{ "type": "object" }` in openapi.json, describing NEITHER side of the wire. Metadata only —+ * no validators here; the runtime types stay authoritative.+ */+class WebhookFilterConditionDto {+ @ApiProperty({ example: 'sender', description: 'Filterable field for the fired event family.' })+ field!: string;++ @ApiProperty({ enum: ['is', 'isNot', 'contains', 'equals'], example: 'is' })+ operator!: FilterOperator;++ @ApiProperty({+ oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }, { type: 'boolean' }],+ example: ['[email protected]'],+ })+ value!: string | string[] | boolean;++ @ApiPropertyOptional({ description: 'Only meaningful for text fields. Defaults to false.' })+ caseSensitive?: boolean;+}++class WebhookFiltersDto {+ @ApiProperty({+ type: [WebhookFilterConditionDto],+ minItems: 1,+ maxItems: MAX_CONDITIONS,+ description: 'Every condition must match (AND) for the webhook to fire.',+ })+ conditions!: WebhookFilterConditionDto[];+}+const FILTERS_API_DESCRIPTION ='Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.';const FILTERS_API_EXAMPLE = {@@ -107,7 +142,12 @@ export class CreateWebhookDto {// STORED as null whenever a webhook is created without filters (`dto.filters ?? null`), and the// description offers null as an input, so a schema without it rejects a value the route both// sends and accepts.- @ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE, nullable: true })+ @ApiPropertyOptional({+ type: WebhookFiltersDto,+ description: FILTERS_API_DESCRIPTION,+ example: FILTERS_API_EXAMPLE,+ nullable: true,+ })@IsOptional()@IsValidWebhookFilters()filters?: WebhookFilters | null;@@ -160,7 +200,12 @@ export class UpdateWebhookDto {// STORED as null whenever a webhook is created without filters (`dto.filters ?? null`), and the// description offers null as an input, so a schema without it rejects a value the route both// sends and accepts.- @ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE, nullable: true })+ @ApiPropertyOptional({+ type: WebhookFiltersDto,+ description: FILTERS_API_DESCRIPTION,+ example: FILTERS_API_EXAMPLE,+ nullable: true,+ })@IsOptional()@IsValidWebhookFilters()filters?: WebhookFilters | null;@@ -217,7 +262,12 @@ export class WebhookResponseDto {// STORED as null whenever a webhook is created without filters (`dto.filters ?? null`), and the// description offers null as an input, so a schema without it rejects a value the route both// sends and accepts.- @ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE, nullable: true })+ @ApiPropertyOptional({+ type: WebhookFiltersDto,+ description: FILTERS_API_DESCRIPTION,+ example: FILTERS_API_EXAMPLE,+ nullable: true,+ })filters?: WebhookFilters | null;@Expose()