Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(auth): scope API keys to an allowedChats allowlist
Bhavya Choprad01a495ac518
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c26c57f6..56637279e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- API keys carry an optional `allowedChats` allowlist next to `allowedSessions`: a curated set of chats (groups and/or contacts) a key may read and send to, `null`/empty meaning unrestricted and independent of the session scope. The `ApiKeyGuard` fences the chat in the path (`:chatId` / `:groupId` / `:contactId`) and, for sends, the `chatId` in the request body, rejecting an out-of-scope chat with `403`; a contact entry matches its resolved `@lid` form (and vice versa) through the lid mapping table, and an unmapped `@lid` stays outside the fence. A structural coverage spec pins the surface so a later endpoint cannot bypass it silently.- Baileys inbound button, template quick-reply, list-row and native-flow replies arrive as `type: "text"` with a structured `button { id, text? }` on `message.received` (whatsapp-web.js still has no interactive reply fields). The REST chat-history route is whatsapp-web.js only and does not carry these fields. Thanks @gabrielmmoraes1999.- Baileys inbound business prompts that offer clickable buttons (or list rows) also carry `buttons: [{ id, text }, …]` on `message.received` (URL/call CTAs are omitted — they cannot be clicked), so choices like Sim/Não are no longer flattened away into `body` only. Thanks @gabrielmmoraes1999.- `POST /api/sessions/:sessionId/messages/click-button` sends a structured button/list reply against a stored WhatsApp Business prompt on Baileys (whatsapp-web.js returns `501`). Classic `buttonsMessage` / `templateMessage` / `listMessage` prompts are supported; native-flow `interactiveMessage` replies are unverified. Thanks @gabrielmmoraes1999.diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 9fc444705..81acb2f0a 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -179,6 +179,7 @@ export interface ApiKey {role: 'admin' | 'operator' | 'viewer';allowedIps?: string[];allowedSessions?: string[];+ allowedChats?: string[];isActive: boolean;expiresAt?: string;lastUsedAt?: string;@@ -976,6 +977,7 @@ export const apiKeyApi = {allowedIps?: string[];allowedSessions?: string[];expiresAt?: string;+ allowedChats?: string[];}) =>request<CreatedApiKey>('/auth/api-keys', {method: 'POST',@@ -989,6 +991,7 @@ export const apiKeyApi = {allowedIps?: string[];allowedSessions?: string[];expiresAt?: string;+ allowedChats?: string[];},) =>request<ApiKey>(`/auth/api-keys/${id}`, {diff --git a/openapi.json b/openapi.jsonindex 6243f7a57..d0a57ecb4 100644--- a/openapi.json+++ b/openapi.json@@ -9947,6 +9947,17 @@"type": "string"}},+ "allowedChats": {+ "description": "Chat ids this key may read and send to — a curated allowlist independent of `allowedSessions`. Entries are a group `<id>@g.us`, a contact `<phone>@c.us` / `<lid>@lid`, or a bare phone number. A contact entry also matches its resolved `@lid` form (and vice versa) through the lid mapping table. Omit or leave empty to let the key reach every chat.",+ "example": [+ "[email protected]",+ ],+ "type": "array",+ "items": {+ "type": "string"+ }+ },"expiresAt": {"type": "string","description": "Expiration date (ISO 8601)",@@ -9990,6 +10001,12 @@"type": "string"}},+ "allowedChats": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },"isActive": {"type": "boolean"},@@ -10058,6 +10075,12 @@"type": "string"}},+ "allowedChats": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },"isActive": {"type": "boolean"},@@ -10113,6 +10136,12 @@"type": "string"}},+ "allowedChats": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },"expiresAt": {"type": "string"}diff --git a/src/common/security/chat-scope.spec.ts b/src/common/security/chat-scope.spec.tsnew file mode 100644index 000000000..d25cfb65e--- /dev/null+++ b/src/common/security/chat-scope.spec.ts@@ -0,0 +1,68 @@+import { buildChatScope, chatScopeAllows, filterByChatScope, isChatScopeRestricted } from './chat-scope';++const PHONE = '919999999999';+const LID = '555000111';+const directory = {+ resolveLid: (jid: string) => (jid.startsWith(`${LID}@lid`) ? PHONE : null),+ lidsForPhone: (phone: string) => (phone === PHONE ? [LID] : []),+};++describe('chat-scope', () => {+ it('treats NULL/empty as unrestricted', () => {+ expect(isChatScopeRestricted(null)).toBe(false);+ expect(isChatScopeRestricted([])).toBe(false);+ expect(buildChatScope(null)).toBeNull();+ expect(buildChatScope([])).toBeNull();+ expect(chatScopeAllows(null, '[email protected]')).toBe(true);+ });++ it('admits an allowlisted group and rejects any other', () => {+ const scope = buildChatScope(['[email protected]']);+ expect(chatScopeAllows(scope, '[email protected]')).toBe(true);+ expect(chatScopeAllows(scope, '[email protected]')).toBe(false);+ // A group entry must not admit a contact, and vice versa.+ expect(chatScopeAllows(scope, '[email protected]')).toBe(false);+ });++ it('matches a phone entry against the @lid form through the directory', () => {+ const scope = buildChatScope([`${PHONE}@c.us`], directory);+ expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ expect(chatScopeAllows(scope, `${LID}@lid`)).toBe(true);+ expect(chatScopeAllows(scope, '888000222@lid')).toBe(false);+ });++ it('matches a @lid entry against the phone form through the directory', () => {+ const scope = buildChatScope([`${LID}@lid`], directory);+ expect(chatScopeAllows(scope, `${LID}@lid`)).toBe(true);+ expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ });++ it('leaves an unmapped @lid outside the fence', () => {+ const scope = buildChatScope([`${PHONE}@c.us`], directory);+ expect(chatScopeAllows(scope, '777000333@lid')).toBe(false);+ });++ it('accepts a bare phone number as a contact entry', () => {+ const scope = buildChatScope([PHONE], directory);+ expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ expect(chatScopeAllows(scope, `${LID}@lid`)).toBe(true);+ });++ it('normalizes the @s.whatsapp.net dialect to the same contact', () => {+ const scope = buildChatScope([`${PHONE}@s.whatsapp.net`]);+ expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ });++ it('never admits status, channels or broadcast lists', () => {+ const scope = buildChatScope(['[email protected]', `${PHONE}@c.us`]);+ expect(chatScopeAllows(scope, 'status@broadcast')).toBe(false);+ expect(chatScopeAllows(scope, '123@newsletter')).toBe(false);+ expect(chatScopeAllows(scope, '123@broadcast')).toBe(false);+ });++ it('filters a list to the fenced chats, leaving an unrestricted key untouched', () => {+ const rows = [{ id: '[email protected]' }, { id: '[email protected]' }, { id: `${PHONE}@c.us` }];+ expect(filterByChatScope(buildChatScope(['[email protected]']), rows, r => r.id)).toEqual([{ id: '[email protected]' }]);+ expect(filterByChatScope(null, rows, r => r.id)).toEqual(rows);+ });+});diff --git a/src/common/security/chat-scope.ts b/src/common/security/chat-scope.tsnew file mode 100644index 000000000..44ceb0d2b--- /dev/null+++ b/src/common/security/chat-scope.ts@@ -0,0 +1,123 @@+/**+ * Resolve the effective chat filter for a scoped read or send, mirroring `session-scope.ts`.+ *+ * An API key's `allowedChats` is a curated allowlist of chat ids — groups, and/or individual+ * contacts — independent of `allowedSessions`. A key with no allowlist (NULL/empty) is unrestricted;+ * with one, it may only read or send to chats inside the fence.+ *+ * Matching is not a string comparison. WhatsApp addresses the same contact through several dialects+ * (`<phone>@c.us`, `<lid>@lid`, and their `@s.whatsapp.net` twin), so an allowlist entry written as+ * a phone must also match the contact's `@lid` form, and vice versa. That cross-mapping is supplied+ * by the caller as a {@link ChatScopeDirectory} backed by the shared lid<->phone table. An+ * unmapped `@lid` stays outside the fence: absent a mapping there is no way to prove it is the+ * allowlisted contact, so it is not admitted.+ *+ * The comparison key is the *user-part* (domain + device suffix stripped). Contacts and groups are+ * kept in separate sets so a group id can never match a contact entry.+ */++/** Lid<->phone lookups, backed by the persisted lid mapping table. Both are pure reads. */+export interface ChatScopeDirectory {+ /** The phone digits a `<lid>@lid` resolves to, or null when it is unmapped. */+ resolveLid(jid: string): string | null;+ /** The <lid> user-parts currently mapped to a phone's digits. */+ lidsForPhone(phone: string): string[];+}++/** A compiled allowlist: user-parts to admit, split by whether they name a group or a contact. */+export interface ChatScope {+ contacts: Set<string>;+ groups: Set<string>;+}++/** A bare phone number (MSISDN digits) — accepted as a convenience in place of `<phone>@c.us`. */+const BARE_NUMBER = /^\d{5,}$/;++/** The user-part of a JID: domain and multi-device suffix stripped (`628:[email protected]` -> `628`). */+function userPart(jid: string): string {+ return jid.split('@')[0].split(':')[0];+}++/** The domain of a JID, lowercased, or `''` when it has none. */+function domainOf(jid: string): string {+ const at = jid.lastIndexOf('@');+ return at === -1 ? '' : jid.slice(at + 1).toLowerCase();+}++/** True when the key carries a non-empty allowlist, i.e. is actually fenced. */+export function isChatScopeRestricted(allowedChats: string[] | null | undefined): boolean {+ return (allowedChats?.length ?? 0) > 0;+}++/**+ * Compile an `allowedChats` allowlist into a {@link ChatScope}, or `null` for "unrestricted"+ * (NULL/empty). Contact entries are expanded with their cross-dialect forms through `directory`: a+ * phone entry gains its known lids (and a `@lid` entry its phone), so either form matches the other+ * later.+ */+export function buildChatScope(+ allowedChats: string[] | null | undefined,+ directory?: ChatScopeDirectory,+): ChatScope | null {+ if (!isChatScopeRestricted(allowedChats)) return null;+ const contacts = new Set<string>();+ const groups = new Set<string>();+ for (const raw of allowedChats as string[]) {+ const entry = raw.trim();+ if (!entry) continue;+ const domain = domainOf(entry);+ const user = userPart(entry);+ if (domain === 'g.us') {+ groups.add(user);+ continue;+ }+ if (domain && domain !== 'c.us' && domain !== 's.whatsapp.net' && domain !== 'lid') {+ // status@broadcast, newsletters, broadcast lists and anything unrecognized are not chattable+ // contacts; admit nothing for them.+ continue;+ }+ if (!BARE_NUMBER.test(user)) continue;+ contacts.add(user);+ if (domain === 'c.us' || domain === 's.whatsapp.net') {+ for (const lid of directory?.lidsForPhone(user) ?? []) contacts.add(userPart(lid));+ } else if (domain === 'lid') {+ const phone = directory?.resolveLid(entry);+ if (phone) contacts.add(userPart(phone));+ } else {+ // Bare number: cross-map to its lids as well.+ for (const lid of directory?.lidsForPhone(user) ?? []) contacts.add(userPart(lid));+ }+ }+ return { contacts, groups };+}++/**+ * Whether `chatId` falls inside `scope`. A `null` scope is unrestricted and admits everything; a+ * scoped one admits a group only by group id and a contact only by a user-part in the contact set+ * (phone or mapped lid). Special channels and unknown ids never match a contact entry.+ */+export function chatScopeAllows(scope: ChatScope | null, chatId: string): boolean {+ if (scope === null) return true;+ const domain = domainOf(chatId);+ const user = userPart(chatId);+ if (domain === 'g.us') return scope.groups.has(user);+ if (domain === 'c.us' || domain === 's.whatsapp.net' || domain === 'lid') return scope.contacts.has(user);+ return false;+}++/**+ * Filter `items` down to the chats a scope admits, keyed by `chatIdOf`. A `null` scope returns the+ * list unchanged. List endpoints (`/chats`, `/contacts`, `/groups`, `/search`, …) use this instead+ * of rejecting, because they have no single chat in the path to refuse.+ */+export function filterByChatScope<T>(+ scope: ChatScope | null,+ items: readonly T[],+ chatIdOf: (item: T) => string | null | undefined,+): T[] {+ if (scope === null) return [...items];+ return items.filter(item => {+ const id = chatIdOf(item);+ return id != null && chatScopeAllows(scope, id);+ });+}diff --git a/src/database/migrations-main/1786600000000-AddApiKeyAllowedChats.ts b/src/database/migrations-main/1786600000000-AddApiKeyAllowedChats.tsnew file mode 100644index 000000000..0343e7b6f--- /dev/null+++ b/src/database/migrations-main/1786600000000-AddApiKeyAllowedChats.ts@@ -0,0 +1,41 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `allowedChats` to `api_keys` — the chat-level allowlist that scopes a key to chosen chats+ * (a curated set of groups, and/or individual contacts) next to the existing session scope.+ *+ * NULL/empty means "every chat", the same fail-open semantic as `allowedSessions`, and the two are+ * independent: a key may carry either list, both, or neither. The column is `simple-array` on the+ * entity, so it is stored as a comma-joined `text` column here, exactly like `allowedSessions`.+ *+ * Runs on the **main** connection (auth), which is always SQLite. Idempotent: the column is probed+ * before the ALTER, so a run interrupted after the DDL still completes and a database previously+ * created by `synchronize` is safe to adopt.+ */+export class AddApiKeyAllowedChats1786600000000 implements MigrationInterface {+ name = 'AddApiKeyAllowedChats1786600000000';++ private async hasColumn(queryRunner: QueryRunner, name: string): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'api_keys' AND column_name = '${name}'`,+ )) as unknown[];+ return rows.length > 0;+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("api_keys")`)) as Array<{ name: string }>;+ return rows.some(r => r.name === name);+ }++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await this.hasColumn(queryRunner, 'allowedChats'))) {+ await queryRunner.query(`ALTER TABLE "api_keys" ADD COLUMN "allowedChats" text NULL`);+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (await this.hasColumn(queryRunner, 'allowedChats')) {+ await queryRunner.query(`ALTER TABLE "api_keys" DROP COLUMN "allowedChats"`);+ }+ }+}diff --git a/src/database/migrations-main/__tests__/1786600000000-AddApiKeyAllowedChats.spec.ts b/src/database/migrations-main/__tests__/1786600000000-AddApiKeyAllowedChats.spec.tsnew file mode 100644index 000000000..1f31de5b6--- /dev/null+++ b/src/database/migrations-main/__tests__/1786600000000-AddApiKeyAllowedChats.spec.ts@@ -0,0 +1,62 @@+import { DataSource } from 'typeorm';+import { CreateAuthAuditTables1779900000000 } from '../1779900000000-CreateAuthAuditTables';+import { AddApiKeyAllowedChats1786600000000 } from '../1786600000000-AddApiKeyAllowedChats';++/**+ * Regression lock: the main-connection migration must add `allowedChats` to `api_keys` so a deploy+ * with `MAIN_DATABASE_SYNCHRONIZE=false` can persist and enforce a chat-scoped key.+ */+describe('AddApiKeyAllowedChats migration', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [], synchronize: false });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const columns = async (): Promise<string[]> => {+ const qr = ds.createQueryRunner();+ const rows = (await qr.query(`PRAGMA table_info("api_keys")`)) as Array<{ name: string }>;+ await qr.release();+ return rows.map(r => r.name);+ };++ it('adds the nullable allowedChats column on the existing api_keys table', async () => {+ const qr = ds.createQueryRunner();+ await new CreateAuthAuditTables1779900000000().up(qr);+ expect(await columns()).not.toContain('allowedChats');++ await new AddApiKeyAllowedChats1786600000000().up(qr);+ expect(await columns()).toContain('allowedChats');++ await qr.query("INSERT INTO api_keys (id, name, keyHash, keyPrefix) VALUES ('1', 'k', 'hash', 'pref')");+ const rows = (await qr.query("SELECT allowedChats FROM api_keys WHERE id = '1'")) as Array<{+ allowedChats: string | null;+ }>;+ expect(rows[0].allowedChats).toBeNull();+ await qr.release();+ });++ it('is idempotent', async () => {+ const qr = ds.createQueryRunner();+ await new CreateAuthAuditTables1779900000000().up(qr);+ const migration = new AddApiKeyAllowedChats1786600000000();+ await migration.up(qr);+ await expect(migration.up(qr)).resolves.not.toThrow();+ await qr.release();+ });++ it('down() drops the column', async () => {+ const qr = ds.createQueryRunner();+ await new CreateAuthAuditTables1779900000000().up(qr);+ const migration = new AddApiKeyAllowedChats1786600000000();+ await migration.up(qr);+ await migration.down(qr);+ expect(await columns()).not.toContain('allowedChats');+ await qr.release();+ });+});diff --git a/src/modules/auth/api-key-authorization.ts b/src/modules/auth/api-key-authorization.tsindex bee3dfffe..ff1652800 100644--- a/src/modules/auth/api-key-authorization.ts+++ b/src/modules/auth/api-key-authorization.ts@@ -26,10 +26,14 @@ export function apiKeyExpiryTime(value: Date | string | null | undefined): numbe}/** The columns that decide what a key may do. Everything else on the row is descriptive or advisory. */-export type ApiKeyAuthorization = Pick<ApiKey, 'role' | 'allowedIps' | 'allowedSessions' | 'expiresAt'>;+export type ApiKeyAuthorization = Pick<+ ApiKey,+ 'role' | 'allowedIps' | 'allowedSessions' | 'allowedChats' | 'expiresAt'+>;/**- * A stable string for what a key is AUTHORIZED to do: role, IP allowlist, session scope, expiry.+ * A stable string for what a key is AUTHORIZED to do: role, IP allowlist, session scope, chat+ * scope, expiry.* Two rows sharing a fingerprint authorize identically, so any other column moving must leave it* untouched, in particular `lastUsedAt`/`usageCount`/`updatedAt`, which the usage tracker rewrites* for every key in active use. A fingerprint that moved with them would disconnect every live@@ -44,5 +48,11 @@ export function apiKeyAuthorizationFingerprint(key: ApiKeyAuthorization): stringconst normalized = normalizeScopeList(list);return normalized ? [...normalized].sort() : null;};- return JSON.stringify([key.role, scope(key.allowedIps), scope(key.allowedSessions), apiKeyExpiryTime(key.expiresAt)]);+ return JSON.stringify([+ key.role,+ scope(key.allowedIps),+ scope(key.allowedSessions),+ scope(key.allowedChats),+ apiKeyExpiryTime(key.expiresAt),+ ]);}diff --git a/src/modules/auth/api-key-usage-write-scope.spec.ts b/src/modules/auth/api-key-usage-write-scope.spec.tsindex 564e567b2..205c05c12 100644--- a/src/modules/auth/api-key-usage-write-scope.spec.ts+++ b/src/modules/auth/api-key-usage-write-scope.spec.ts@@ -32,6 +32,7 @@ function makeRow(overrides: Partial<ApiKey> = {}): ApiKey {role: ApiKeyRole.OPERATOR,allowedIps: null,allowedSessions: null,+ allowedChats: null,isActive: true,expiresAt: null,lastUsedAt: null,diff --git a/src/modules/auth/auth.module.ts b/src/modules/auth/auth.module.tsindex a9291e8a2..2eb4a80c8 100644--- a/src/modules/auth/auth.module.ts+++ b/src/modules/auth/auth.module.ts@@ -4,6 +4,7 @@ import { APP_GUARD } from '@nestjs/core';import { ApiKey } from './entities/api-key.entity';import { AuthService } from './auth.service';import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';+import { ChatScopeService } from './chat-scope.service';import { AuthController } from './auth.controller';import { AuthValidateController } from './auth-validate.controller';import { ApiKeyGuard } from './guards/api-key.guard';@@ -16,6 +17,7 @@ import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throproviders: [AuthService,ApiKeyUsageTracker,+ ChatScopeService,{provide: APP_GUARD,useClass: ProxyAwareThrottlerGuard,@@ -25,6 +27,6 @@ import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throuseClass: ApiKeyGuard,},],- exports: [AuthService],+ exports: [AuthService, ChatScopeService],})export class AuthModule {}diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 08789a344..d94b70440 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -24,6 +24,7 @@ function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {role: ApiKeyRole.OPERATOR,allowedIps: null,allowedSessions: null,+ allowedChats: null,isActive: true,expiresAt: null,lastUsedAt: null,diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex afa1bf55a..9d19e346e 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -185,6 +185,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {role: dto.role || ApiKeyRole.OPERATOR,allowedIps: dto.allowedIps || null,allowedSessions: normalizeScopeList(dto.allowedSessions),+ allowedChats: normalizeScopeList(dto.allowedChats),expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,});@@ -231,6 +232,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {role: apiKey.role,allowedIps: apiKey.allowedIps,allowedSessions: apiKey.allowedSessions,+ allowedChats: apiKey.allowedChats,expiresAt: apiKey.expiresAt,};@@ -239,6 +241,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {if (dto.role) patch.role = dto.role;if (dto.allowedIps !== undefined) patch.allowedIps = dto.allowedIps;if (dto.allowedSessions !== undefined) patch.allowedSessions = normalizeScopeList(dto.allowedSessions);+ if (dto.allowedChats !== undefined) patch.allowedChats = normalizeScopeList(dto.allowedChats);if (dto.expiresAt !== undefined) patch.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;let saved: ApiKey;diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.tsnew file mode 100644index 000000000..133e4554b--- /dev/null+++ b/src/modules/auth/chat-scope-coverage.spec.ts@@ -0,0 +1,169 @@+// Structural guard for the chat-scope class of bug: an API key restricted with `allowedChats` must+// not reach a chat outside its fence.+//+// There are two enforcement shapes, and this spec pins both:+//+// 1. PATH — a handler with a `:chatId` / `:groupId` / `:contactId` route param is fenced by the+// ApiKeyGuard (api-key.guard.ts), the same way `allowedSessions` fences a `:sessionId`.+// 2. QUERY / BODY — a chat id that travels in `?chatId=` or in the request body cannot be seen by+// the guard's route-param fence. The guard reads `body.chatId` (every send DTO names it that),+// and handlers that take `@Query('chatId')` must scope through ChatScopeService.+//+// This spec fails when a handler takes a chat id in the query or body and is neither covered by the+// guard's body rule nor known to this file — so a later endpoint cannot bypass the fence silently.+// Known-uncovered handlers are listed in ALLOWLIST with the reason they are not yet fenced; each+// entry is work still owed, and the list is expected to shrink to empty.+import { readdirSync, readFileSync } from 'fs';+import { basename, join, sep } from 'path';++/**+ * Route params the ApiKeyGuard fences as chat ids. Kept in sync with the guard by the assertion+ * below, so narrowing the guard cannot silently drop a param class.+ */+const GUARD_CHAT_PARAMS = ['chatId', 'groupId', 'contactId'];++/**+ * Handlers that take an in-body or in-query chat id and are not yet fenced, awaiting the follow-up+ * slices of the chat-scope feature. Key format: `<controller file basename> :: <handler name>`.+ * Every entry needs a reason. This list is expected to shrink to empty.+ */+const ALLOWLIST = new Map<string, string>([+ ['message.controller.ts :: getMessages', 'GET /messages without chatId: require chatId or filter the page'],+ ['message.controller.ts :: sendBulk', 'bulk send: each items[].chatId must be checked'],+ ['message.controller.ts :: forward', 'forward target travels as `to`, not chatId'],+]);++/**+ * Request DTOs that carry a chat id, mapped to how the id is named. `chatId` is fenced centrally by+ * the ApiKeyGuard's body rule; any other chat-targeting property (e.g. forward's `to`) is not, so a+ * `@Body()` of that shape is an offender until a handler checks it or it is allowlisted.+ */+function chatBearingDtoClasses(dir: string): Map<string, 'chatId' | 'other'> {+ const out = new Map<string, 'chatId' | 'other'>();+ const walk = (current: string): void => {+ for (const entry of readdirSync(current, { withFileTypes: true })) {+ const full = join(current, entry.name);+ if (entry.isDirectory()) {+ walk(full);+ continue;+ }+ if (!entry.name.endsWith('.ts') || entry.name.endsWith('.spec.ts')) continue;+ const source = readFileSync(full, 'utf8');+ // Split on class boundaries so a chatId in one class does not mark an earlier one.+ for (const chunk of source.split(/export\s+class\s+/).slice(1)) {+ const name = /^([A-Za-z0-9_]+)/.exec(chunk)?.[1];+ if (!name) continue;+ if (/\bchatId[!?]?\s*:/.test(chunk)) out.set(name, 'chatId');+ else if (/\b(?:to|recipient)[!?]?\s*:/.test(chunk)) out.set(name, 'other');+ }+ }+ };+ walk(dir);+ return out;+}++/** Return handlers that take a chat id in the query or body but do not use ChatScopeService. */+export function handlersMissingChatScope(source: string, chatDtos: Map<string, 'chatId' | 'other'>): string[] {+ const offenders: string[] = [];+ // Two-space indentation is the controller convention; requiring it keeps a deeper call inside a+ // method body (` this.svc.get(`) from being mistaken for a handler declaration.+ const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)\s*[:{]/gm;+ const matches: { name: string; from: number }[] = [];+ for (let m = handlerRe.exec(source); m !== null; m = handlerRe.exec(source)) {+ matches.push({ name: m[2], from: m.index });+ }+ for (let i = 0; i < matches.length; i++) {+ const { name, from } = matches[i];+ const to = matches[i + 1]?.from ?? source.length;+ const body = source.slice(from, to);+ if (name === 'constructor') continue;+ // Guard-covered path param: the guard fences it, nothing to do here.+ if (new RegExp(`@Param\\(\\s*['"](?:${GUARD_CHAT_PARAMS.join('|')})['"]\\s*\\)`).test(body)) continue;+ const takesChatIdQuery = /@Query\(\s*['"]chatId['"]\s*\)/.test(body);+ const bodyDto = /@Body\(\)\s*[A-Za-z0-9_]+\s*:\s*([A-Za-z0-9_]+)/.exec(body)?.[1];+ // A `chatId` body is fenced by the guard; any other chat-targeting body field is not.+ const takesUnfencedChatBody = bodyDto !== undefined && chatDtos.get(bodyDto) === 'other';+ if (!takesChatIdQuery && !takesUnfencedChatBody) continue;+ if (/chatScope/.test(body)) continue;+ offenders.push(name);+ }+ return offenders;+}++function listControllerFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...listControllerFiles(full));+ else if (entry.name.endsWith('.controller.ts') && !entry.name.endsWith('.spec.ts')) out.push(full);+ }+ return out;+}++describe('chat-scoped keys cannot reach chats outside their allowedChats', () => {+ it('the guard fences both the path chat params and body.chatId', () => {+ const guard = readFileSync(join(__dirname, 'guards', 'api-key.guard.ts'), 'utf8');+ for (const param of GUARD_CHAT_PARAMS) {+ expect(guard).toContain(`request.params['${param}']`);+ }+ expect(guard).toMatch(/bodyChatId/);+ });++ it('flags a handler that reads @Query(chatId) without ChatScopeService', () => {+ const vulnerable = `+ async getThing(+ @Query('chatId') chatId?: string,+ ): Promise<unknown> {+ return this.svc.get(chatId);+ }+`;+ expect(handlersMissingChatScope(vulnerable, new Map())).toEqual(['getThing']);+ });++ it('clears a chatId body (the guard fences it) but flags another chat-targeting body field', () => {+ const source = `+ async sendThing(+ @Body() dto: SendThingDto,+ ): Promise<unknown> {+ return this.svc.send(dto);+ }+`;+ expect(handlersMissingChatScope(source, new Map([['SendThingDto', 'chatId']]))).toEqual([]);+ expect(handlersMissingChatScope(source, new Map([['SendThingDto', 'other']]))).toEqual(['sendThing']);+ });++ it('clears a path-param handler (the guard fences it) and a handler using chatScope', () => {+ const fenced = `+ async getThing(+ @Param('chatId') chatId: string,+ ): Promise<unknown> {+ return this.svc.get(chatId);+ }++ async sendThing(+ @CurrentApiKey() apiKey: ApiKey,+ @Body() dto: SendThingDto,+ ): Promise<unknown> {+ if (!this.chatScope.allows(apiKey, dto.chatId)) throw new ForbiddenException();+ return this.svc.send(dto);+ }+`;+ expect(handlersMissingChatScope(fenced, new Map([['SendThingDto', 'other']]))).toEqual([]);+ });++ it('no real controller takes a chat id without a fence or an allowlisted reason', () => {+ const modulesDir = join(__dirname, '..');+ const chatDtos = chatBearingDtoClasses(join(modulesDir));+ expect(chatDtos.size).toBeGreaterThan(0); // the DTO scan must not silently collapse+ const offenders: string[] = [];+ for (const file of listControllerFiles(modulesDir)) {+ const fileName = basename(file);+ const posixPath = file.split(sep).join('/');+ for (const handler of handlersMissingChatScope(readFileSync(file, 'utf8'), chatDtos)) {+ if (ALLOWLIST.has(`${fileName} :: ${handler}`)) continue;+ offenders.push(`${posixPath.replace(/.*\/src\//, 'src/')} :: ${handler}`);+ }+ }+ expect(offenders).toEqual([]);+ });+});diff --git a/src/modules/auth/chat-scope.service.ts b/src/modules/auth/chat-scope.service.tsnew file mode 100644index 000000000..cab409f19--- /dev/null+++ b/src/modules/auth/chat-scope.service.ts@@ -0,0 +1,63 @@+import { Injectable, Optional } from '@nestjs/common';+import { ApiKey } from './entities/api-key.entity';+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import {+ ChatScope,+ ChatScopeDirectory,+ buildChatScope,+ chatScopeAllows,+ filterByChatScope,+ isChatScopeRestricted,+} from '../../common/security/chat-scope';++/**+ * Compiles an API key's `allowedChats` into an enforceable {@link ChatScope} and answers membership,+ * wiring the shared lid<->phone directory so a phone entry matches its `@lid` form and vice versa.+ *+ * Provided by the global AuthModule so both the ApiKeyGuard (route-param fence) and the feature+ * controllers/services (list filtering and body-chat sends) share one definition of "inside the+ * fence". A missing lid directory degrades to exact-dialect matching only, which fails CLOSED for an+ * unmapped `@lid` — the documented behaviour.+ */+@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 compiled scope for a key, or `null` when unrestricted. */+ scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): ChatScope | null {+ return buildChatScope(apiKey?.allowedChats ?? null, this.directory());+ }++ /** Whether `chatId` is inside the key's fence (an unrestricted key admits every chat). */+ allows(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string): boolean {+ return chatScopeAllows(this.scopeFor(apiKey), chatId);+ }++ /** The subset of `items` whose chat id is inside the key's fence (unrestricted ⇒ unchanged). */+ filter<T>(+ apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined,+ items: readonly T[],+ chatIdOf: (item: T) => string | null | undefined,+ ): T[] {+ return filterByChatScope(this.scopeFor(apiKey), items, chatIdOf);+ }++ private directory(): ChatScopeDirectory | undefined {+ const store = this.lidStore;+ if (!store) return undefined;+ return {+ resolveLid: jid => store.resolveLid(jid),+ lidsForPhone: phone => store.lidsForPhone(phone),+ };+ }+}diff --git a/src/modules/auth/dto/api-key.dto.ts b/src/modules/auth/dto/api-key.dto.tsindex da1eb270a..a1d0cd44d 100644--- a/src/modules/auth/dto/api-key.dto.ts+++ b/src/modules/auth/dto/api-key.dto.ts@@ -13,6 +13,7 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';import { ApiKeyRole } from '../entities/api-key.entity';import { IsIpOrCidrConstraint } from './is-ip-or-cidr.validator';import { IsSessionIdConstraint } from './is-session-id.validator';+import { IsChatIdConstraint } from './is-chat-id.validator';export class CreateApiKeyDto {@ApiProperty({@@ -57,6 +58,21 @@ export class CreateApiKeyDto {@Validate(IsSessionIdConstraint, { each: true })allowedSessions?: string[];+ @ApiPropertyOptional({+ description:+ 'Chat ids this key may read and send to — a curated allowlist independent of `allowedSessions`. ' ++ 'Entries are a group `<id>@g.us`, a contact `<phone>@c.us` / `<lid>@lid`, or a bare phone number. ' ++ 'A contact entry also matches its resolved `@lid` form (and vice versa) through the lid mapping ' ++ 'table. Omit or leave empty to let the key reach every chat.',+ example: ['[email protected]', '[email protected]'],+ })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ @ArrayUnique()+ @Validate(IsChatIdConstraint, { each: true })+ allowedChats?: string[];+@ApiPropertyOptional({description: 'Expiration date (ISO 8601)',example: '2027-12-31T23:59:59Z',@@ -87,6 +103,9 @@ export class ApiKeyResponseDto {@ApiPropertyOptional()allowedSessions?: string[];+ @ApiPropertyOptional()+ allowedChats?: string[];+@ApiProperty()isActive!: boolean;@@ -148,6 +167,14 @@ export class UpdateApiKeyDto {@Validate(IsSessionIdConstraint, { each: true })allowedSessions?: string[];+ @ApiPropertyOptional()+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ @ArrayUnique()+ @Validate(IsChatIdConstraint, { each: true })+ allowedChats?: string[];+@ApiPropertyOptional()@IsOptional()@IsDateString()diff --git a/src/modules/auth/dto/is-chat-id.validator.spec.ts b/src/modules/auth/dto/is-chat-id.validator.spec.tsnew file mode 100644index 000000000..53a35039e--- /dev/null+++ b/src/modules/auth/dto/is-chat-id.validator.spec.ts@@ -0,0 +1,29 @@+import { isChatId } from './is-chat-id.validator';++describe('isChatId', () => {+ it('accepts well-formed group, contact and lid ids', () => {+ expect(isChatId('[email protected]')).toBe(true);+ expect(isChatId('[email protected]')).toBe(true);+ expect(isChatId('[email protected]')).toBe(true);+ expect(isChatId('[email protected]')).toBe(true);+ expect(isChatId('555000111@lid')).toBe(true);+ expect(isChatId('919999999999')).toBe(true);+ });++ it('rejects the simple-array footguns (empty, comma, surrounding whitespace)', () => {+ expect(isChatId('')).toBe(false);+ expect(isChatId(' ')).toBe(false);+ expect(isChatId(' [email protected]')).toBe(false);+ expect(isChatId('[email protected] ')).toBe(false);+ expect(isChatId('[email protected],555@lid')).toBe(false);+ });++ it('rejects non-chat ids and special channels', () => {+ expect(isChatId('not-a-jid')).toBe(false);+ expect(isChatId('status@broadcast')).toBe(false);+ expect(isChatId('123@newsletter')).toBe(false);+ expect(isChatId('123@broadcast')).toBe(false);+ expect(isChatId('[email protected]')).toBe(false);+ expect(isChatId(42)).toBe(false);+ });+});diff --git a/src/modules/auth/dto/is-chat-id.validator.ts b/src/modules/auth/dto/is-chat-id.validator.tsnew file mode 100644index 000000000..a31cad38c--- /dev/null+++ b/src/modules/auth/dto/is-chat-id.validator.ts@@ -0,0 +1,43 @@+import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';++/** A bare phone number (MSISDN digits), accepted as a convenience in place of a `<phone>@c.us` id. */+const BARE_NUMBER = /^\d{5,}$/;+/** A group id's user-part: digits, with the legacy `<a>-<b>@g.us` hyphenated form allowed. */+const GROUP_USER_PART = /^\d+(?:-\d+)?$/;+const PLAIN_DIGITS = /^\d{5,}$/;++/**+ * Whether a string is a WhatsApp chat id fit for `allowedChats` and safe to store in the+ * `simple-array` column.+ *+ * Two storage rules are load-bearing and shared with {@link isSessionId}: an empty/whitespace entry+ * joins to `''` and reads back as `[]`, which every enforcement site treats as "unrestricted" (fail+ * OPEN), and an entry containing a comma is split into two on read. Both are rejected here.+ *+ * Beyond that the entry must be a well-formed chat id: a group (`<id>@g.us`), an individual+ * (`<phone>@c.us` or `<lid>@lid`), or a bare phone number. A non-matching entry fails CLOSED (it+ * matches no chat), so the id shape is checked to catch typos rather than to gate the storage.+ */+export function isChatId(value: unknown): boolean {+ if (typeof value !== 'string') return false;+ const trimmed = value.trim();+ if (trimmed === '' || trimmed !== value || trimmed.includes(',')) return false;+ if (BARE_NUMBER.test(trimmed)) return true;+ const at = trimmed.lastIndexOf('@');+ if (at === -1) return false;+ const user = trimmed.slice(0, at).split(':')[0];+ const domain = trimmed.slice(at + 1).toLowerCase();+ if (domain === 'g.us') return GROUP_USER_PART.test(user);+ if (domain === 'c.us' || domain === 's.whatsapp.net' || domain === 'lid') return PLAIN_DIGITS.test(user);+ return false;+}++@ValidatorConstraint({ name: 'isChatId', async: false })+export class IsChatIdConstraint implements ValidatorConstraintInterface {+ validate(value: unknown): boolean {+ return isChatId(value);+ }+ defaultMessage(): string {+ return 'each allowedChats entry must be a chat id (a group "<id>@g.us", a contact "<phone>@c.us" / "<lid>@lid", or a bare phone number) with no surrounding whitespace and no comma';+ }+}diff --git a/src/modules/auth/entities/api-key.entity.ts b/src/modules/auth/entities/api-key.entity.tsindex fa75a1f05..3b18ea9af 100644--- a/src/modules/auth/entities/api-key.entity.ts+++ b/src/modules/auth/entities/api-key.entity.ts@@ -36,6 +36,13 @@ export class ApiKey {@Column({ type: 'simple-array', nullable: true })allowedSessions!: string[] | null;+ // Chat-level allowlist, independent of allowedSessions and the same fail-open semantic: NULL or+ // empty means "every chat". Entries are WhatsApp chat ids (a group `<id>@g.us`, a contact+ // `<phone>@c.us` / `<lid>@lid`, or a bare phone number). Enforced on the read surface and on+ // sends; see src/common/security/chat-scope.ts.+ @Column({ type: 'simple-array', nullable: true })+ allowedChats!: string[] | null;+@Column({ type: 'boolean', default: true })isActive!: boolean;diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 3ae2601ad..1e77fe5bb 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -4,6 +4,7 @@ import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { ApiKeyGuard } from './api-key.guard';import { AuthService } from '../auth.service';+import { ChatScopeService } from '../chat-scope.service';import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';import { AuditService } from '../../audit/audit.service';import { AuditAction } from '../../audit/entities/audit-log.entity';@@ -17,6 +18,7 @@ function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {role: ApiKeyRole.OPERATOR,allowedIps: null,allowedSessions: null,+ allowedChats: null,isActive: true,expiresAt: null,lastUsedAt: null,@@ -64,6 +66,7 @@ describe('ApiKeyGuard', () => {reflector,configService as ConfigService,auditService as AuditService,+ new ChatScopeService(),);}diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex bff900ee1..63d6f961a 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -3,6 +3,7 @@ import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { Request } from 'express';import { AuthService } from '../auth.service';+import { ChatScopeService } from '../chat-scope.service';import { ApiKeyRole } from '../entities/api-key.entity';import { REQUIRED_ROLE_KEY, PUBLIC_KEY, SESSION_SCOPED_KEY, UNSCOPED_KEY } from '../decorators/auth.decorators';import { resolveClientIp } from '../../../common/utils/ip';@@ -17,6 +18,7 @@ export class ApiKeyGuard implements CanActivate {private readonly reflector: Reflector,private readonly configService: ConfigService,private readonly auditService: AuditService,+ private readonly chatScope: ChatScopeService,) {}async canActivate(context: ExecutionContext): Promise<boolean> {@@ -92,6 +94,28 @@ export class ApiKeyGuard implements CanActivate {throw new ForbiddenException(`Insufficient permissions. Required: ${requiredRole}`);}+ // Chat fence. Routes that name a chat in the path — `:chatId`, `:groupId`, `:contactId` — are+ // rejected when the chat is outside the key's `allowedChats`, exactly as a session outside+ // `allowedSessions` is rejected inside validateApiKey. An unrestricted key (no allowlist) admits+ // every chat, so the model stays fail-open. List routes (`/chats`, `/contacts`, `/groups`, …) and+ // sends whose target travels in the body carry no such param; they scope themselves through+ // ChatScopeService, which is what the structural coverage spec enforces.+ const scopedChatId = (request.params['chatId'] || request.params['groupId'] || request.params['contactId']) as+ string | undefined;+ if (scopedChatId && !this.chatScope.allows(apiKey, scopedChatId)) {+ throw new ForbiddenException('API key not authorized for this chat');+ }++ // Body fence. Sends carry their target chat in the body, not the path (`POST /messages` and the+ // other write routes). Every send DTO names it `chatId`, so one check here fences the whole send+ // surface instead of one per handler — and a handler cannot forget it. Remaining body shapes+ // (bulk `items[].chatId`, forward `to`) are enumerated by the structural coverage spec.+ const body: unknown = request.body;+ const bodyChatId = body !== null && typeof body === 'object' ? (body as { chatId?: unknown }).chatId : undefined;+ if (typeof bodyChatId === 'string' && bodyChatId && !this.chatScope.allows(apiKey, bodyChatId)) {+ throw new ForbiddenException('API key not authorized for this chat');+ }+// Routes marked @RequireUnscopedKey carry no session dimension, so the allowedSessions check// above can never bite on them. A session-scoped key reaching such a surface (e.g. API-key// lifecycle management) could mint or widen credentials beyond its own confinement — reject it