Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): match group authors in the from-filter and scope JID candidates by chat kind (#931)

Yudhi Armyndharis1ecceab71d1f
diff --git a/openapi.json b/openapi.json
index 9f018c901..e8956a471 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1289,7 +1289,7 @@
"name": "from",
"required": false,
"in": "query",
- "description": "Filter by sender. A phone also matches messages from a lid that resolves to it.",
+ "description": "Filter by sender. A phone also matches group messages via the author field and any lid that resolves to it.",
"schema": {
"type": "string"
}
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 61eb433dd..7637a6223 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -33,7 +33,8 @@ export class MessageController {
@ApiQuery({
name: 'from',
required: false,
- description: 'Filter by sender. A phone also matches messages from a lid that resolves to it.',
+ description:
+ 'Filter by sender. A phone also matches group messages via the author field and any lid that resolves to it.',
})
@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max messages to return (default 50)' })
@ApiQuery({ name: 'offset', required: false, type: Number, description: 'Offset for pagination' })
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index a0a490ace..cd610cde2 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -41,7 +41,7 @@ describe('MessageService', () => {
let sessionService: jest.Mocked<Partial<SessionService>>;
let hookManager: jest.Mocked<Partial<HookManager>>;
let templateService: jest.Mocked<Partial<TemplateService>>;
- let lidMappingStore: { lidsForPhone: jest.Mock };
+ let lidMappingStore: { lidsForPhone: jest.Mock; getCached: jest.Mock };
let mockEngine: ReturnType<typeof createMockEngine>;
// Auto-typing is on by default; disable it for the unrelated send tests so they don't incur the
@@ -84,7 +84,7 @@ describe('MessageService', () => {
resolve: jest.fn(),
};
- lidMappingStore = { lidsForPhone: jest.fn().mockReturnValue([]) };
+ lidMappingStore = { lidsForPhone: jest.fn().mockReturnValue([]), getCached: jest.fn().mockReturnValue(undefined) };
const module: TestingModule = await Test.createTestingModule({
providers: [
@@ -584,21 +584,30 @@ describe('MessageService', () => {
const dmRow = { id: 'm-dm', from: '[email protected]', chatId: '[email protected]' } as Message;
const rows = [lidRow, dmRow];
- // A query-builder fake that actually filters by the `from IN (:...froms)` clause it receives, so the
- // test exercises the resolution-driven expansion end to end (filter -> rows returned).
+ // A query-builder fake that actually filters by the `(from IN (:...froms) OR author IN (:...authorFroms))`
+ // clause it receives, so the test exercises the resolution-driven expansion end to end (filter -> rows).
const makeFilteringQb = () => {
let froms: string[] | null = null;
+ let authorFroms: string[] | null = null;
const qb = {
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
- andWhere: jest.fn().mockImplementation((_clause: string, params?: { froms?: string[] }) => {
- if (params?.froms) froms = params.froms;
- return qb;
- }),
+ andWhere: jest
+ .fn()
+ .mockImplementation((_clause: string, params?: { froms?: string[]; authorFroms?: string[] }) => {
+ if (params?.froms) froms = params.froms;
+ if (params?.authorFroms) authorFroms = params.authorFroms;
+ return qb;
+ }),
getManyAndCount: jest.fn().mockImplementation(() => {
- const matched = froms ? rows.filter(r => froms!.includes(r.from)) : rows;
+ const matched =
+ froms || authorFroms
+ ? rows.filter(
+ r => froms?.includes(r.from) || (r.author != null && (authorFroms?.includes(r.author) ?? false)),
+ )
+ : rows;
return Promise.resolve([matched, matched.length]);
}),
};
@@ -627,6 +636,166 @@ describe('MessageService', () => {
});
});
+ // ── getMessages from-filter matches the group author ──────────────
+ describe('getMessages from-filter matches the group author', () => {
+ // Group rows: `from` holds the group JID; the real sender lives in `author`.
+ const aliceGroupRow = { id: 'm-grp-alice', from: '[email protected]', author: '[email protected]', chatId: '[email protected]' } as Message;
+ const bobGroupRow = { id: 'm-grp-bob', from: '[email protected]', author: '[email protected]', chatId: '[email protected]' } as Message;
+ const aliceDmRow = { id: 'm-dm', from: '[email protected]', chatId: '[email protected]' } as Message;
+ // A query-builder fake applying the chatId AND (from OR author) predicates like the real SQL.
+ const makeAuthorQb = (rows: Message[]) => {
+ let chatIds: string[] | null = null;
+ let froms: string[] | null = null;
+ let authorFroms: string[] | null = null;
+ const qb = {
+ where: jest.fn().mockReturnThis(),
+ orderBy: jest.fn().mockReturnThis(),
+ skip: jest.fn().mockReturnThis(),
+ take: jest.fn().mockReturnThis(),
+ andWhere: jest
+ .fn()
+ .mockImplementation(
+ (_clause: string, params?: { chatIds?: string[]; froms?: string[]; authorFroms?: string[] }) => {
+ if (params?.chatIds) chatIds = params.chatIds;
+ if (params?.froms) froms = params.froms;
+ if (params?.authorFroms) authorFroms = params.authorFroms;
+ return qb;
+ },
+ ),
+ getManyAndCount: jest.fn().mockImplementation(() => {
+ let matched = rows;
+ if (chatIds) matched = matched.filter(r => chatIds!.includes(r.chatId));
+ if (froms || authorFroms) {
+ matched = matched.filter(
+ r => froms?.includes(r.from) || (r.author != null && (authorFroms?.includes(r.author) ?? false)),
+ );
+ }
+ return Promise.resolve([matched, matched.length]);
+ }),
+ };
+ return qb;
+ };
+
+ it('returns group messages authored by the filtered phone (matched via author, not from)', async () => {
+ lidMappingStore.lidsForPhone.mockReturnValue([]);
+ const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow]);
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ const { messages } = await service.getMessages('sess-1', { from: '628999' });
+
+ // Alice's group row + her DM; Bob's group row (same `from` = group JID) stays out.
+ expect(messages.map(m => m.id).sort()).toEqual(['m-dm', 'm-grp-alice']);
+ });
+
+ it('matches a group author stored as a lid once the table maps the lid to the phone', async () => {
+ const lidAuthorRow = { id: 'm-grp-lid', from: '[email protected]', author: '111@lid', chatId: '[email protected]' } as Message;
+ lidMappingStore.lidsForPhone.mockReturnValue(['111']); // table: lid 111 -> phone 628999
+ const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow, lidAuthorRow]);
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ const { messages } = await service.getMessages('sess-1', { from: '628999' });
+
+ expect(messages.map(m => m.id).sort()).toEqual(['m-dm', 'm-grp-alice', 'm-grp-lid']);
+ });
+
+ it('still applies the chatId filter alongside the from/author match', async () => {
+ lidMappingStore.lidsForPhone.mockReturnValue([]);
+ const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow]);
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ const { messages } = await service.getMessages('sess-1', { chatId: '[email protected]', from: '628999' });
+
+ // Alice's DM is excluded by the chatId filter, Bob's row by the from/author filter.
+ expect(messages.map(m => m.id)).toEqual(['m-grp-alice']);
+ });
+ });
+
+ // ── candidate expansion is scoped by chat kind ────────────────────
+ describe('getMessages candidate expansion is scoped by chat kind', () => {
+ // Captures the candidate arrays the service binds, so the scoping is asserted directly.
+ const makeCaptureQb = () => {
+ const captured: { chatIds?: string[]; froms?: string[]; authorFroms?: string[] } = {};
+ const qb = {
+ where: jest.fn().mockReturnThis(),
+ orderBy: jest.fn().mockReturnThis(),
+ skip: jest.fn().mockReturnThis(),
+ take: jest.fn().mockReturnThis(),
+ andWhere: jest
+ .fn()
+ .mockImplementation(
+ (_clause: string, params?: { chatIds?: string[]; froms?: string[]; authorFroms?: string[] }) => {
+ if (params?.chatIds) captured.chatIds = params.chatIds;
+ if (params?.froms) captured.froms = params.froms;
+ if (params?.authorFroms) captured.authorFroms = params.authorFroms;
+ return qb;
+ },
+ ),
+ getManyAndCount: jest.fn().mockResolvedValue([[], 0]),
+ };
+ return { qb, captured };
+ };
+
+ it('does not expand a group chatId into the user dialects (fail-closed on the literal id)', async () => {
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { chatId: '[email protected]' });
+
+ // No `[email protected]`/`@s.whatsapp.net` and no lid-table probe with the group's digits.
+ expect(captured.chatIds).toEqual(['[email protected]']);
+ expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
+ expect(lidMappingStore.getCached).not.toHaveBeenCalled();
+ });
+
+ it('does not expand a status broadcast or newsletter chatId', async () => {
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { chatId: 'status@broadcast' });
+ expect(captured.chatIds).toEqual(['status@broadcast']);
+
+ await service.getMessages('sess-1', { chatId: '12345@newsletter' });
+ expect(captured.chatIds).toEqual(['12345@newsletter']);
+
+ expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
+ });
+
+ it('forward-resolves a @lid from-filter to its phone instead of minting <lid-digits>@c.us', async () => {
+ lidMappingStore.getCached.mockReturnValue('628999'); // table: lid 111 -> phone 628999
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { from: '111@lid' });
+
+ expect(lidMappingStore.getCached).toHaveBeenCalledWith('111');
+ expect(captured.froms).toEqual(['111@lid', '[email protected]', '[email protected]']);
+ expect(captured.authorFroms).toEqual(captured.froms); // same candidates drive the author match
+ expect(captured.froms).not.toContain('[email protected]'); // the lid's digits are not a phone
+ expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unresolved @lid filter to the literal id only', async () => {
+ lidMappingStore.getCached.mockReturnValue(null); // known-unresolved
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { from: '111@lid' });
+
+ expect(captured.froms).toEqual(['111@lid']);
+ });
+
+ it('keeps the user-dialect expansion for a bare phone filter', async () => {
+ lidMappingStore.lidsForPhone.mockReturnValue(['111']);
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { from: '628999' });
+
+ expect(captured.froms).toEqual(['628999', '[email protected]', '[email protected]', '111@lid']);
+ expect(lidMappingStore.lidsForPhone).toHaveBeenCalledWith('628999');
+ });
+ });
+
// ── getMessages chatId filter is dialect-agnostic ─────────────────
describe('getMessages chatId filter matches across dialects', () => {
// A message stored with the raw @s.whatsapp.net chatId (e.g. an outbound send addressed by a raw id).
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 906a7cc42..f715ef0f2 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -14,14 +14,14 @@ import { TemplateService } from '../template/template.service';
import { renderTemplate } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
-import { userPart } from '../../engine/identity/wa-id';
+import { parseWaId } from '../../engine/identity/wa-id';
import { resolveFeatureFlags } from '../../config/feature-flags';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
export interface GetMessagesOptions {
chatId?: string;
- /** Filter by sender. A phone matches stored `@c.us`/`@s.whatsapp.net` ids AND any lid resolving to it. */
+ /** Filter by sender. A phone matches stored `@c.us`/`@s.whatsapp.net` ids AND any lid resolving to it. Group messages match on `author` (the real sender) as well as `from` (which holds the group JID). */
from?: string;
limit?: number;
offset?: number;
@@ -296,7 +296,17 @@ export class MessageService {
// Resolve the filter through the lid->phone table so a phone matches not just the stored
// `<phone>@c.us` id but also any lid that resolves to the same person - turning the prior
// silent miss (a lid-stored author vs a phone filter) into a hit.
- query.andWhere('message.from IN (:...froms)', { froms: this.resolveJidCandidates(from) });
+ // A group message stores the real sender in `author` (`from` holds the group JID), so match
+ // BOTH columns against the same candidate set or the filter skips every group message the
+ // person wrote. Query plan: neither `from` nor `author` is indexed - the predicate applies
+ // within the (sessionId, createdAt)-narrowed scan exactly as the from-only filter did, so the
+ // OR costs nothing the old plan didn't already pay. No new index: per-session narrowing
+ // dominates selectivity and a single btree cannot serve an OR across two columns anyway.
+ const froms = this.resolveJidCandidates(from);
+ query.andWhere('(message.from IN (:...froms) OR message.author IN (:...authorFroms))', {
+ froms,
+ authorFroms: froms,
+ });
}
const [messages, total] = await query.getManyAndCount();
@@ -304,12 +314,32 @@ export class MessageService {
}
/**
- * Expand a JID filter into every stored id that refers to the same chat/person: the literal input (so
- * an exact group/lid filter still matches), the user-part in both user dialects (`@c.us` /
+ * Expand a user JID filter into every stored id that refers to the same person: the literal input
+ * (so an exact lid filter still matches), the user-part in both user dialects (`@c.us` /
* `@s.whatsapp.net`), and every lid the resolution table maps to that phone.
+ *
+ * Scoped by chat kind. For a non-user kind (group/status/newsletter/broadcast) the stored id can
+ * only ever be the literal JID, so no candidates are generated: expanding a group or channel id's
+ * digits into the user dialects (or probing the lid table with them) could mis-resolve the filter
+ * onto an unrelated entity whose phone digits happen to match — fail closed on the literal id.
+ * A `@lid` input forward-resolves to its phone instead of minting `<lid-digits>@c.us` (the lid's
+ * digits are NOT a phone), so rows stored under the resolved form still match a raw-lid filter.
*/
private resolveJidCandidates(value: string): string[] {
- const phone = userPart(value);
+ const parsed = parseWaId(value);
+ if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {
+ return [value];
+ }
+ if (parsed.kind === 'lid') {
+ const candidates = new Set<string>([value]);
+ const resolved = this.lidMappingStore.getCached(parsed.userPart);
+ if (resolved) {
+ candidates.add(`${resolved}@c.us`);
+ candidates.add(`${resolved}@s.whatsapp.net`);
+ }
+ return [...candidates];
+ }
+ const phone = parsed.userPart;
const candidates = new Set<string>([value, `${phone}@c.us`, `${phone}@s.whatsapp.net`]);
for (const lid of this.lidMappingStore.lidsForPhone(phone)) {
candidates.add(`${lid}@lid`);