Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(automation): keep rules without a kind condition out of channels
Yudhi Armyndharis6bd221bd68fe
diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 347daddfa..69a877222 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -459,7 +459,8 @@ CREATE TABLE webhooks (### 5.3.2a automation_rulesPer-session single-message autoreply rules. `conditions` reuses the webhook filter shape verbatim-(null/empty matches every inbound message); the reply goes through the ordinary send path.+(null/empty matches every inbound message except channel, broadcast-list and status messages, which+need a `kind` condition); the reply goes through the ordinary send path.```sqlCREATE TABLE automation_rules (diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2c05c5acd..2201ea108 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6572,7 +6572,11 @@ the receive path and runs at most once per message (engine re-fires are deduplic`conditions` uses the **webhook filter format** (`message` family — see 6.4.8): a flat AND list ofconditions over `sender`, `recipient`, `chatId`, `body`, `type`, `isGroup`, `kind`, `fromMe`, `hasMedia`, `mentions`.-Omitted or empty conditions match every inbound message.+Omitted or empty conditions match every inbound message except channel, broadcast-list and status+messages: a rule answers those only when its conditions include a `kind` condition that matches+them (for example `kind is channel`). A rule without one skips those chats, because a reply into a+channel the account administers is published to every follower, and anywhere else WhatsApp refuses+it.Loop safety: a rule never answers the account's own (`fromMe`) messages, messages older than5 minutes get no automated answer (so a reconnect never burst-replies the offline-queued backlog),@@ -6588,13 +6592,13 @@ Create a rule. **Auth:** API key (OPERATOR)**Request body**-| Field | Type | Required | Description |-| --------------- | ------- | -------- | ------------------------------------------------------------------ |-| name | string | yes | Display name, max 100 chars. |-| replyText | string | yes | Reply content, max 4096 chars (the send-text limit). |-| conditions | object | no | Webhook-filter conditions (`message` family). Omitted = match all. |-| cooldownSeconds | number | no | Per-chat quiet period, 0–86400. Default `60`. |-| enabled | boolean | no | Default `true`. |+| Field | Type | Required | Description |+| --------------- | ------- | -------- | ------------------------------------------------------------------------------------------- |+| name | string | yes | Display name, max 100 chars. |+| replyText | string | yes | Reply content, max 4096 chars (the send-text limit). |+| conditions | object | no | Webhook-filter conditions (`message` family). Omitted = match all (see above for channels). |+| cooldownSeconds | number | no | Per-chat quiet period, 0–86400. Default `60`. |+| enabled | boolean | no | Default `true`. |**Response** `201`diff --git a/openapi.json b/openapi.jsonindex e2d85c650..c3fb8c818 100644--- a/openapi.json+++ b/openapi.json@@ -11504,7 +11504,7 @@},"conditions": {"type": "object",- "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message."+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message except channel, broadcast-list and status messages, which a rule answers only when it has a `kind` condition that matches them."},"cooldownSeconds": {"type": "number",@@ -11541,7 +11541,7 @@},"conditions": {"type": "object",- "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message.",+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message except channel, broadcast-list and status messages, which a rule answers only when it has a `kind` condition that matches them.","nullable": true},"replyText": {@@ -11585,7 +11585,7 @@},"conditions": {"type": "object",- "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message."+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message except channel, broadcast-list and status messages, which a rule answers only when it has a `kind` condition that matches them."},"cooldownSeconds": {"type": "number",diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.tsindex 30fc3b888..8acf9a389 100644--- a/src/modules/automation/automation-rules.service.spec.ts+++ b/src/modules/automation/automation-rules.service.spec.ts@@ -150,6 +150,47 @@ describe('AutomationRulesService', () => {expect(sends).toHaveLength(1);});+ it('a rule with no kind condition never answers a channel, broadcast list or status', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 0 });+ await service.create('sessA', {+ name: 'hello',+ replyText: 'hi',+ cooldownSeconds: 0,+ conditions: { conditions: [{ field: 'body', operator: 'contains', value: 'hello' }] },+ });++ for (const chatId of ['120363000000000001@newsletter', '1234@broadcast', 'status@broadcast']) {+ await service.evaluateInbound('sessA', inbound({ chatId, from: chatId }));+ }+ expect(sends).toHaveLength(0);++ // Direct and group chats are still answered.+ await service.evaluateInbound('sessA', inbound());+ await service.evaluateInbound('sessA', inbound({ chatId: '[email protected]', isGroup: true }));+ expect(sends.map(s => s.chatId)).toEqual(['[email protected]', '[email protected]']);+ });++ it('an explicit kind condition still reaches a channel or broadcast list', async () => {+ // Ordered first, so it would win if the kind guard did not skip it for the channel.+ const all = await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 0 });+ await service.create('sessA', {+ name: 'channels',+ replyText: 'channel-reply',+ cooldownSeconds: 0,+ conditions: { conditions: [{ field: 'kind', operator: 'is', value: ['channel', 'broadcast'] }] },+ });+ // createdAt has 1s precision on SQLite; pin it so the evaluation order is the one described.+ await ds.getRepository(AutomationRule).update(all.id, { createdAt: new Date('2026-01-01T00:00:00Z') });++ await service.evaluateInbound('sessA', inbound({ chatId: '120363000000000001@newsletter' }));+ await service.evaluateInbound('sessA', inbound({ chatId: '1234@broadcast' }));++ expect(sends.map(s => [s.chatId, s.text])).toEqual([+ ['120363000000000001@newsletter', 'channel-reply'],+ ['1234@broadcast', 'channel-reply'],+ ]);+ });+it('never replies to the account’s own messages (fromMe)', async () => {await service.create('sessA', { name: 'all', replyText: 'ack' });diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsindex 46a3cc3a1..32ecd8797 100644--- a/src/modules/automation/automation-rules.service.ts+++ b/src/modules/automation/automation-rules.service.ts@@ -5,6 +5,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { createLogger } from '../../common/services/logger.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import { chatKind } from '../../engine/identity/wa-id';import { evaluateFilters } from '../webhook/filters/filter-evaluator';import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';import { AutomationRule } from './entities/automation-rule.entity';@@ -22,6 +23,13 @@ const COOLDOWN_SWEEP_THRESHOLD = 10_000;*/const MAX_MESSAGE_AGE_SECONDS = 300;+/**+ * Chat kinds a rule answers only when it names them. A reply into a channel is published to every+ * follower when the account is an admin there, and is refused everywhere else (a failed send that can+ * also count toward the send-pacing breaker); a status or broadcast list has no conversation to answer.+ */+const OPT_IN_CHAT_KINDS: ReadonlySet<string> = new Set(['channel', 'broadcast', 'status']);+/*** Single-message autoreply rules: evaluated on every inbound message, first matching rule replies* into the chat through the ordinary send path.@@ -153,10 +161,17 @@ export class AutomationRulesService {// matches a lid-addressed sender identically in both places.const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;+ // Resolved the way the `kind` filter field resolves it, so the guard and a kind condition agree.+ const kind = typeof message.kind === 'string' && message.kind ? message.kind : chatKind(chatId);+ const optInOnly = OPT_IN_CHAT_KINDS.has(kind);+// First match wins: one inbound message never produces more than one automated reply, and rule- // order (creation order) is the tiebreak the operator can reason about.- const rule = rules.find(candidate =>- evaluateFilters(candidate.conditions, 'message.received', message, resolveLid),+ // order (creation order) is the tiebreak the operator can reason about. A rule without a `kind`+ // condition skips the opt-in chat kinds; naming the kind is how a rule reaches them.+ const rule = rules.find(+ candidate =>+ (!optInOnly || candidate.conditions?.conditions?.some(c => c.field === 'kind')) &&+ evaluateFilters(candidate.conditions, 'message.received', message, resolveLid),);if (!rule) return;if (this.inCooldown(rule, chatId)) return;diff --git a/src/modules/automation/dto/automation-rule.dto.ts b/src/modules/automation/dto/automation-rule.dto.tsindex 94eeb0957..a53dc3627 100644--- a/src/modules/automation/dto/automation-rule.dto.ts+++ b/src/modules/automation/dto/automation-rule.dto.ts@@ -13,7 +13,8 @@ export const AUTOMATION_COOLDOWN_MAX_SECONDS = 86_400;const CONDITIONS_DESCRIPTION ='Match conditions in the webhook filter format (message family: sender, recipient, chatId, body, ' +'type, isGroup, kind, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or ' +- 'empty means the rule matches every inbound message.';+ 'empty means the rule matches every inbound message except channel, broadcast-list and status ' ++ 'messages, which a rule answers only when it has a `kind` condition that matches them.';const COOLDOWN_DESCRIPTION ='Quiet period per chat, in seconds: after the rule replies in a chat it stays silent there for ' +diff --git a/src/modules/automation/entities/automation-rule.entity.ts b/src/modules/automation/entities/automation-rule.entity.tsindex f5b17f75a..1ecef0417 100644--- a/src/modules/automation/entities/automation-rule.entity.ts+++ b/src/modules/automation/entities/automation-rule.entity.ts@@ -18,7 +18,8 @@ import { WebhookFilters } from '../../webhook/filters/filter-types';** `conditions` reuses the webhook filter shape (`message` family) verbatim — same JSON, same* validator, same evaluator — so a rule matches exactly what a filtered `message.received` webhook- * would have fired for. Null/empty conditions match every inbound message.+ * would have fired for. Null/empty conditions match every inbound message. One exception: a rule+ * without a `kind` condition never answers a channel, broadcast list or status (see evaluateInbound).*/@Entity('automation_rules')export class AutomationRule {