Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(auth): filter group, contact and label-chat lists by chat scope
Yudhi Armyndharisd72b0226cae6
diff --git a/README.md b/README.mdindex 0ed3aaece..2f9448174 100644--- a/README.md+++ b/README.md@@ -67,7 +67,7 @@ This lets you point an **AI agent or third-party integration at a shared accountIdentity is matched through the lid mapping table: a contact allowlisted by phone number also matches the same person's `@lid` privacy id once the table maps the two, and an unmapped `@lid` is refused rather than guessed. A lid's digits are never mistaken for a phone number, so `555000111@lid` does not admit `[email protected]`.-The default covers REST routes only. Surfaces that authenticate outside the REST guard do not inherit it, so each one that can return chat data refuses a chat-scoped key with its own check: the `/events` WebSocket, the MCP mount (per tool call), and the Bull Board queue dashboard. Of the list routes, only `GET /sessions/{sessionId}/chats` is usable, and it filters to the key's chats before paging.+The default covers REST routes only. Surfaces that authenticate outside the REST guard do not inherit it, so each one that can return chat data refuses a chat-scoped key with its own check: the `/events` WebSocket, the MCP mount (per tool call), and the Bull Board queue dashboard. Four list routes are usable, each filtered to the key's chats before paging: `GET /sessions/{sessionId}/chats`, `GET /sessions/{sessionId}/groups` (id, name and community parent id only), `GET /sessions/{sessionId}/contacts` and `GET /sessions/{sessionId}/labels/{labelId}/chats`.The API also accepts `allowedChats` on an admin key, but no admin-only route is open to a chat-scoped key, and the last usable admin key cannot be scoped this way.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 086a36ad6..225d39451 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -47,7 +47,7 @@ API keys carry one of three roles, ordered by privilege:A key may additionally be scoped to specific sessions (`allowedSessions`) and/or source IPs (`allowedIps`). The scope/IP check runs in the guard **before** any role check, so a request outside that scope is rejected with `401` (not `403`) even if the role would otherwise allow it.-A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`). An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. Chat list routes return only the allowed chats. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The surfaces outside the REST guard refuse a chat-restricted key outright: the `/events` WebSocket at the handshake and on every subscribe, every MCP tool call (`403`), and the Bull Board queue dashboard (`403`).+A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`). An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. The chat, group, contact and label-chat list routes (`GET /api/sessions/:sessionId/chats`, `/groups`, `/contacts` and `/labels/:labelId/chats`) return only the allowed entries, filtered before paging. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The surfaces outside the REST guard refuse a chat-restricted key outright: the `/events` WebSocket at the handshake and on every subscribe, every MCP tool call (`403`), and the Bull Board queue dashboard (`403`).### API-Key Lifecyclediff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.tsindex 19156165f..0e5cee96b 100644--- a/src/modules/auth/chat-scope-coverage.spec.ts+++ b/src/modules/auth/chat-scope-coverage.spec.ts@@ -82,6 +82,11 @@ export const MUST_STAY_MARKED: ReadonlyArray<readonly [string, string, string]>['message.controller.ts', 'getChatHistory', 'fenced'],// Stored history on both engines, for the chat named in ?chatId=.['message.controller.ts', 'getMessages', 'fenced'],+ // List routes a restricted key may use, each filtered to its chats before paging.+ ['session.controller.ts', 'getChats', 'filtered'],+ ['session.controller.ts', 'getGroups', 'filtered'],+ ['contact.controller.ts', 'findAll', 'filtered'],+ ['label.controller.ts', 'getChatsByLabel', 'filtered'],];const REQUIRED_GUARD_FIELD = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})!\\s*:`);diff --git a/src/modules/contact/contact.controller.spec.ts b/src/modules/contact/contact.controller.spec.tsindex 9af76b0ed..5548e4551 100644--- a/src/modules/contact/contact.controller.spec.ts+++ b/src/modules/contact/contact.controller.spec.ts@@ -1,9 +1,11 @@import { ContactController } from './contact.controller';import { ContactService } from './contact.service';+import { ChatScopeService } from '../auth/chat-scope.service';+import type { ApiKey } from '../auth/entities/api-key.entity';describe('ContactController', () => {const service = {- getContacts: jest.fn(),+ listContacts: jest.fn(),getProfilePictures: jest.fn(),getContactById: jest.fn(),getNumberId: jest.fn(),@@ -15,20 +17,38 @@ describe('ContactController', () => {unblockContact: jest.fn(),getBlockedContacts: jest.fn(),};- const controller = new ContactController(service as unknown as ContactService);+ const controller = new ContactController(service as unknown as ContactService, new ChatScopeService());beforeEach(() => jest.clearAllMocks());- it('findAll parses limit/offset query strings', async () => {- service.getContacts.mockResolvedValue([]);- await controller.findAll('s1', '5', '10');- expect(service.getContacts).toHaveBeenCalledWith('s1', { limit: 5, offset: 10 });+ const contacts = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `${i}@c.us` }));++ it('findAll applies limit/offset query strings', async () => {+ service.listContacts.mockResolvedValue(contacts(50));+ const page = (await controller.findAll('s1', '5', '10')) as { id: string }[];+ expect(service.listContacts).toHaveBeenCalledWith('s1');+ expect(page.map(c => c.id)).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']);+ });++ it('findAll caps an unpaged list at the default window', async () => {+ service.listContacts.mockResolvedValue(contacts(1500));+ await expect(controller.findAll('s1')).resolves.toHaveLength(1000);});- it('findAll leaves paging undefined without query params', async () => {- service.getContacts.mockResolvedValue([]);- await controller.findAll('s1');- expect(service.getContacts).toHaveBeenCalledWith('s1', { limit: undefined, offset: undefined });+ it('findAll filters to a chat-restricted key before the window, matching either phone dialect', async () => {+ // The disallowed contact comes first, so a page of 1 taken before filtering would hold nothing allowed.+ service.listContacts.mockResolvedValue([+ { id: '[email protected]' },+ { id: '[email protected]' },+ { id: '[email protected]' },+ { id: '555000111@lid' },+ ]);+ const apiKey = { allowedChats: ['[email protected]'] } as ApiKey;++ const all = (await controller.findAll('s1', undefined, undefined, apiKey)) as { id: string }[];+ expect(all.map(c => c.id)).toEqual(['[email protected]', '[email protected]']);+ const first = (await controller.findAll('s1', '1', '0', apiKey)) as { id: string }[];+ expect(first.map(c => c.id)).toEqual(['[email protected]']);});it('getProfilePictures splits, trims and drops empty ids', async () => {diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 7e9cbab87..34b9ab9d5 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -1,8 +1,10 @@import { Body, Controller, Get, Post, Put, Delete, Param, Query, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';import { ContactService } from './contact.service';-import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { ChatScoped, CurrentApiKey, RequireRole } from '../auth/decorators/auth.decorators';+import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';+import { ChatScopeService } from '../auth/chat-scope.service';+import { paginate } from '../../common/utils/paginate';import { UpsertContactDto } from './dto/upsert-contact.dto';import {ContactAckResponseDto,@@ -17,8 +19,12 @@ import { ENGINE_NOT_READY_409 } from '../../common/openapi/engine-status-respons@ApiTags('contacts')@Controller('sessions/:sessionId/contacts')export class ContactController {- constructor(private readonly contactService: ContactService) {}+ constructor(+ private readonly contactService: ContactService,+ private readonly chatScope: ChatScopeService,+ ) {}+ @ChatScoped('filtered')@Get()@ApiOperation({ summary: 'Get all contacts for a session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -41,11 +47,11 @@ export class ContactController {@Param('sessionId') sessionId: string,@Query('limit') limit?: string,@Query('offset') offset?: string,+ @CurrentApiKey() apiKey?: ApiKey,) {- return this.contactService.getContacts(sessionId, {- limit: limit ? parseInt(limit, 10) : undefined,- offset: offset ? parseInt(offset, 10) : undefined,- });+ // Filtered before paging so a chat-restricted key sees only its contacts, in full windows.+ const visible = await this.chatScope.filter(apiKey, await this.contactService.listContacts(sessionId), c => c.id);+ return paginate(visible, limit ? parseInt(limit, 10) : undefined, offset ? parseInt(offset, 10) : undefined);}@Get('profile-pictures')diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex e36188c64..49ba94a87 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -26,6 +26,13 @@ describe('ContactService', () => {expect(() => makeService(undefined).getBlockedContacts('s1')).toThrow(BadRequestException);});+ it('listContacts returns the whole set, unwindowed', async () => {+ const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));+ const getContacts = jest.fn().mockResolvedValue(big);+ await expect(makeService({ getContacts }).listContacts('s1')).resolves.toHaveLength(1500);+ expect(() => makeService(undefined).listContacts('s1')).toThrow(BadRequestException);+ });+it('caps an unbounded contacts list at the default limit (1000)', async () => {const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));const getContacts = jest.fn().mockResolvedValue(big);diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex e184258d9..4c2106d5c 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -21,12 +21,15 @@ export class ContactService {return this.engines.require(sessionId);}+ /** Every contact WITHOUT the response window, for callers that filter before paging. */+ listContacts(sessionId: string) {+ // getEngine throws synchronously (keeps the "session not started" guard a sync 400).+ return this.getEngine(sessionId).getContacts();+ }+getContacts(sessionId: string, opts: ListOptions = {}) {- // getEngine throws synchronously (keeps the "session not started" guard a sync 400); the- // engine returns the full set and we bound the HTTP response window via paginate().- return this.getEngine(sessionId)- .getContacts()- .then(contacts => paginate(contacts, opts.limit, opts.offset));+ // The engine returns the full set and we bound the HTTP response window via paginate().+ return this.listContacts(sessionId).then(contacts => paginate(contacts, opts.limit, opts.offset));}async getContactById(sessionId: string, contactId: string) {diff --git a/src/modules/label/label.controller.spec.ts b/src/modules/label/label.controller.spec.tsnew file mode 100644index 000000000..f8afa54d5--- /dev/null+++ b/src/modules/label/label.controller.spec.ts@@ -0,0 +1,32 @@+import { NotImplementedException } from '@nestjs/common';+import { LabelController } from './label.controller';+import type { LabelService } from './label.service';+import { ChatScopeService } from '../auth/chat-scope.service';+import type { ApiKey } from '../auth/entities/api-key.entity';++describe('LabelController - GET :labelId/chats for a chat-restricted key', () => {+ const getChatsByLabel = jest.fn();+ const controller = new LabelController({ getChatsByLabel } as unknown as LabelService, new ChatScopeService());+ const chats = [{ id: '[email protected]' }, { id: '[email protected]' }, { id: '[email protected]' }];++ beforeEach(() => getChatsByLabel.mockReset());++ it('returns only the chats inside the key allowlist', async () => {+ getChatsByLabel.mockResolvedValue(chats);+ const out = await controller.getChatsByLabel('s1', 'l1', { allowedChats: ['[email protected]'] } as ApiKey);+ expect(getChatsByLabel).toHaveBeenCalledWith('s1', 'l1');+ expect(out).toEqual([{ id: '[email protected]' }]);+ });++ it('passes every chat through for an unrestricted key', async () => {+ getChatsByLabel.mockResolvedValue(chats);+ await expect(controller.getChatsByLabel('s1', 'l1', { allowedChats: null } as ApiKey)).resolves.toEqual(chats);+ });++ it('lets an engine refusal through unchanged', async () => {+ getChatsByLabel.mockRejectedValue(new NotImplementedException('no label query'));+ await expect(controller.getChatsByLabel('s1', 'l1', { allowedChats: ['[email protected]'] } as ApiKey)).rejects.toThrow(+ NotImplementedException,+ );+ });+});diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex 78a6ba49e..32211b4ac 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -5,8 +5,9 @@ import { ChatSummaryDto } from '../session/dto/chat-summary.dto';import { LabelService } from './label.service';import { AddLabelDto } from './dto/add-label.dto';import { UpsertLabelDto } from './dto/upsert-label.dto';-import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { ChatScoped, CurrentApiKey, RequireRole } from '../auth/decorators/auth.decorators';+import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';+import { ChatScopeService } from '../auth/chat-scope.service';import {ENGINE_NOT_READY_409,ENGINE_NOT_SUPPORTED_501,@@ -16,7 +17,10 @@ import {@ApiTags('labels')@Controller('sessions/:sessionId/labels')export class LabelController {- constructor(private readonly labelService: LabelService) {}+ constructor(+ private readonly labelService: LabelService,+ private readonly chatScope: ChatScopeService,+ ) {}@Get()@ApiOperation({ summary: 'Get all labels (WhatsApp Business only)' })@@ -57,6 +61,7 @@ export class LabelController {return this.labelService.getLabelById(sessionId, labelId);}+ @ChatScoped('filtered')@Get(':labelId/chats')@ApiOperation({summary: 'Get every chat carrying a label',@@ -77,8 +82,12 @@ export class LabelController {})@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 404, description: LABEL_NOT_FOUND_404 })- async getChatsByLabel(@Param('sessionId') sessionId: string, @Param('labelId') labelId: string) {- return this.labelService.getChatsByLabel(sessionId, labelId);+ async getChatsByLabel(+ @Param('sessionId') sessionId: string,+ @Param('labelId') labelId: string,+ @CurrentApiKey() apiKey?: ApiKey,+ ) {+ return this.chatScope.filter(apiKey, await this.labelService.getChatsByLabel(sessionId, labelId), c => c.id);}@Put(':labelId')diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 302f3b729..07e24e4c4 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -542,3 +542,41 @@ describe('SessionController — GET .../chats filters before paginating', () =>expect(out).toHaveLength(2);});});++// GET /sessions/:sessionId/groups follows the same rule: a restricted key sees only its groups, and+// the window is taken after the filter.+describe('SessionController: GET .../groups filters before paginating', () => {+ const group = (id: string) => ({ id, name: id, linkedParentJID: '[email protected]' });+ let sessionService: { listGroups: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = { listGroups: jest.fn() };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ { logInfo: jest.fn() } as unknown as AuditService,+ new ChatScopeService(),+ );+ });++ it('filters the full list before the window, keeping the allowed group as returned', async () => {+ sessionService.listGroups.mockResolvedValue([group('[email protected]'), group('[email protected]'), group('[email protected]')]);+ const apiKey = { allowedChats: ['[email protected]', '[email protected]'] } as ApiKey;++ const out = await controller.getGroups('sess-uuid-1', apiKey, '1', '0');++ expect(out).toEqual([group('[email protected]')]);+ });++ it('pages the whole list for an unrestricted key', async () => {+ sessionService.listGroups.mockResolvedValue([group('[email protected]'), group('[email protected]'), group('[email protected]')]);+ const out = await controller.getGroups('sess-uuid-1', { allowedChats: null } as ApiKey, '2', '1');+ expect(out.map(g => g.id)).toEqual(['[email protected]', '[email protected]']);+ });++ it('caps an unbounded group list at the default limit (1000)', async () => {+ sessionService.listGroups.mockResolvedValue(Array.from({ length: 1500 }, (_, i) => group(`${i}@g.us`)));+ const out = await controller.getGroups('sess-uuid-1', { allowedChats: null } as ApiKey);+ expect(out).toHaveLength(1000);+ });+});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex ccd4497bf..816c7e1bc 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -481,6 +481,7 @@ export class SessionController {// Shares a Path Item with GroupController's POST on the same route — one parameter name for the// one positional segment, or the contract splits it into two entries.+ @ChatScoped('filtered')@Get(':sessionId/groups')@ApiOperation({ summary: 'Get all groups for a session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -503,13 +504,14 @@ export class SessionController {@ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })async getGroups(@Param('sessionId', ParseUUIDPipe) id: string,+ @CurrentApiKey() apiKey?: ApiKey,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {- return this.sessionService.getGroups(id, {- limit: limit ? parseInt(limit, 10) : undefined,- offset: offset ? parseInt(offset, 10) : undefined,- });+ // Filtered before paging, as getChats is, so a chat-restricted key sees only its groups and+ // never a short window while an allowed group sat just past it.+ const visible = await this.chatScope.filter(apiKey, await this.sessionService.listGroups(id), g => g.id);+ return paginate(visible, limit ? parseInt(limit, 10) : undefined, offset ? parseInt(offset, 10) : undefined);}@ChatScoped('filtered')diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex a6a75f133..91be30c1b 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -6966,21 +6966,6 @@ describe('SessionService', () => {});});- describe('getGroups pagination', () => {- it('caps an unbounded group list at the default limit (1000)', async () => {- const session = createMockSession();- (repository.findOne as jest.Mock).mockResolvedValue(session);- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });- await service.start('sess-uuid-1');-- const groups = Array.from({ length: 1500 }, (_, i) => ({ id: `g${i}`, name: `G${i}` }));- mockEngine.getGroups.mockResolvedValue(groups);-- const result = await service.getGroups('sess-uuid-1');- expect(result).toHaveLength(1000);- });- });-describe('start() concurrent stop/delete guard', () => {it('tears down the just-initialized engine if a stop/delete lands during start() (no resurrection to READY)', async () => {const session = createMockSession();diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 6dec7b03e..626eb88e4 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -766,20 +766,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.require(id);}- async getGroups(- id: string,- opts: ListOptions = {},- ): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {+ /** Every group for a session WITHOUT the response window, for callers that filter before paging. */+ async listGroups(id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {await this.findOne(id); // Verify session existsconst engine = this.requireEngine(id);const groups = await engine.getGroups();- const mapped = groups.map(g => ({+ return groups.map(g => ({id: g.id,name: g.name,linkedParentJID: g.linkedParentJID,}));- return paginate(mapped, opts.limit, opts.offset);}/**