Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(auth): let a chat-restricted key read stored messages by chatId
Yudhi Armyndharis4cc9fa28c2e1
diff --git a/README.md b/README.mdindex 17746c9e5..0ed3aaece 100644--- a/README.md+++ b/README.md@@ -63,7 +63,7 @@ A session-scoped key still reaches every chat on the sessions it may use. A key- **One or more selected** — the key reaches only those chats. Every authenticated REST route not explicitly marked as safe for a chat-scoped key refuses it with `403` (a request naming a session outside `allowedSessions` still answers `401` first), including routes added in later releases: the refusal is the default. Inside its chats an operator key can do what the marked routes allow, which is more than reading and sending: it can also delete or clear a chat, leave or rename a group, and block the contact. It cannot change who belongs to a group: adding, removing, promoting or demoting participants, answering join requests and reading or resetting the invite link all stay closed.- **The two scopes are independent** — a key may be limited to sessions, to chats, to both, or to neither.-This lets you point an **AI agent or third-party integration at a shared account** without handing it every chat. Give the agent a key scoped to the few groups (or DMs) it is meant to handle: it can send and reply there, but it cannot list your other chats, read any other DM, message a contact outside its set, or reach the queue dashboard. It reads its chats through `GET /sessions/{sessionId}/messages/{chatId}/history`, which works on whatsapp-web.js only; on Baileys it sees just each chat's last-message preview. It receives no pushed events, so it has to poll. It can still read the session's own status (`GET /sessions/{sessionId}`) so an integration can tell whether it is connected.+This lets you point an **AI agent or third-party integration at a shared account** without handing it every chat. Give the agent a key scoped to the few groups (or DMs) it is meant to handle: it can send and reply there, but it cannot list your other chats, read any other DM, message a contact outside its set, or reach the queue dashboard. It reads its chats' stored messages on either engine through `GET /sessions/{sessionId}/messages?chatId=`, where `chatId` is required for such a key, and live history through `GET /sessions/{sessionId}/messages/{chatId}/history` on whatsapp-web.js only. It receives no pushed events, so it has to poll. It can still read the session's own status (`GET /sessions/{sessionId}`) so an integration can tell whether it is connected.Identity 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]`.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 6e38ee6ea..086a36ad6 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. 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. 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`).### API-Key Lifecycle@@ -1276,7 +1276,7 @@ Get persisted message history for a session from the local DB (paginated, filter| Name | Type | Required | Default | Description || ----------- | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |+| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. Required for a key restricted to selected chats. || from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. || limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. || offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |@@ -1312,7 +1312,7 @@ Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from> **Inline media is carried up to a budget, then omitted.** `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one response may hold across its rows. A row is not a bounded object — `limit` is clamped to `[1,100]` but each row can carry its base64 in `metadata.media.data`, so a page of media rows could otherwise reach hundreds of megabytes and fail the read outright. The budget is spent newest-first, matching the `createdAt` DESC order above, so a page that cannot carry everything keeps the most recent media. Past it a payload is replaced with `{ mimetype, filename?, omitted: true, sizeBytes }` — the same marker the engine emits for inbound media over `MEDIA_DOWNLOAD_MAX_BYTES` — and the bytes remain available from [`GET /messages/:chatId/:messageId/media`](#get-apisessionssessionidmessageschatidmessageidmedia). Two rules bound the edges: the newest payload is always inlined even when it alone exceeds the budget (otherwise a single large photo would be permanently unreadable through this route), and a budget of `0` means "never inline" and grants no such allowance. The knob is validated at boot — `8MiB` would parse to 8 bytes — and is forwarded by both compose files. The MCP `MessageList` tool shares this path and the same budget.-**Errors:** `400` `after` names no message in this session · `401` missing/invalid API key+**Errors:** `400` `after` names no message in this session · `401` missing/invalid API key · `403` a key restricted to selected chats sent no `chatId`, or one outside its allowlistA blank `after` is treated as absent, the way a blank `limit` or `offset` already is, so a clienttemplating a cursor it has not got yet keeps the unfiltered first page rather than a `400`.diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.tsindex 9d85ce694..19156165f 100644--- a/src/modules/auth/chat-scope-coverage.spec.ts+++ b/src/modules/auth/chat-scope-coverage.spec.ts@@ -11,8 +11,9 @@// @ChatScoped('fenced') the handler names a chat the guard inspects — a `:chatId` / `:groupId` /// `:contactId` path param, or a REQUIRED guard-read body field// (`chatId` / `fromChatId` / `toChatId` / `messages[]`). An optional-// `?chatId=` does NOT qualify: the guard would have nothing to check when-// it is omitted.+// `?chatId=` qualifies only when the handler also calls+// `this.chatScope.requireChat(`, which refuses a restricted key that omits+// it; on its own the guard would have nothing to check.// @ChatScoped('filtered') the handler lists chats and returns through ChatScopeService.filter.// @ChatScoped('agnostic') the handler cannot reach a chat at all. This is the one category the// spec cannot derive (a webhook with `events: ['*']` also names no chat),@@ -77,8 +78,10 @@ export const MUST_STAY_UNMARKED: ReadonlyArray<readonly [string, string]> = [/** Handlers that must stay marked with the given category; a lost mark silently becomes a 403. */export const MUST_STAY_MARKED: ReadonlyArray<readonly [string, string, string]> = [- // The only chat-read route a restricted key has on whatsapp-web.js.+ // Live history, whatsapp-web.js only.['message.controller.ts', 'getChatHistory', 'fenced'],+ // Stored history on both engines, for the chat named in ?chatId=.+ ['message.controller.ts', 'getMessages', 'fenced'],];const REQUIRED_GUARD_FIELD = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})!\\s*:`);@@ -168,7 +171,9 @@ export function chatScopeViolations(const hasPathChat = new RegExp(`@Param\\(\\s*['"](?:${GUARD_CHAT_ROUTE_PARAMS.join('|')})['"]\\s*\\)`).test(body);const bodyDto = /@Body\(\)\s*[A-Za-z0-9_]+\s*:\s*([A-Za-z0-9_]+)/.exec(body)?.[1];const hasRequiredBodyChat = bodyDto !== undefined && requiredDtos.has(bodyDto);- if (kind === 'fenced' && !(hasPathChat || hasRequiredBodyChat))+ const hasRequiredQueryChat =+ /@Query\(\s*['"]chatId['"]\s*\)/.test(body) && /this\.chatScope\.requireChat\(/.test(body);+ if (kind === 'fenced' && !(hasPathChat || hasRequiredBodyChat || hasRequiredQueryChat))offenders.push(`${name} (fenced, no guard-read chat)`);else if (kind === 'filtered' && !/chatScope\.filter\(/.test(body)) offenders.push(`${name} (filtered, no filter)`);else if (kind === 'agnostic' && !agnosticGrants.some(([f, h]) => f === file && h === name))@@ -225,6 +230,28 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedChexpect(chatScopeViolations(source, 'x.controller.ts', new Set())).toEqual(['list (fenced, no guard-read chat)']);});+ it("clears a 'fenced' optional query chat only when the handler requires it", () => {+ const required = `+ @ChatScoped('fenced')+ @Get()+ async list(@Query('chatId') chatId?: string, @CurrentApiKey() apiKey?: ApiKey): Promise<unknown> {+ this.chatScope.requireChat(apiKey, chatId);+ return this.svc.list(chatId);+ }+`;+ expect(chatScopeViolations(required, 'x.controller.ts', new Set())).toEqual([]);++ const noQuery = `+ @ChatScoped('fenced')+ @Get()+ async list(@CurrentApiKey() apiKey?: ApiKey): Promise<unknown> {+ this.chatScope.requireChat(apiKey, undefined);+ return this.svc.list();+ }+`;+ expect(chatScopeViolations(noQuery, 'x.controller.ts', new Set())).toEqual(['list (fenced, no guard-read chat)']);+ });+it("flags a 'filtered' handler that does not filter and an unlisted 'agnostic'", () => {const source = `@ChatScoped('filtered')diff --git a/src/modules/auth/chat-scope.service.spec.ts b/src/modules/auth/chat-scope.service.spec.tsindex b7d219a59..8b9220243 100644--- a/src/modules/auth/chat-scope.service.spec.ts+++ b/src/modules/auth/chat-scope.service.spec.ts@@ -1,3 +1,4 @@+import { ForbiddenException } from '@nestjs/common';import { ChatScopeService } from './chat-scope.service';import { FindOperator, Repository } from 'typeorm';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';@@ -21,6 +22,17 @@ function fakeStore(): LidMappingStoreService {}describe('ChatScopeService', () => {+ it('requireChat refuses a restricted key that names no chat, and nothing else', () => {+ const svc = new ChatScopeService();+ const restricted = { allowedChats: ['[email protected]'] };+ for (const chatId of [undefined, '', ' ']) {+ expect(() => svc.requireChat(restricted, chatId)).toThrow(ForbiddenException);+ }+ expect(() => svc.requireChat(restricted, '[email protected]')).not.toThrow();+ expect(() => svc.requireChat({ allowedChats: null }, undefined)).not.toThrow();+ expect(() => svc.requireChat(undefined, undefined)).not.toThrow();+ });+it('is unrestricted without an allowlist', async () => {const svc = new ChatScopeService();expect(svc.isRestricted({ allowedChats: null })).toBe(false);diff --git a/src/modules/auth/chat-scope.service.ts b/src/modules/auth/chat-scope.service.tsindex 78bc1d820..bf2102faf 100644--- a/src/modules/auth/chat-scope.service.ts+++ b/src/modules/auth/chat-scope.service.ts@@ -1,4 +1,4 @@-import { Injectable, Optional } from '@nestjs/common';+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';@@ -35,6 +35,17 @@ export class ChatScopeService {return isChatScopeRestricted(apiKey?.allowedChats);}+ /**+ * Refuse a restricted key that names no chat on a route whose chat is an optional `?chatId=`. The+ * guard fences the chat id when it is present; this closes the case where it is missing or blank,+ * which the route would otherwise read as "every chat".+ */+ requireChat(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string | undefined): void {+ if (this.isRestricted(apiKey) && !chatId?.trim()) {+ throw new ForbiddenException('chatId is required for a key restricted to selected chats');+ }+ }+/** 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);diff --git a/src/modules/message/message.controller.spec.ts b/src/modules/message/message.controller.spec.tsindex 51f742724..3df4755ba 100644--- a/src/modules/message/message.controller.spec.ts+++ b/src/modules/message/message.controller.spec.ts@@ -6,6 +6,9 @@ import type { Server } from 'http';import { MessageController } from './message.controller';import { MessageService } from './message.service';import { BulkMessageService } from './bulk-message.service';+import { ChatScopeService } from '../auth/chat-scope.service';+import { CHAT_SCOPED_KEY } from '../auth/decorators/auth.decorators';+import type { ApiKey } from '../auth/entities/api-key.entity';import type { SendBulkMessageDto } from './dto/bulk-message.dto';import type { Response } from 'express';@@ -20,6 +23,7 @@ describe('MessageController — stored media download', () => {const controller = new MessageController({ getChatMedia } as unknown as MessageService,{} as unknown as BulkMessageService,+ new ChatScopeService(),);/**@@ -78,6 +82,7 @@ describe('MessageController - inlineMedia is opt-out', () => {const controller = new MessageController({ getMessages } as unknown as MessageService,{} as unknown as BulkMessageService,+ new ChatScopeService(),);const inlineMediaFor = async (raw?: string): Promise<boolean> => {@@ -117,6 +122,49 @@ describe('MessageController - inlineMedia is opt-out', () => {});});+/**+ * A key restricted to selected chats reads stored history only for a chat it names: the guard fences+ * the ?chatId= it sends, and the handler refuses the same key when it names none, which the service+ * would otherwise read as every chat in the session.+ */+describe('MessageController - stored history for a chat-restricted key', () => {+ const getMessages = jest.fn().mockResolvedValue({ messages: [], total: 0 });+ const controller = new MessageController(+ { getMessages } as unknown as MessageService,+ {} as unknown as BulkMessageService,+ new ChatScopeService(),+ );+ const restricted = { allowedChats: ['[email protected]'] } as ApiKey;+ const list = (chatId: string | undefined, apiKey?: ApiKey) =>+ controller.getMessages('s1', chatId, undefined, undefined, undefined, undefined, undefined, apiKey);++ beforeEach(() => getMessages.mockClear());++ it('is fenced', () => {+ expect(+ Reflect.getMetadata(+ CHAT_SCOPED_KEY,+ Object.getOwnPropertyDescriptor(MessageController.prototype, 'getMessages')!.value as object,+ ),+ ).toBe('fenced');+ });++ it.each([undefined, ''])('refuses a restricted key with chatId %p before reading', async chatId => {+ await expect(list(chatId, restricted)).rejects.toThrow('chatId is required for a key restricted to selected chats');+ expect(getMessages).not.toHaveBeenCalled();+ });++ it('reads the named chat for a restricted key, passing chatId through as sent', async () => {+ await list('[email protected]', restricted);+ expect(getMessages).toHaveBeenCalledWith('s1', expect.objectContaining({ chatId: '[email protected]' }));+ });++ it('leaves an unrestricted key free to list every chat', async () => {+ await list(undefined, { allowedChats: null } as ApiKey);+ expect(getMessages).toHaveBeenCalledWith('s1', expect.objectContaining({ chatId: undefined }));+ });+});+/*** A caller may pick its own batchId. 'history' shares the two-segment shape of ':chatId/history',* and an id with a reserved character must survive the statusUrl handed back on creation.@@ -134,6 +182,7 @@ describe('MessageController - caller-supplied batch ids', () => {providers: [{ provide: MessageService, useValue: messages },{ provide: BulkMessageService, useValue: bulk },+ ChatScopeService,],}).compile();const app = moduleRef.createNestApplication();@@ -153,6 +202,7 @@ describe('MessageController - caller-supplied batch ids', () => {const controller = new MessageController(messages as unknown as MessageService,bulk as unknown as BulkMessageService,+ new ChatScopeService(),);const res = await controller.sendBulk('s1', {} as SendBulkMessageDto);diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex bebf0e525..07c48de12 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -46,8 +46,9 @@ import {ClickButtonDto,UnpinMessageDto,} from './dto/message-actions.dto';-import { ChatQuotedAllowed, ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { ChatQuotedAllowed, 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 {CHANNEL_MEDIA_501,CUSTOM_LINK_PREVIEW_501,@@ -73,12 +74,20 @@ export class MessageController {constructor(private readonly messageService: MessageService,private readonly bulkMessageService: BulkMessageService,+ private readonly chatScope: ChatScopeService,) {}+ // Fenced on the optional ?chatId=: the guard checks it when present, and requireChat refuses a+ // chat-restricted key that omits it, so such a key reads only its own chats' stored history.+ @ChatScoped('fenced')@Get()@ApiOperation({ summary: 'Get message history for a session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })- @ApiQuery({ name: 'chatId', required: false, description: 'Filter by chat ID' })+ @ApiQuery({+ name: 'chatId',+ required: false,+ description: 'Filter by chat ID. Required for an API key restricted to selected chats.',+ })@ApiQuery({name: 'from',required: false,@@ -115,6 +124,12 @@ export class MessageController {'empty page, which reads exactly like the end of the history, so a walk resumed from a stale ' +'or foreign cursor would stop silently instead of reporting the cursor.',})+ @ApiResponse({+ status: 403,+ description:+ 'The API key is restricted to selected chats and either sent no `chatId` or named a chat outside ' ++ 'its allowlist.',+ })async getMessages(@Param('sessionId') sessionId: string,@Query('chatId') chatId?: string,@@ -123,7 +138,9 @@ export class MessageController {@Query('offset') offset?: string,@Query('after') after?: string,@Query('inlineMedia') inlineMedia?: string,+ @CurrentApiKey() apiKey?: ApiKey,) {+ this.chatScope.requireChat(apiKey, chatId);return this.messageService.getMessages(sessionId, {chatId,from,