Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhooks): keep distinct LID filters separate
Yudhi Armyndharis5ae3b19096cb
diff --git a/src/modules/webhook/filters/filter-evaluator.spec.ts b/src/modules/webhook/filters/filter-evaluator.spec.tsindex 38c00feb3..fd25b5ee7 100644--- a/src/modules/webhook/filters/filter-evaluator.spec.ts+++ b/src/modules/webhook/filters/filter-evaluator.spec.ts@@ -211,6 +211,26 @@ describe('evaluateFilters', () => {// engine emits and regardless of how the filter is written (bare digits or a JID).describe('engine-neutral id matching', () => {+ it.each(['sender', 'mentions'])('preserves raw LID identity in %s conditions', field => {+ const resolve = () => '628999';+ const matches = (actual: string, candidate: string, operator: 'is' | 'isNot' = 'is') =>+ evaluateFilters(+ filters({ field, operator, value: [candidate] }),+ 'message.received',+ msg({ from: actual, mentionedIds: [actual] }),+ resolve,+ );+ expect(matches('111@lid', '222@lid')).toBe(false);+ expect(matches('111@lid', '222@lid', 'isNot')).toBe(true);+ expect(matches('111:7@lid', '111:2@LID')).toBe(true);+ expect(matches('111:7@lid', '111:2@LID', 'isNot')).toBe(false);+ expect(matches('111@lid', '+62 (89) 99')).toBe(true);+ expect(matches('628999:[email protected]', '111@lid')).toBe(true);+ expect(matches('111@lid', '628999:[email protected]')).toBe(true);+ expect(matches('[email protected]', '628999:[email protected]')).toBe(true);+ expect(matches('111@lid', '[email protected]')).toBe(false);+ });+it('matches the same user across @c.us and @s.whatsapp.net', () => {const f = filters({ field: 'sender', operator: 'is', value: ['[email protected]'] });expect(evaluateFilters(f, 'message.received', msg({ from: '[email protected]' }))).toBe(true);diff --git a/src/modules/webhook/filters/filter-evaluator.ts b/src/modules/webhook/filters/filter-evaluator.tsindex ff14b7d76..6cf7d001e 100644--- a/src/modules/webhook/filters/filter-evaluator.ts+++ b/src/modules/webhook/filters/filter-evaluator.ts@@ -14,11 +14,7 @@ import { parseWaId, toNeutralJid } from '../../../engine/identity/wa-id';*/export type LidResolver = (jid: string) => string | null;-// Reduce an id to its engine-neutral canonical key so the same contact matches regardless of dialect.-// An engine-emitted JID (any of @c.us / @s.whatsapp.net / @lid, an optional :device suffix, a lid the-// table resolves to its phone) and a user-typed filter value (bare digits or a JID) both collapse to-// the same neutral string (`<phone>@c.us` / `<id>@g.us` / `<lid>@lid`). So a phone filter now matches-// the person across user dialects AND any lid resolving to that phone - previously a silent miss.+// Normalize dialect and device suffixes without losing the original LID identity.const canonicalActor = (jid: string, resolve?: LidResolver): string => toNeutralJid(jid, resolve).toLowerCase();const canonicalInput = (value: string, resolve?: LidResolver): string => {// Bare digits are a phone-addressed user; anything else parses as a JID. Mirrors the engine's@@ -29,16 +25,25 @@ const canonicalInput = (value: string, resolve?: LidResolver): string => {if (trimmed && !trimmed.includes('@')) {return `${trimmed.replace(/\D/g, '') || trimmed}@c.us`.toLowerCase();}- // Through the same resolver as the payload side. A rule can hold a lid: the dashboard's chat- // picker stores whatever id the chat carries. Canonicalising only one side meant the two stopped- // agreeing the moment the gateway learned that lid's phone, which silently flips an exclusion- // open and an inclusion shut, with the rule still reading correctly in the UI.return toNeutralJid(trimmed, resolve).toLowerCase();};const toStringArray = (value: unknown): string[] =>Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [];+function identitiesIntersect(candidates: string[], actual: string[], resolve?: LidResolver): boolean {+ const literal = new Set(candidates.map(v => canonicalInput(v)));+ const lidPhones = new Set(candidates.filter(v => parseWaId(v).kind === 'lid').map(v => canonicalInput(v, resolve)));+ return actual.some(jid => {+ const key = canonicalActor(jid);+ if (literal.has(key)) return true;+ const kind = parseWaId(jid).kind;+ // A reported pair bridges LID and phone, never two different LIDs sharing a phone.+ if (kind === 'lid') return literal.has(canonicalActor(jid, resolve));+ return kind === 'user' && lidPhones.has(key);+ });+}+/** Read the current aliases once for both sides of the id conditions, rather than a resident mirror. */export async function prepareFilterLidResolver(filters: readonly (WebhookFilters | null | undefined)[],@@ -85,9 +90,8 @@ function evaluateCondition(switch (def.kind) {case 'id': {- const candidates = new Set(toStringArray(value).map(v => canonicalInput(v, resolve)));- const actual = typeof resolved === 'string' ? resolved : undefined;- const isMatch = actual != null && candidates.has(canonicalActor(actual, resolve));+ const actual = typeof resolved === 'string' ? [resolved] : [];+ const isMatch = identitiesIntersect(toStringArray(value), actual, resolve);return operator === 'isNot' ? !isMatch : isMatch;}@@ -99,9 +103,7 @@ function evaluateCondition(}case 'idArray': {- const candidates = new Set(toStringArray(value).map(v => canonicalInput(v, resolve)));- const actual = toStringArray(resolved).map(jid => canonicalActor(jid, resolve));- const intersects = actual.some(v => candidates.has(v));+ const intersects = identitiesIntersect(toStringArray(value), toStringArray(resolved), resolve);return operator === 'isNot' ? !intersects : intersects;}diff --git a/src/modules/webhook/filters/filter-identity.spec.ts b/src/modules/webhook/filters/filter-identity.spec.tsindex a916cb489..39b634b34 100644--- a/src/modules/webhook/filters/filter-identity.spec.ts+++ b/src/modules/webhook/filters/filter-identity.spec.ts@@ -26,10 +26,10 @@ import { WebhookFilters } from './filter-types';const LID = '484848@lid';const P = '[email protected]';const Q = '[email protected]';-const filtersFor = (jid: string): WebhookFilters => ({- conditions: [{ field: 'sender', operator: 'is', value: [jid] }],+const filtersFor = (jid: string, field = 'sender', operator: 'is' | 'isNot' = 'is'): WebhookFilters => ({+ conditions: [{ field, operator, value: [jid] }],});-const message = { from: LID, to: '[email protected]', chatId: LID, body: 'hello', type: 'text' };+const message = { from: LID, to: '[email protected]', chatId: LID, mentionedIds: [LID], body: 'hello', type: 'text' };describe('Identity readers after a peer changes a mapping', () => {let db: DataSource;@@ -54,7 +54,7 @@ describe('Identity readers after a peer changes a mapping', () => {await db.destroy();});- async function webhookMatches(jid: string): Promise<Webhook[]> {+ async function webhookMatches(jid: string, field = 'sender', operator: 'is' | 'isNot' = 'is'): Promise<Webhook[]> {const delivery = new WebhookDeliveryService({} as Repository<Webhook>,{} as Repository<WebhookDeliveryFailure>,@@ -68,17 +68,20 @@ describe('Identity readers after a peer changes a mapping', () => {filterMatchingWebhooks: (rows: Webhook[], event: string, data: Record<string, unknown>) => Promise<Webhook[]>;}).filterMatchingWebhooks(- [{ id: 'w', events: ['message.received'], filters: filtersFor(jid) } as Webhook],+ [{ id: 'w', events: ['message.received'], filters: filtersFor(jid, field, operator) } as Webhook],'message.received',message,);}- async function automationSends(jid: string): Promise<jest.Mock> {+ async function automationSends(jid: string, field = 'sender', operator: 'is' | 'isNot' = 'is'): Promise<jest.Mock> {const sendText = jest.fn().mockResolvedValue({});const rules = new AutomationRulesService({- find: () => Promise.resolve([{ id: 'r', conditions: filtersFor(jid), replyText: 'reply', cooldownSeconds: 0 }]),+ find: () =>+ Promise.resolve([+ { id: 'r', conditions: filtersFor(jid, field, operator), replyText: 'reply', cooldownSeconds: 0 },+ ]),} as unknown as Repository<AutomationRule>,{} as Repository<Session>,{ get: () => ({ sendText }) } as unknown as ModuleRef,@@ -150,4 +153,21 @@ describe('Identity readers after a peer changes a mapping', () => {expect(await pluginCapability().canonicalChatId('s', LID)).toBe(P);expect(await pluginCapability().canonicalChatId('s', Q)).toBe(Q);});++ it.each([+ ['sender', 'is'],+ ['sender', 'isNot'],+ ['mentions', 'is'],+ ['mentions', 'isNot'],+ ] as const)('keeps distinct reported LIDs separate for %s %s rules', async (field, operator) => {+ const other = '595959@lid';+ await peer.remember('595959', '628111', 'peer');+ const matches = operator === 'is' ? 0 : 1;+ expect(await webhookMatches(other, field, operator)).toHaveLength(matches);+ expect(await automationSends(other, field, operator)).toHaveBeenCalledTimes(matches);+ expect(await webhookMatches(P, field)).toHaveLength(1);+ expect(await automationSends(P, field)).toHaveBeenCalledTimes(1);+ expect(await webhookMatches(LID, field)).toHaveLength(1);+ expect(await automationSends(LID, field)).toHaveBeenCalledTimes(1);+ });});