Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(search): match chat and sender filters against every id form
Yudhi Armyndharise5f20bfa8aaf
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 105101968..20025c845 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6516,10 +6516,10 @@ Search messages across sessions (active search provider).| ----------- | ------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `q` | string | **Yes** | — | Search term. Must be non-empty after trim; `400` for whitespace-only, over 1000 characters, or over 32 words (punctuation separates words, a symbol or emoji that stands apart counts as a word, a whitespace-separated word said again counts once). Passed to the active provider's native full-text matcher. || `sessionId` | string | No | — | Restrict to a single session id (intersected with the key's `allowedSessions` scope). |-| `chatId` | string | No | — | Restrict to a single chat id. For a key restricted to selected chats this must name an allowed chat (`403` otherwise), and its hits are additionally narrowed to the allowlist. |+| `chatId` | string | No | — | Restrict to a single chat id. A phone also matches the chat's other stored forms (the other user dialect and any lid that resolves to it). For a key restricted to selected chats this must name an allowed chat (`403` otherwise), and its hits are additionally narrowed to the allowlist. || `direction` | enum (`incoming` \| `outgoing`) | No | — | Filter by message direction. || `type` | string | No | — | Filter by stored message `type` (e.g. `text`, `image`, `video`). Compared against `messages.type`; not an enum validation, any string is accepted and unmatched values simply return no hits. |-| `from` | string | No | — | Filter by sender. |+| `from` | string | No | — | Filter by sender; matches `from` or a group message's `author`. A phone also matches any lid that resolves to it. || `dateFrom` | integer (epoch ms) | No | — | Inclusive lower bound on `timestamp`. A non-numeric value is rejected with `400`. || `dateTo` | integer (epoch ms) | No | — | Inclusive upper bound on `timestamp`. A non-numeric value is rejected with `400`. || `limit` | integer (≥ 1) | No | `50` | Max hits to return. Clamped to `SEARCH_LIMIT_MAX` (default `100`). A non-integer value is rejected with `400`. |diff --git a/openapi.json b/openapi.jsonindex c326052be..f83b1e9fd 100644--- a/openapi.json+++ b/openapi.json@@ -17836,7 +17836,7 @@"name": "chatId","required": false,"in": "query",- "description": "Restrict to a single chat id",+ "description": "Restrict to a single chat id. A phone also matches the chat's other stored forms (the other user dialect and any lid that resolves to it).","schema": {"type": "string"}@@ -17845,7 +17845,7 @@"name": "from","required": false,"in": "query",- "description": "Sender filter",+ "description": "Sender filter. Matches `from` or a group message's `author`; a phone also matches any lid that resolves to it.","schema": {"type": "string"}diff --git a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.tsindex 85a9f4189..a7022e2e6 100644--- a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts+++ b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts@@ -42,7 +42,7 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`);await ds.query(`CREATE TABLE "messages" (` +- `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "waMessageId" varchar, ` ++ `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "waMessageId" varchar, "author" varchar, ` +`"chatId" varchar NOT NULL, "from" varchar NOT NULL, "to" varchar NOT NULL, "body" text, ` +`"type" varchar NOT NULL DEFAULT 'text', "direction" varchar NOT NULL DEFAULT 'outgoing', ` +`"timestamp" bigint, "status" varchar NOT NULL DEFAULT 'sent', ` +@@ -153,6 +153,51 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';}});+ // A chat first stored under one dialect and later under another is one chat, and a group message keeps+ // the group in `from` and the person in `author`. The host passes the expanded forms; the count behind+ // a later page numbers the same bind parameters again.+ it('matches the stored dialects of a chat and a sender, and pages through them', async () => {+ const insert = (id: string, chatId: string, from: string, author: string | null, ts: number) =>+ ds.query(+ `INSERT INTO "messages" ("id","sessionId","chatId","from","author","to","body","timestamp") ` ++ `VALUES ($1,'s1',$2,$3,$4,'[email protected]','dialectprobe',$5)`,+ [id, chatId, from, author, ts],+ );+ await insert('d1', '[email protected]', '[email protected]', null, 10);+ await insert('d2', '[email protected]', '[email protected]', null, 11);+ await insert('d4', '[email protected]', '[email protected]', null, 13);+ const ids = (r: { hits: Array<{ messageId: string }> }) => r.hits.map(h => h.messageId).sort();++ const chat = { q: 'dialectprobe', chatId: '[email protected]' };+ const chatForms = ['[email protected]', '[email protected]'];+ expect(ids(await provider.search(chat))).toEqual(['d1']);+ const expandedChat = await provider.search({ ...chat, chatIdAliases: chatForms });+ expect(ids(expandedChat)).toEqual(['d1', 'd2']);+ const chatPage = await provider.search({ ...chat, chatIdAliases: chatForms, limit: 1, offset: 1 });+ expect(chatPage.hits).toHaveLength(1);+ expect(chatPage.total).toBe(2);++ const sender = { q: 'dialectprobe', from: '[email protected]', fromAliases: ['[email protected]', '[email protected]'] };+ expect(ids(await provider.search({ q: 'dialectprobe', from: '[email protected]' }))).toEqual(['d1']);+ expect(ids(await provider.search(sender))).toEqual(['d1', 'd2', 'd3']);+ const senderPage = await provider.search({ ...sender, limit: 1, offset: 2 });+ expect(senderPage.hits).toHaveLength(1);+ expect(senderPage.total).toBe(3);++ const combined = await provider.search({+ ...sender,+ sessionIds: ['s1'],+ chatId: '[email protected]',+ chatIdAliases: chatForms,+ limit: 1,+ offset: 1,+ });+ expect(combined.hits).toHaveLength(1);+ expect(combined.total).toBe(2);+ });+it('reports healthy', async () => {expect((await provider.health()).ok).toBe(true);});diff --git a/src/modules/auth/chat-scope.service.spec.ts b/src/modules/auth/chat-scope.service.spec.tsindex d78fe3447..262bd90e3 100644--- a/src/modules/auth/chat-scope.service.spec.ts+++ b/src/modules/auth/chat-scope.service.spec.ts@@ -55,6 +55,22 @@ describe('ChatScopeService', () => {expect(await svc.allows({ allowedChats: [`${LID}@lid`] }, `${PHONE}@c.us`)).toBe(true);});+ it('candidatesFor expands a phone and a lid through the directory, and always keeps the id as given', async () => {+ const svc = new ChatScopeService(fakeStore());++ const phone = await svc.candidatesFor(`${PHONE}@c.us`);+ expect(phone).toEqual(expect.arrayContaining([`${PHONE}@c.us`, `${PHONE}@s.whatsapp.net`, `${LID}@lid`]));++ const lid = await svc.candidatesFor(`${LID}@lid`);+ expect(lid).toEqual(expect.arrayContaining([`${LID}@lid`, `${PHONE}@c.us`]));++ // A spelling the expansion does not fold still names the rows stored under it.+ for (const spelling of ['[email protected]', '[email protected] ', '999@LID', '999:7@lid']) {+ expect(await svc.candidatesFor(spelling)).toContain(spelling);+ }+ expect(new Set(phone).size).toBe(phone.length);+ });+it('filters a list through the batched expansion, passing an unrestricted key through', async () => {const svc = new ChatScopeService(fakeStore());const rows = [{ id: '[email protected]' }, { id: `${LID}@lid` }, { id: '[email protected]' }];diff --git a/src/modules/auth/chat-scope.service.ts b/src/modules/auth/chat-scope.service.tsindex a8164289b..62a816d16 100644--- a/src/modules/auth/chat-scope.service.ts+++ b/src/modules/auth/chat-scope.service.ts@@ -1,7 +1,7 @@import { ForbiddenException, Injectable, Optional } from '@nestjs/common';import { ApiKey } from './entities/api-key.entity';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';-import { ContactDirectory } from '../../engine/identity/jid-candidates';+import { ContactDirectory, resolveJidCandidates } from '../../engine/identity/jid-candidates';import {ChatScope,ChatScopeDirectory,@@ -59,6 +59,17 @@ export class ChatScopeService {return chatIdAllowed(this.scopeFor(apiKey), chatId, this.singleDirectory());}+ /**+ * Every stored form of one chat or sender id: the neutral dialects of a phone plus the lids mapped to+ * it, or the phone behind a lid. The same expansion the message list applies to its `chatId` and `from`+ * filters, so a caller-supplied filter finds the same rows on every surface: the id as given is kept too,+ * because a row stored under a spelling the expansion does not fold (a group or lid id with another case or+ * device suffix) must still match the filter that names it.+ */+ async candidatesFor(id: string): Promise<string[]> {+ return [...new Set([id, ...(await resolveJidCandidates(id, this.singleDirectory()))])];+ }+/** The allowlist expanded once with the lid table (batched), for filtering a whole list. */scopeForFilter(apiKey?: Pick<ApiKey, 'allowedChats'> | null): Promise<ChatScope | null> {return buildExpandedChatScope(apiKey?.allowedChats ?? null, this.batchDirectory());diff --git a/src/modules/search/dto/search-query.dto.ts b/src/modules/search/dto/search-query.dto.tsindex 76b14c764..44375042b 100644--- a/src/modules/search/dto/search-query.dto.ts+++ b/src/modules/search/dto/search-query.dto.ts@@ -31,12 +31,18 @@ export class SearchQueryDto {@IsString()sessionId?: string;- @ApiPropertyOptional({ description: 'Restrict to a single chat id' })+ @ApiPropertyOptional({+ description:+ "Restrict to a single chat id. A phone also matches the chat's other stored forms (the other user dialect and any lid that resolves to it).",+ })@IsOptional()@IsString()chatId?: string;- @ApiPropertyOptional({ description: 'Sender filter' })+ @ApiPropertyOptional({+ description:+ "Sender filter. Matches `from` or a group message's `author`; a phone also matches any lid that resolves to it.",+ })@IsOptional()@IsString()from?: string;diff --git a/src/modules/search/providers/builtin-fts.provider.spec.ts b/src/modules/search/providers/builtin-fts.provider.spec.tsindex f62cb36db..33ae97316 100644--- a/src/modules/search/providers/builtin-fts.provider.spec.ts+++ b/src/modules/search/providers/builtin-fts.provider.spec.ts@@ -1,5 +1,5 @@import 'reflect-metadata';-import { DataSource } from 'typeorm';+import { DataSource, type QueryDeepPartialEntity } from 'typeorm';import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';import { Session } from '../../../modules/session/entities/session.entity';import { BuiltInFtsProvider } from './builtin-fts.provider';@@ -125,6 +125,83 @@ describe('BuiltInFtsProvider (sqlite)', () => {expect(page.total).toBe(1);});+ describe('chat and sender filters expanded by the host', () => {+ // One person, three stored forms: the same chat was first stored under a lid, later under each phone+ // dialect, and a group message keeps the group in `from` and the person in `author`.+ beforeEach(async () => {+ const insert = (row: QueryDeepPartialEntity<Message>): Promise<unknown> =>+ ds.getRepository(Message).insert({+ sessionId: 's1',+ to: '[email protected]',+ type: 'text',+ direction: MessageDirection.INCOMING,+ timestamp: 10,+ ...row,+ });+ await insert({ chatId: '[email protected]', from: '[email protected]', body: 'invoice via phone' });+ await insert({+ chatId: '[email protected]',+ from: '[email protected]',+ body: 'invoice via other dialect',+ });+ await insert({ chatId: '999@lid', from: '999@lid', body: 'invoice via lid' });+ await insert({ chatId: '[email protected]', from: '[email protected]', author: '[email protected]', body: 'invoice in a group' });+ await insert({ chatId: '[email protected]', from: '[email protected]', body: 'invoice from someone else' });+ });++ const bodies = async (filter: Omit<SearchQuery, 'q'>): Promise<string[]> =>+ (await provider.search({ q: 'invoice', ...filter })).hits.map(h => h.body).sort();++ it('finds a chat under every stored form of its id', async () => {+ const chatIdAliases = ['[email protected]', '[email protected]', '999@lid'];++ expect(await bodies({ chatId: '[email protected]' })).toEqual(['invoice via phone']);+ expect(await bodies({ chatId: '[email protected]', chatIdAliases })).toEqual([+ 'invoice via lid',+ 'invoice via other dialect',+ 'invoice via phone',+ ]);+ });++ it('matches a sender by its from column or, in a group, by its author', async () => {+ const fromAliases = ['[email protected]', '[email protected]', '999@lid'];++ expect(await bodies({ from: '[email protected]', fromAliases })).toEqual([+ 'invoice in a group',+ 'invoice via lid',+ 'invoice via other dialect',+ 'invoice via phone',+ ]);+ });++ it('still honours the key allowlist beside an expanded chat filter, in the page and in the total', async () => {+ const res = await provider.search({+ q: 'invoice',+ chatId: '[email protected]',+ chatIdAliases: ['[email protected]', '[email protected]', '999@lid'],+ chatIds: ['[email protected]'],+ limit: 1,+ offset: 0,+ });++ expect(res.hits.map(h => h.body)).toEqual(['invoice via other dialect']);+ expect(res.total).toBe(1);+ });++ it('counts the expanded filters too', async () => {+ const page = await provider.search({+ q: 'invoice',+ from: '[email protected]',+ fromAliases: ['[email protected]', '[email protected]', '999@lid'],+ limit: 1,+ offset: 1,+ });++ expect(page.hits).toHaveLength(1);+ expect(page.total).toBe(4);+ });+ });+it('scopes by sessionIds (auth) and by sessionId filter', async () => {const scoped = await provider.search({ q: 'hello', sessionIds: ['s1'] });expect(scoped.hits.every(h => h.sessionId === 's1')).toBe(true);diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsindex 27da680a4..a897771dd 100644--- a/src/modules/search/providers/builtin-fts.provider.ts+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -380,8 +380,16 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {params.push(q.sessionId);}if (q.chatId) {- where.push(`${prefix}"chatId" = ${ph()}`);- params.push(q.chatId);+ // Every stored form of the chat when the host expanded it (a chat first stored under a lid and later+ // under the phone is one chat, as in the message list), the literal id otherwise.+ if (q.chatIdAliases?.length) {+ const placeholders = q.chatIdAliases.map(() => ph()).join(',');+ where.push(`${prefix}"chatId" IN (${placeholders})`);+ params.push(...q.chatIdAliases);+ } else {+ where.push(`${prefix}"chatId" = ${ph()}`);+ params.push(q.chatId);+ }}if (q.chatIds?.length === 0) where.push('1 = 0');else if (q.chatIds) {@@ -390,8 +398,16 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {params.push(...q.chatIds);}if (q.from) {- where.push(`${prefix}"from" = ${ph()}`);- params.push(q.from);+ if (q.fromAliases?.length) {+ // A group message keeps the group id in `from` and the person in `author`, so both are matched.+ const asSender = q.fromAliases.map(() => ph()).join(',');+ const asAuthor = q.fromAliases.map(() => ph()).join(',');+ where.push(`(${prefix}"from" IN (${asSender}) OR ${prefix}"author" IN (${asAuthor}))`);+ params.push(...q.fromAliases, ...q.fromAliases);+ } else {+ where.push(`${prefix}"from" = ${ph()}`);+ params.push(q.from);+ }}if (q.direction) {where.push(`${prefix}"direction" = ${ph()}`);diff --git a/src/modules/search/providers/plugin-search-provider.spec.ts b/src/modules/search/providers/plugin-search-provider.spec.tsindex 632fd508e..1e3923b11 100644--- a/src/modules/search/providers/plugin-search-provider.spec.ts+++ b/src/modules/search/providers/plugin-search-provider.spec.ts@@ -29,6 +29,26 @@ describe('PluginSearchProvider', () => {expect(dispatchSearch).toHaveBeenCalledWith({ query: { q: 'hi' }, timeoutMs: 7000 });});+ it('keeps the host-expanded id lists out of the query a plugin receives', async () => {+ const dispatchSearch = jest+ .fn()+ .mockResolvedValue({ ok: true, results: { hits: [], total: 0, tookMs: 1, provider: 'plugin:p' } });+ const p = new PluginSearchProvider('p', 'P', fakeTransport({ dispatchSearch }), 1000);++ await p.search({+ q: 'hi',+ chatId: '[email protected]',+ chatIdAliases: ['[email protected]', '999@lid'],+ from: '[email protected]',+ fromAliases: ['[email protected]'],+ });++ expect(dispatchSearch).toHaveBeenCalledWith({+ query: { q: 'hi', chatId: '[email protected]', from: '[email protected]' },+ timeoutMs: 1000,+ });+ });+it('search throws a 503 ServiceUnavailableException carrying the cause on ok:false', async () => {const transport = fakeTransport({dispatchSearch: jest.fn().mockResolvedValue({ ok: false, error: 'backend down' }),diff --git a/src/modules/search/providers/plugin-search-provider.ts b/src/modules/search/providers/plugin-search-provider.tsindex 3defa04b5..de12321b5 100644--- a/src/modules/search/providers/plugin-search-provider.ts+++ b/src/modules/search/providers/plugin-search-provider.ts@@ -86,7 +86,12 @@ export class PluginSearchProvider implements SearchProvider {// Filtering an already paginated plugin response cannot enforce scoped offsets or counts.throw new ForbiddenException('Chat-restricted search requires the built-in search provider');}- const reply = await this.transport.dispatchSearch({ query, timeoutMs: this.timeoutMs });+ // The expanded id lists are the built-in provider's business; a plugin keeps the query shape it was+ // written against (`chatId` and `from` as the caller sent them).+ const pluginQuery: SearchQuery = { ...query };+ delete pluginQuery.chatIdAliases;+ delete pluginQuery.fromAliases;+ const reply = await this.transport.dispatchSearch({ query: pluginQuery, timeoutMs: this.timeoutMs });if (!reply.ok) throw new ServiceUnavailableException(reply.error);// The result shape is untrusted wire data: reject an invalid payload with an honest 502 (bad// upstream) instead of fabricating a 200 — or crashing the re-filter below into a 500.diff --git a/src/modules/search/search.controller.ts b/src/modules/search/search.controller.tsindex 95cea2c76..b06087649 100644--- a/src/modules/search/search.controller.ts+++ b/src/modules/search/search.controller.ts@@ -46,10 +46,20 @@ export class SearchController {description: 'Search term (required, non-empty, at most 1000 characters and 32 words)',})@ApiQuery({ name: 'sessionId', required: false, description: 'Restrict to a single session' })- @ApiQuery({ name: 'chatId', required: false, description: 'Restrict to a single chat id' })+ @ApiQuery({+ name: 'chatId',+ required: false,+ description:+ "Restrict to a single chat id. A phone also matches the chat's other stored forms (the other user dialect and any lid that resolves to it).",+ })@ApiQuery({ name: 'direction', required: false, description: 'incoming | outgoing' })@ApiQuery({ name: 'type', required: false, description: 'Message type filter' })- @ApiQuery({ name: 'from', required: false, description: 'Sender filter' })+ @ApiQuery({+ name: 'from',+ required: false,+ description:+ "Sender filter. Matches `from` or a group message's `author`; a phone also matches any lid that resolves to it.",+ })@ApiQuery({ name: 'dateFrom', required: false, description: 'Epoch-ms lower bound (inclusive)' })@ApiQuery({ name: 'dateTo', required: false, description: 'Epoch-ms upper bound (inclusive)' })@ApiQuery({ name: 'limit', required: false, type: 'integer', description: 'Max hits to return' })diff --git a/src/modules/search/search.service.spec.ts b/src/modules/search/search.service.spec.tsindex 72ddbdb47..e3d6e00f9 100644--- a/src/modules/search/search.service.spec.ts+++ b/src/modules/search/search.service.spec.ts@@ -3,6 +3,7 @@ import { SearchService } from './search.service';import { SearchProviderRegistry } from './search-provider.registry';import { SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX, SEARCH_OFFSET_MAX, SEARCH_TERMS_MAX } from './search.constants';import type { SearchProvider, SearchResults } from './search.types';+import type { ChatScopeService } from '../auth/chat-scope.service';function mkProvider(id: string, search: SearchProvider['search']): SearchProvider {return {@@ -51,6 +52,70 @@ describe('SearchService', () => {expect(search).toHaveBeenCalledWith(expect.objectContaining({ chatIds: ['[email protected]', '111@lid'] }));});+ describe('chat and sender filters', () => {+ const lidAware = (): Pick<ChatScopeService, 'candidatesFor'> => ({+ candidatesFor: jest.fn((id: string) =>+ Promise.resolve(id === '[email protected]' ? ['[email protected]', '[email protected]', '999@lid'] : [id]),+ ),+ });++ it('hands the provider every stored form of the ids, expanded by the host', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg, lidAware() as ChatScopeService);++ await svc.search({ q: 'x', chatId: '[email protected]', from: '[email protected]' });++ expect(search).toHaveBeenCalledWith(+ expect.objectContaining({+ chatId: '[email protected]',+ chatIdAliases: ['[email protected]', '[email protected]', '999@lid'],+ from: '[email protected]',+ fromAliases: ['[email protected]'],+ }),+ );+ });++ it('expands nothing when the query names neither a chat nor a sender', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const chatScope = lidAware();+ const svc = new SearchService(reg, chatScope as ChatScopeService);++ await svc.search({ q: 'x' });++ expect(chatScope.candidatesFor).not.toHaveBeenCalled();+ expect(search).toHaveBeenCalledWith(+ expect.objectContaining({ chatIdAliases: undefined, fromAliases: undefined }),+ );+ });++ it('does not let a caller supply the expanded lists', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));+ const svc = new SearchService(reg, lidAware() as ChatScopeService);++ await svc.search({ q: 'x', chatId: '[email protected]', chatIdAliases: ['[email protected]'], fromAliases: ['[email protected]'] });++ const [query] = search.mock.calls[0] as [{ chatIdAliases?: string[]; fromAliases?: string[] }];+ expect(query.chatIdAliases).not.toContain('[email protected]');+ expect(query.fromAliases).toBeUndefined();+ });++ it('leaves the filters literal when no lid table is available', async () => {+ const reg = new SearchProviderRegistry();+ const search = jest.fn().mockResolvedValue(emptyResults);+ reg.register(mkProvider('builtin-fts', search));++ await new SearchService(reg).search({ q: 'x', chatId: '[email protected]' });++ expect(search).toHaveBeenCalledWith(expect.objectContaining({ chatId: '[email protected]', chatIdAliases: undefined }));+ });+ });+it('refuses a query of more than SEARCH_TERMS_MAX words before any provider runs it', async () => {const reg = new SearchProviderRegistry();const search = jest.fn().mockResolvedValue(emptyResults);diff --git a/src/modules/search/search.service.ts b/src/modules/search/search.service.tsindex 5b3974a45..7eb5e5728 100644--- a/src/modules/search/search.service.ts+++ b/src/modules/search/search.service.ts@@ -1,12 +1,18 @@-import { BadRequestException, Injectable, NotImplementedException } from '@nestjs/common';+import { BadRequestException, Injectable, NotImplementedException, Optional } from '@nestjs/common';import { SearchProviderRegistry } from './search-provider.registry';import { SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX, SEARCH_OFFSET_MAX, SEARCH_TERMS_MAX } from './search.constants';import { searchTermCount } from './search-terms';import type { SearchQuery, SearchResults } from './search.types';+import { ChatScopeService } from '../auth/chat-scope.service';@Injectable()export class SearchService {- constructor(private readonly registry: SearchProviderRegistry) {}+ constructor(+ private readonly registry: SearchProviderRegistry,+ // Provided by the global AuthModule. Optional so the service still builds in a unit test without it;+ // the chat and sender filters then match the stored id literally.+ @Optional() private readonly chatScope?: ChatScopeService,+ ) {}async search(query: SearchQuery, callerSessionIds?: string[], callerChatIds?: string[]): Promise<SearchResults> {const provider = this.registry.active();@@ -22,8 +28,16 @@ export class SearchService {// (built-in + plugin) receives capped values: the built-in re-clamps in its own SQL, but a// plugin would otherwise receive the raw caller value and could pressure host heap by// returning an oversized page.+ // The chat and sender filters match every stored form of the id, as the message list does: a chat first+ // stored under a lid and later under the phone is one chat. Host-set, never taken from the caller.+ const [chatIdAliases, fromAliases] = await Promise.all([+ query.chatId ? this.chatScope?.candidatesFor(query.chatId) : undefined,+ query.from ? this.chatScope?.candidatesFor(query.from) : undefined,+ ]);const scoped: SearchQuery = {...query,+ chatIdAliases,+ fromAliases,sessionIds: callerSessionIds,chatIds: callerChatIds,limit: Math.min(query.limit ?? SEARCH_DEFAULT_LIMIT, SEARCH_LIMIT_MAX),diff --git a/src/modules/search/search.types.ts b/src/modules/search/search.types.tsindex 1a43c7b6d..87bf67c02 100644--- a/src/modules/search/search.types.ts+++ b/src/modules/search/search.types.ts@@ -26,9 +26,17 @@ export interface SearchQuery {chatIds?: string[];sessionId?: string;chatId?: string;+ /**+ * Host-set: every stored form of `chatId` (both user dialects and the lids mapped to the phone), so the+ * built-in filter finds the chat the message list does. Not part of the plugin provider contract: it is+ * stripped before a plugin sees the query.+ */+ chatIdAliases?: string[];direction?: MessageDirection;type?: MessageType | MessageType[];from?: string;+ /** Host-set, like `chatIdAliases`: every stored form of `from`, matched against the sender and the author. */+ fromAliases?: string[];dateFrom?: number; // epoch msdateTo?: number; // epoch mslimit?: number;