Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Merge branch 'main' into feat/api-key-allowed-chats
Yudhi Armyndhariseecbf2e8a512
diff --cc openapi.jsonindex f5305b924,cda621902..0e1b8fd7d--- a/openapi.json+++ b/openapi.json@@@ -3182,6 -3197,97 +3197,103 @@@]}},+ "/api/sessions/{sessionId}/messages/batch/{batchId}": {+ "get": {+ "operationId": "MessageController_getBatchStatus",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "batchId",+ "required": true,+ "in": "path",+ "description": "Batch ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Batch status and progress",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchStatusResponseDto"+ }+ }+ }+ },++ "403": {++ "description": "The calling key is restricted with `allowedChats`. A batch row has no key owner, so the status cannot be checked against the key's allowlist and a chat-restricted key is refused; use the single-send routes instead."++ },+ "404": {+ "description": "Batch not found"+ }+ },+ "summary": "Get batch processing status",+ "tags": [+ "messages"+ ]+ }+ },+ "/api/sessions/{sessionId}/messages/batch/{batchId}/cancel": {+ "post": {+ "operationId": "MessageController_cancelBatch",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "batchId",+ "required": true,+ "in": "path",+ "description": "Batch ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Batch cancelled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchCancelResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Batch already completed, cancelled, or failed (terminal statuses are exclusive)"+ },++ "403": {++ "description": "The calling key is restricted with `allowedChats`. A batch row has no key owner, so the cancel cannot be checked against the key's allowlist and a chat-restricted key is refused."++ },+ "404": {+ "description": "Batch not found"+ }+ },+ "summary": "Cancel a running batch",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/{chatId}/history": {"get": {"description": "Reads messages directly from the WhatsApp client for the given chat, bypassing the local DB. Useful for retrieving messages that arrived before the gateway was started.",diff --cc src/engine/identity/lid-mapping-store.service.tsindex 9320b8bf6,0a57c23d6..2662a270f--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@@ -8,22 -8,10 +8,23 @@@ import { resolveNonNegativeIntEnv } fro// Default cap on the in-memory lid->phone mirror. Every other long-lived map in the engine surface is// bounded (the per-session lidPhoneCache is 5000); the LID mirror was the lone exception. A miss falls- // back to engine re-resolution, so the cap trades a re-resolution for bounded memory, never data loss.+ // back to engine re-resolution (a reverse lookup reads the table), so the cap trades a re-resolution for+ // bounded memory, never data loss.export const LID_MAPPING_CACHE_DEFAULT = 5000;+/**+ * SQLite binds at most 32766 variables in one statement (Postgres 65535), so an `IN (...)` over a+ * large allowlist is chunked. Small enough to stay well inside both, large enough that a realistic+ * allowlist is one round trip.+ */+const LID_QUERY_CHUNK = 500;++function chunk<T>(items: T[], size = LID_QUERY_CHUNK): T[][] {+ const out: T[][] = [];+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));+ return out;+}+/*** Narrow read/write port over the `lid -> phone` table. The Baileys session store depends on this (sync* reads on the resolution hot path + write-through) and the message from-filter depends on the reverse@@@ -161,79 -151,44 +164,104 @@@ export class LidMappingStoreService impreturn set ? [...set] : [];}+ /**- * Deterministic forward lookup for authorization paths (the API-key chat fence): the in-memory- * cache first, then the persisted table. The cache alone is NOT enough there — it is LRU-evicted- * at `LID_MAPPING_CACHE_MAX`, so a cache-only answer would let the same key and chat pass or fail- * depending on cache residency. The table is the source of truth and is consulted on every miss.++ * Deterministic forward lookup for authorization paths (the API-key chat fence): the persisted++ * table first, the in-memory mirror only when the table read fails or has no row. The mirror alone++ * is not enough there: it is LRU-evicted at `LID_MAPPING_CACHE_MAX` and can hold a stale negative++ * for a lid another node has since mapped, so a cache-first answer would let the same key and chat++ * pass or fail depending on cache residency. {@link findPhoneForLid} is the cache-first variant.+ */+ async resolveLidPersisted(jid: string): Promise<string | null> {+ const lid = userPart(jid);- // The TABLE is authoritative, not the mirror: a node can hold a stale negative for a lid another- // node has since mapped, and answering from the cache would refuse a chat the table admits.+ try {+ const row = await this.repo.findOne({ where: { lid } });+ if (row) return row.phone;+ } catch {+ // The table may not exist yet (migration pending); fall back to the mirror.+ }+ return this.getCached(lid) ?? null;+ }+- /** Deterministic reverse lookup, companion to {@link resolveLidPersisted}: cache ∪ persisted table. */- async lidsForPhonePersisted(phone: string): Promise<string[]> {- const lids = new Set<string>(this.lidsForPhone(phone));+ /**+ * Reverse lookup that also reads the table. {@link lidsForPhone} only sees lids resident in the+ * forward cache, and nothing phone-keyed ever warms it, so a mapping past the preload cap or+ * evicted by the LRU would stay invisible to a phone filter for good. For callers that can await+ * (the message and status filters, the handover gate). Table rows are not indexed into the cache,+ * so a list query cannot evict hot forward entries. A lid this process has since re-mapped+ * elsewhere is skipped (last-write-wins), and a read error falls back to the cache alone.+ */+ async findLidsForPhone(phone: string): Promise<string[]> {+ const lids = new Set(this.lidsForPhone(phone));try {- const rows = await this.repo.find({ where: { phone } });- for (const row of rows) lids.add(row.lid);- } catch {- // The table may not exist yet (migration pending); the cache is the best available answer.+ const rows = await this.repo.find({ select: { lid: true }, where: { phone } });+ for (const { lid } of rows) {+ const cached = this.lidToPhone.get(lid);+ if (cached === undefined || cached === phone) lids.add(lid);+ }+ } catch (err) {+ this.logger.warn(`Could not read lids for a phone: ${err instanceof Error ? err.message : String(err)}`);}return [...lids];}+ /**+ * Batched forward lookup for a list filter: lid user-part -> phone digits. Chunked queries for the+ * whole allowlist instead of one per entry, and the TABLE wins over the mirror so a stale cached+ * negative cannot shadow a mapping another node persisted.+ */+ async phonesForLidsPersisted(lids: string[]): Promise<Record<string, string | null>> {+ const out: Record<string, string | null> = {};+ if (lids.length === 0) return out;+ for (const lid of lids) out[lid] = this.getCached(lid) ?? null;+ try {+ for (const batch of chunk(lids)) {+ const rows = await this.repo.find({ where: { lid: In(batch) } });+ // The table WINS: a stale cached negative must not shadow a mapping another node persisted.+ for (const row of rows) out[row.lid] = row.phone;+ }+ } catch {+ // The table may not exist yet (migration pending); the mirror is the best available answer.+ }+ return out;+ }++ /** Batched reverse lookup, companion to {@link phonesForLidsPersisted}: phone digits -> lids. */+ async lidsForPhonesPersisted(phones: string[]): Promise<Record<string, string[]>> {+ const out: Record<string, string[]> = {};+ if (phones.length === 0) return out;+ for (const phone of phones) out[phone] = this.lidsForPhone(phone);+ try {+ for (const batch of chunk(phones)) {+ const rows = await this.repo.find({ where: { phone: In(batch) } });+ for (const row of rows) {+ if (!row.phone) continue;+ const list = out[row.phone] ?? [];+ if (!list.includes(row.lid)) list.push(row.lid);+ out[row.phone] = list;+ }+ }+ } catch {+ // The table may not exist yet (migration pending); the cache is the best available answer.+ }+ return out;+ }++ /**+ * Forward lookup that reads the table on a cache miss, for callers that can await (the handover+ * gate). {@link getCached} answers a miss with undefined and only warms in the background, which+ * is exactly when a mapping past the cap or evicted matters. Like {@link findLidsForPhone}, the row+ * is not indexed, and a read error answers null.+ */+ async findPhoneForLid(lid: string): Promise<string | null> {+ if (this.lidToPhone.has(lid)) return this.getCached(lid) ?? null;+ try {+ return (await this.repo.findOne({ where: { lid } }))?.phone ?? null;+ } catch (err) {+ this.logger.warn(`Could not read the phone for a lid: ${err instanceof Error ? err.message : String(err)}`);+ return null;+ }+ }+async remember(lid: string, phone: string | null, sessionId?: string): Promise<void> {if (!lid || this.lidToPhone.get(lid) === phone) {return; // unseen-or-changed only; a no-op write would just churn updatedAtdiff --cc src/engine/identity/lid-mapping-store.spec.tsindex c5cd6ea1a,1931cb67c..c9c2c8a2c--- a/src/engine/identity/lid-mapping-store.spec.ts+++ b/src/engine/identity/lid-mapping-store.spec.ts@@@ -403,127 -449,3 +449,127 @@@ describe('LidMappingStoreService — deexpect(store.getCached('lid-a')).toBeUndefined();});});++describe('LidMappingStoreService — deterministic persisted lookups (authorization path)', () => {+ it('resolveLidPersisted answers from the cache when warm', async () => {+ const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);+ const store = await newStore(repo);+ expect(await store.resolveLidPersisted('111@lid')).toBe('628999');+ });++ it('resolveLidPersisted reads the table for a lid evicted from the LRU cache', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '1';+ try {+ // Preload keeps one row; the other is persisted but not cached, so the table must answer.+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '222', phone: '628888' },+ ]);+ const store = await newStore(repo);+ expect(await store.resolveLidPersisted('111@lid')).toBe('628999');+ expect(await store.resolveLidPersisted('222@lid')).toBe('628888');+ } finally {+ delete process.env.LID_MAPPING_CACHE_MAX;+ }+ });++ it('a stale cached negative never shadows a mapping the table has', async () => {+ const repo = makeFakeRepo();+ const store = await newStore(repo);+ await store.remember('222', null); // this node cached a negative+ repo.rows[0].phone = '628888'; // another node has since mapped it in the table+ expect(await store.resolveLidPersisted('222@lid')).toBe('628888');+ expect(await store.phonesForLidsPersisted(['222'])).toEqual({ 222: '628888' });+ });++ it('resolveLidPersisted returns null for a lid with no persisted row', async () => {+ const repo = makeFakeRepo();+ const store = await newStore(repo);+ expect(await store.resolveLidPersisted('999@lid')).toBeNull();+ expect(repo.findOne).toHaveBeenCalledWith({ where: { lid: '999' } });+ });++ it('resolveLidPersisted fails soft (null) when the table read throws', async () => {+ const repo = makeFakeRepo();+ const store = await newStore(repo);+ repo.findOne.mockRejectedValueOnce(new Error('no such table'));+ expect(await store.resolveLidPersisted('555@lid')).toBeNull();+ });+- it('lidsForPhonePersisted reads the table for a lid evicted from the LRU cache', async () => {++ it('findLidsForPhone reads the table for a lid evicted from the LRU cache', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '1';+ try {+ // Preload keeps one of the two lids; the reverse map then holds only that one, so the second+ // can only come from the table.+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '222', phone: '628999' },+ ]);+ const store = await newStore(repo);- expect((await store.lidsForPhonePersisted('628999')).sort()).toEqual(['111', '222']);++ expect((await store.findLidsForPhone('628999')).sort()).toEqual(['111', '222']);+ } finally {+ delete process.env.LID_MAPPING_CACHE_MAX;+ }+ });+- it('lidsForPhonePersisted unions the cache with the persisted table', async () => {++ it('findLidsForPhone unions the cache with the persisted table', async () => {+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '222', phone: '628999' },+ ]);+ const store = await newStore(repo);- expect((await store.lidsForPhonePersisted('628999')).sort()).toEqual(['111', '222']);++ expect((await store.findLidsForPhone('628999')).sort()).toEqual(['111', '222']);+ });++ it('phonesForLidsPersisted reads the table for a lid evicted from the LRU cache', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '1';+ try {+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '222', phone: '628888' },+ ]);+ const store = await newStore(repo);+ expect(await store.phonesForLidsPersisted(['111', '222'])).toEqual({ 111: '628999', 222: '628888' });+ } finally {+ delete process.env.LID_MAPPING_CACHE_MAX;+ }+ });++ it('lidsForPhonesPersisted reads the table for a lid evicted from the LRU cache', async () => {+ process.env.LID_MAPPING_CACHE_MAX = '1';+ try {+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '222', phone: '628999' },+ ]);+ const store = await newStore(repo);+ expect((await store.lidsForPhonesPersisted(['628999']))['628999'].sort()).toEqual(['111', '222']);+ } finally {+ delete process.env.LID_MAPPING_CACHE_MAX;+ }+ });++ it('batched lookups handle an empty input, a null-phone row, and a read error', async () => {+ const repo = makeFakeRepo([+ { lid: '111', phone: '628999' },+ { lid: '333', phone: null },+ ]);+ const store = await newStore(repo);+ expect(await store.phonesForLidsPersisted([])).toEqual({});+ expect(await store.lidsForPhonesPersisted([])).toEqual({});+ // The null-phone row is skipped rather than indexed under a null key.+ expect((await store.lidsForPhonesPersisted(['628999']))['628999']).toEqual(['111']);+ // A read error falls back to the cache, which the preload filled.+ repo.find.mockRejectedValueOnce(new Error('no such table'));+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: '628999' });+ repo.find.mockRejectedValueOnce(new Error('no such table'));+ expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: ['111'] });+ });+- it('lidsForPhonePersisted falls back to the cache when the table read throws', async () => {++ it('findLidsForPhone falls back to the cache when the table read throws', async () => {+ const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);+ const store = await newStore(repo);+ repo.find.mockRejectedValueOnce(new Error('no such table'));- expect(await store.lidsForPhonePersisted('628999')).toEqual(['111']);++ expect(await store.findLidsForPhone('628999')).toEqual(['111']);+ });+});diff --cc src/modules/auth/chat-scope.service.spec.tsindex b09f3b3f7,000000000..dab44f047mode 100644,000000..100644--- a/src/modules/auth/chat-scope.service.spec.ts+++ b/src/modules/auth/chat-scope.service.spec.ts@@@ -1,56 -1,0 +1,56 @@@+import { ChatScopeService } from './chat-scope.service';+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';++const PHONE = '919999999999';+const LID = '555000111';++/** Deterministic persisted-lookup stand-in; the real service reads the lid table on a cache miss. */+function fakeStore(): LidMappingStoreService {+ return {+ resolveLidPersisted: jest.fn((lid: string) => Promise.resolve(lid === LID ? PHONE : null)),- lidsForPhonePersisted: jest.fn((phone: string) => Promise.resolve(phone === PHONE ? [LID] : [])),++ findLidsForPhone: jest.fn((phone: string) => Promise.resolve(phone === PHONE ? [LID] : [])),+ phonesForLidsPersisted: jest.fn((lids: string[]) =>+ Promise.resolve(Object.fromEntries(lids.map(lid => [lid, lid === LID ? PHONE : null]))),+ ),+ lidsForPhonesPersisted: jest.fn((phones: string[]) =>+ Promise.resolve(Object.fromEntries(phones.map(phone => [phone, phone === PHONE ? [LID] : []]))),+ ),+ } as unknown as LidMappingStoreService;+}++describe('ChatScopeService', () => {+ it('is unrestricted without an allowlist', async () => {+ const svc = new ChatScopeService();+ expect(svc.isRestricted({ allowedChats: null })).toBe(false);+ expect(svc.isRestricted({ allowedChats: [] })).toBe(false);+ expect(svc.scopeFor({ allowedChats: null })).toBeNull();+ expect(await svc.allows({ allowedChats: null }, '[email protected]')).toBe(true);+ });++ it('matches a phone entry to its lid through the persisted directory', async () => {+ const svc = new ChatScopeService(fakeStore());+ expect(svc.isRestricted({ allowedChats: [`${PHONE}@c.us`] })).toBe(true);+ expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, `${LID}@lid`)).toBe(true);+ expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, '888000222@lid')).toBe(false);+ });++ it('does not admit the same-digits @c.us for a @lid entry', async () => {+ const svc = new ChatScopeService(fakeStore());+ expect(await svc.allows({ allowedChats: [`${LID}@lid`] }, `${LID}@c.us`)).toBe(false);+ expect(await svc.allows({ allowedChats: [`${LID}@lid`] }, `${LID}@lid`)).toBe(true);+ expect(await svc.allows({ allowedChats: [`${LID}@lid`] }, `${PHONE}@c.us`)).toBe(true);+ });++ 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]' }];+ expect(await svc.filter({ allowedChats: [`${PHONE}@c.us`] }, rows, r => r.id)).toEqual([{ id: `${LID}@lid` }]);+ expect(await svc.filter({ allowedChats: null }, rows, r => r.id)).toEqual(rows);+ });++ it('degrades to exact dialects when no lid directory is available', async () => {+ const svc = new ChatScopeService();+ expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, `${LID}@lid`)).toBe(false);+ expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, `${PHONE}@c.us`)).toBe(true);+ });+});diff --cc src/modules/auth/chat-scope.service.tsindex 8a25612c8,000000000..0aaf8485amode 100644,000000..100644--- a/src/modules/auth/chat-scope.service.ts+++ b/src/modules/auth/chat-scope.service.ts@@@ -1,82 -1,0 +1,82 @@@+import { 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 {+ ChatScope,+ ChatScopeDirectory,+ buildChatScope,+ buildExpandedChatScope,+ chatIdAllowed,+ filterByChatScope,+ isChatScopeRestricted,+} from '../../common/security/chat-scope';++/**+ * Compiles an API key's `allowedChats` into an enforceable {@link ChatScope} and answers membership,+ * wiring the lid<->phone table so a phone entry matches its `@lid` form and vice versa.+ *+ * Provided by the global AuthModule so both the ApiKeyGuard (single requested id) and the list+ * endpoints (whole result set) share one definition of "inside the fence". The table is read+ * persistently rather than from the evictable in-memory mirror, so the answer is deterministic. A+ * missing store degrades to exact-dialect matching only, which fails CLOSED for an unmapped `@lid`.+ */+@Injectable()+export class ChatScopeService {+ constructor(+ // Exported by the global EngineModule. Optional so the auth surface still boots in a unit test+ // (or a stripped build) without the engine: the fence then matches dialects exactly.+ @Optional()+ private readonly lidStore?: LidMappingStoreService,+ ) {}++ /** True when the key carries a non-empty allowlist and is therefore fenced. */+ isRestricted(apiKey?: Pick<ApiKey, 'allowedChats'> | null): boolean {+ return isChatScopeRestricted(apiKey?.allowedChats);+ }++ /** The literal scope for a key (no lookups), or `null` when unrestricted. */+ scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): ChatScope | null {+ return buildChatScope(apiKey?.allowedChats ?? null);+ }++ /**+ * Whether a single requested `chatId` is inside the key's fence. Expands the REQUESTED id once+ * through the lid table (at most two lookups) instead of expanding the whole allowlist.+ */+ allows(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string): Promise<boolean> {+ return chatIdAllowed(this.scopeFor(apiKey), chatId, this.singleDirectory());+ }++ /** The allowlist expanded once with the lid table (batched), for filtering a whole list. */+ scopeForFilter(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined): Promise<ChatScope | null> {+ return buildExpandedChatScope(apiKey?.allowedChats ?? null, this.batchDirectory());+ }++ /** The subset of `items` whose chat id is inside the key's fence (unrestricted ⇒ unchanged). */+ async filter<T>(+ apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined,+ items: readonly T[],+ chatIdOf: (item: T) => string | null | undefined,+ ): Promise<T[]> {+ return filterByChatScope(await this.scopeForFilter(apiKey), items, chatIdOf);+ }++ private singleDirectory(): ContactDirectory | undefined {+ const store = this.lidStore;+ if (!store) return undefined;+ return {+ resolveLid: userPart => store.resolveLidPersisted(userPart),- lidsForPhone: phone => store.lidsForPhonePersisted(phone),++ lidsForPhone: phone => store.findLidsForPhone(phone),+ };+ }++ private batchDirectory(): ChatScopeDirectory | undefined {+ const store = this.lidStore;+ if (!store) return undefined;+ return {+ phonesForLids: lids => store.phonesForLidsPersisted(lids),+ lidsForPhones: phones => store.lidsForPhonesPersisted(phones),+ };+ }+}diff --cc src/modules/message/message.controller.tsindex 7f878a6ee,5a7af10ed..a5a735952--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@@ -450,7 -442,61 +457,75 @@@ export class MessageControllerreturn { success: true };}+ // Declared before ':chatId/history': Express takes the first matching route, so a batch whose+ // caller-supplied id is 'history' would otherwise be read as the chat history of chat 'batch'.+ @Get('batch/:batchId')+ @ApiOperation({ summary: 'Get batch processing status' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'batchId', description: 'Batch ID' })+ @ApiResponse({+ status: 200,+ description: 'Batch status and progress',+ type: BatchStatusResponseDto,+ })+ @ApiResponse({+ status: 404,+ description: 'Batch not found',+ })++ @ApiResponse({++ status: 403,++ description:++ 'The calling key is restricted with `allowedChats`. A batch row has no key owner, so the ' +++ "status cannot be checked against the key's allowlist and a chat-restricted key is refused; " +++ 'use the single-send routes instead.',++ })+ async getBatchStatus(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {+ const batch = await this.bulkMessageService.getBatchStatus(sessionId, batchId);+ return {+ batchId: batch.batchId,+ status: batch.status,+ progress: batch.progress,+ results: batch.results,+ startedAt: batch.startedAt,+ completedAt: batch.completedAt,+ };+ }++ @Post('batch/:batchId/cancel')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Cancel a running batch' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'batchId', description: 'Batch ID' })+ @ApiResponse({+ status: 200,+ description: 'Batch cancelled',+ type: BatchCancelResponseDto,+ })++ @ApiResponse({++ status: 403,++ description:++ 'The calling key is restricted with `allowedChats`. A batch row has no key owner, so the ' +++ "cancel cannot be checked against the key's allowlist and a chat-restricted key is refused.",++ })+ @ApiResponse({+ status: 400,+ description: 'Batch already completed, cancelled, or failed (terminal statuses are exclusive)',+ })+ @ApiResponse({+ status: 404,+ description: 'Batch not found',+ })+ async cancelBatch(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {+ const batch = await this.bulkMessageService.cancelBatch(sessionId, batchId);+ return {+ batchId: batch.batchId,+ status: batch.status,+ progress: batch.progress,+ };+ }++ @ChatScoped('fenced')@Get(':chatId/history')@ApiOperation({summary: 'Fetch chat history live from WhatsApp',diff --cc src/modules/message/message.service.tsindex 956129f69,37f438925..3b0f614dc--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@@ -364,15 -364,28 +364,15 @@@ export class MessageService implements* 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): Promise<string[]> {+ private async resolveJidCandidates(value: string): Promise<string[]> {- const parsed = parseWaId(value);- if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {- return [value];- }- if (parsed.kind === 'lid') {- // The folded `<lid>@lid` form is how a raw-lid row is stored, so an upper-case or- // `@hosted.lid` input still matches it.- const candidates = new Set<string>([value, `${parsed.userPart}@lid`]);- const resolved = await this.lidMappingStore.findPhoneForLid(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 await this.lidMappingStore.findLidsForPhone(phone)) {- candidates.add(`${lid}@lid`);- }- return [...candidates];+ // Rules live in the shared helper (engine/identity/jid-candidates) so this filter and the- // API-key chat scope cannot disagree about which ids refer to the same entity. The store's- // cache-based lookups are passed through unchanged: this path is a read filter, not an- // authorization decision, so the evictable mirror is acceptable here.- return expandJidCandidates(value, {- resolveLid: lid => this.lidMappingStore.getCached(lid) ?? null,- lidsForPhone: phone => this.lidMappingStore.lidsForPhone(phone),++ // API-key chat scope cannot disagree about which ids refer to the same entity. The raw input is++ // kept as a candidate too: a row stored under a non-folded spelling must still match it.++ const expanded = await expandJidCandidates(value, {++ resolveLid: lid => this.lidMappingStore.findPhoneForLid(lid),++ lidsForPhone: phone => this.lidMappingStore.findLidsForPhone(phone),+ });++ return [...new Set([value, ...expanded])];}/**