Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(auth): default-deny chat-scoped keys, fence query/sends, fix lid matching
Bhavya Chopra41e4b6d4dadb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 540f657f6..6f757e01f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Message forwarding (`POST .../messages/forward`) and bulk message sending (`POST .../messages/bulk`) enforce the API key `allowedChats` allowlist: forward verifies both `fromChatId` and `toChatId`, while bulk send verifies every recipient in `messages[].chatId`, rejecting any unauthorized chat with `403` ([#1634](https://github.com/rmyndharis/OpenWA/issues/1634)).-- 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.+- API keys carry an optional `allowedChats` allowlist next to `allowedSessions`: a curated set of chats (groups and/or contacts) a key may reach, `null`/empty meaning unrestricted and independent of the session scope. A chat-restricted key is fenced **by default**: the `ApiKeyGuard` answers `403` on every route not marked `@ChatScoped`, so webhooks, automation rules, status, key management, channels and any route added later are closed without enumerating them, and the key cannot manage API keys (a chat-scoped admin no longer counts toward the last-admin invariant). On a marked route the guard checks every chat id it can see — the `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, and the `chatId` / `fromChatId` / `toChatId` / `messages[].chatId` body fields — rejecting an out-of-scope chat with `403` and a present-but-non-string chat field with `400`. Identity is resolved through the lid mapping table (`lid_mappings`, read deterministically rather than from the evictable cache): a phone entry matches its resolved `@lid` form and vice versa, a lid's digits are never read as a phone, and an unmapped `@lid` stays outside the fence. `GET /events` and the MCP mount refuse such a key at their handshake until the event/tool surfaces are filtered. A structural coverage spec fails if a marked handler is neither fenceable nor filters through `ChatScopeService`.- 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, since 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/src/common/security/chat-scope.spec.ts b/src/common/security/chat-scope.spec.tsindex d25cfb65e..5736af241 100644--- a/src/common/security/chat-scope.spec.ts+++ b/src/common/security/chat-scope.spec.ts@@ -1,68 +1,87 @@-import { buildChatScope, chatScopeAllows, filterByChatScope, isChatScopeRestricted } from './chat-scope';+import {+ buildChatScope,+ chatScopeAllows,+ filterByChatScope,+ isChatScopeRestricted,+ normalizeChatAllowList,+} from './chat-scope';const PHONE = '919999999999';const LID = '555000111';const directory = {- resolveLid: (jid: string) => (jid.startsWith(`${LID}@lid`) ? PHONE : null),+ resolveLid: (lid: string) => (lid === LID ? PHONE : null),lidsForPhone: (phone: string) => (phone === PHONE ? [LID] : []),};describe('chat-scope', () => {- it('treats NULL/empty as unrestricted', () => {+ it('treats NULL/empty as unrestricted', async () => {expect(isChatScopeRestricted(null)).toBe(false);expect(isChatScopeRestricted([])).toBe(false);- expect(buildChatScope(null)).toBeNull();- expect(buildChatScope([])).toBeNull();+ expect(await buildChatScope(null)).toBeNull();+ expect(await buildChatScope([])).toBeNull();expect(chatScopeAllows(null, '[email protected]')).toBe(true);});- it('admits an allowlisted group and rejects any other', () => {- const scope = buildChatScope(['[email protected]']);+ it('admits an allowlisted group and rejects any other', async () => {+ const scope = await 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);+ it('matches a phone entry against the @lid form through the directory', async () => {+ const scope = await buildChatScope([`${PHONE}@c.us`], directory);expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ expect(chatScopeAllows(scope, `${PHONE}@s.whatsapp.net`)).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);+ it('does NOT let a @lid entry admit the same-digits @c.us chat', async () => {+ const scope = await buildChatScope([`${LID}@lid`], directory);expect(chatScopeAllows(scope, `${LID}@lid`)).toBe(true);+ // A lid's digits are not a phone number: the phone form must resolve through the table, and+ // `<lid-digits>@c.us` is a different entity that must stay outside the fence.+ expect(chatScopeAllows(scope, `${LID}@c.us`)).toBe(false);expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);});- it('leaves an unmapped @lid outside the fence', () => {- const scope = buildChatScope([`${PHONE}@c.us`], directory);+ it('leaves an unmapped @lid outside the fence', async () => {+ const scope = await 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);+ it('accepts a bare phone number and matches its canonical chat', async () => {+ const scope = await buildChatScope([PHONE], directory);expect(chatScopeAllows(scope, `${PHONE}@c.us`)).toBe(true);+ expect(chatScopeAllows(scope, `${PHONE}@s.whatsapp.net`)).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`]);+ it('never admits status, channels or broadcast lists', async () => {+ const scope = await 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', () => {+ it('filters a list to the fenced chats, leaving an unrestricted key untouched', async () => {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(await buildChatScope(['[email protected]']), rows, r => r.id)).toEqual([{ id: '[email protected]' }]);expect(filterByChatScope(null, rows, r => r.id)).toEqual(rows);});});++describe('normalizeChatAllowList', () => {+ it('qualifies a bare number to @c.us and de-duplicates', () => {+ expect(normalizeChatAllowList([PHONE])).toEqual([`${PHONE}@c.us`]);+ expect(normalizeChatAllowList([PHONE, `${PHONE}@c.us`])).toEqual([`${PHONE}@c.us`]);+ });++ it('trims, drops empties, and keeps NULL for "unrestricted"', () => {+ expect(normalizeChatAllowList([' [email protected] ', ''])).toEqual(['[email protected]']);+ expect(normalizeChatAllowList([])).toBeNull();+ expect(normalizeChatAllowList(null)).toBeNull();+ });+});diff --git a/src/common/security/chat-scope.ts b/src/common/security/chat-scope.tsindex 44ceb0d2b..740d91dc2 100644--- a/src/common/security/chat-scope.ts+++ b/src/common/security/chat-scope.ts@@ -3,112 +3,95 @@** 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.+ * with one, it may reach only the 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.+ * Matching is expansion, not string comparison: each allowlist entry is expanded by+ * {@link resolveJidCandidates} into every JID that refers to the same entity (both user dialects,+ * the lid form of a phone and vice versa, through the directory), and an incoming chat id is+ * reduced to its own address forms before membership. That keeps a lid's digits from being read as+ * a phone: `555000111@lid` admits `555000111@lid` and, once mapped, its phone — never+ * `[email protected]`.*- * 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.+ * The directory for the authorization path must be the persisted lookup, not the evictable cache,+ * so the same key and chat cannot pass or fail depending on cache residency.*/+import { parseWaId } from '../../engine/identity/wa-id';+import { ContactDirectory, resolveJidCandidates } from '../../engine/identity/jid-candidates';-/** 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. */+/** A compiled allowlist: the exact JIDs a key may reach (an entry expands to several). */export interface ChatScope {- contacts: Set<string>;- groups: Set<string>;+ allowed: 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;}+/**+ * Canonicalize an `allowedChats` list for storage: trim, drop empties, and qualify a bare phone+ * number to `<digits>@c.us` so a saved entry is the same shape as the chats it must match. Mirrors+ * `normalizeScopeList`'s NULL-not-`[]` contract.+ */+export function normalizeChatAllowList(list: string[] | null | undefined): string[] | null {+ if (list == null) return null;+ const cleaned = list.map(entry => entry.trim()).filter(entry => entry.length > 0);+ const qualified = [...new Set(cleaned.map(entry => (BARE_NUMBER.test(entry) ? `${entry}@c.us` : entry)))];+ return qualified.length > 0 ? qualified : null;+}+/*** 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.+ * (NULL/empty). Each entry expands through `directory` — see {@link resolveJidCandidates}.*/-export function buildChatScope(+export async function buildChatScope(allowedChats: string[] | null | undefined,- directory?: ChatScopeDirectory,-): ChatScope | null {+ directory?: ContactDirectory,+): Promise<ChatScope | null> {if (!isChatScopeRestricted(allowedChats)) return null;- const contacts = new Set<string>();- const groups = new Set<string>();+ const allowed = 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));- }+ for (const jid of await resolveJidCandidates(entry, directory)) allowed.add(jid);+ }+ return { allowed };+}++/**+ * The stored address forms of an incoming chat id. A user id has two dialects; a lid and a group+ * each have one; a status/channel/broadcast/unknown id has none and so never matches a contact+ * entry (it is not a chattable contact).+ */+function addressForms(chatId: string): string[] {+ const parsed = parseWaId(chatId);+ switch (parsed.kind) {+ case 'user':+ return [`${parsed.userPart}@c.us`, `${parsed.userPart}@s.whatsapp.net`];+ case 'lid':+ return [`${parsed.userPart}@lid`];+ case 'group':+ return [`${parsed.userPart}@g.us`];+ default:+ return [];}- 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.+ * Whether `chatId` falls inside `scope`. A `null` scope is unrestricted and admits everything.*/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;+ return addressForms(chatId).some(form => scope.allowed.has(form));}/*** 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.+ * list unchanged. List endpoints use this instead of rejecting, because they have no single chat in+ * the path to refuse.*/export function filterByChatScope<T>(scope: ChatScope | null,diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.tsindex 7cfe3a24e..80b096f92 100644--- a/src/core/agent-tools/tool-invoker.spec.ts+++ b/src/core/agent-tools/tool-invoker.spec.ts@@ -34,6 +34,13 @@ describe('invokeTool', () => {expect(out).toEqual({ got: 5 });});+ it('refuses a chat-restricted key (chat-scoped tool arguments are a later slice)', async () => {+ const a = auth({ allowedChats: ['[email protected]'] });+ await expect(invokeTool(readTool, { n: 1 }, 'rawkey', a as unknown as AuthService)).rejects.toBeInstanceOf(+ ForbiddenException,+ );+ });+it('maps a zod failure to BadRequestException', async () => {await expect(invokeTool(readTool, { n: 'x' }, 'rawkey', auth() as unknown as AuthService)).rejects.toBeInstanceOf(BadRequestException,diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsindex 97ee1c0cf..6bc279c1d 100644--- a/src/core/agent-tools/tool-invoker.ts+++ b/src/core/agent-tools/tool-invoker.ts@@ -54,6 +54,13 @@ export async function invokeTool(if (tool.requiredRole && !authService.hasPermission(apiKey, tool.requiredRole)) {throw new ForbiddenException('API key lacks the required role');}++ // A chat-restricted key cannot be filtered on the tool surface yet (chat-scoped tool arguments+ // are handled in the follow-up slice), so refuse it outright rather than let a tool act on any+ // chat. Mirrors the REST guard's default-deny for unmarked routes.+ if ((apiKey.allowedChats?.length ?? 0) > 0) {+ throw new ForbiddenException('API key is restricted to selected chats');+ }} catch (error) {// auditMcpAuthFailure (the only current caller hook) filters to 401/403, so the BadRequestException// for a missing sessionId above is NOT audited (parity with the REST guard, which skips 400s).diff --git a/src/engine/identity/jid-candidates.spec.ts b/src/engine/identity/jid-candidates.spec.tsnew file mode 100644index 000000000..73447d71f--- /dev/null+++ b/src/engine/identity/jid-candidates.spec.ts@@ -0,0 +1,39 @@+import { resolveJidCandidates } from './jid-candidates';++const PHONE = '919999999999';+const LID = '555000111';+const directory = {+ resolveLid: (lid: string) => (lid === LID ? PHONE : null),+ lidsForPhone: (phone: string) => (phone === PHONE ? [LID] : []),+};++describe('resolveJidCandidates', () => {+ it('expands a phone into both user dialects and every lid mapped to it', async () => {+ const out = await resolveJidCandidates(`${PHONE}@c.us`, directory);+ expect(out).toEqual(expect.arrayContaining([`${PHONE}@c.us`, `${PHONE}@s.whatsapp.net`, `${LID}@lid`]));+ });++ it('expands a lid into its phone and never into the same-digits @c.us', async () => {+ const out = await resolveJidCandidates(`${LID}@lid`, directory);+ expect(out).toContain(`${LID}@lid`);+ expect(out).toContain(`${PHONE}@c.us`);+ expect(out).not.toContain(`${LID}@c.us`);+ });++ it('fails closed on a group, status or channel id (literal only)', async () => {+ expect(await resolveJidCandidates('[email protected]', directory)).toEqual(['[email protected]']);+ expect(await resolveJidCandidates('status@broadcast', directory)).toEqual(['status@broadcast']);+ expect(await resolveJidCandidates('123@newsletter', directory)).toEqual(['123@newsletter']);+ });++ it('qualifies a bare number', async () => {+ const out = await resolveJidCandidates(PHONE, directory);+ expect(out).toContain(`${PHONE}@c.us`);+ expect(out).toContain(`${LID}@lid`);+ });++ it('works without a directory (dialects only)', async () => {+ expect(await resolveJidCandidates(`${PHONE}@c.us`)).toEqual([`${PHONE}@c.us`, `${PHONE}@s.whatsapp.net`]);+ expect(await resolveJidCandidates(`${LID}@lid`)).toEqual([`${LID}@lid`]);+ });+});diff --git a/src/engine/identity/jid-candidates.ts b/src/engine/identity/jid-candidates.tsnew file mode 100644index 000000000..28c30da23--- /dev/null+++ b/src/engine/identity/jid-candidates.ts@@ -0,0 +1,44 @@+import { parseWaId } from './wa-id';++/**+ * Engine-neutral expansion of a WhatsApp JID into every form of the same entity (shared by the+ * message chat filter and the API-key chat scope, so the two cannot disagree about identity).+ *+ * - a `<phone>@c.us` / `@s.whatsapp.net` input yields the literal, both user dialects, and every lid+ * the directory maps to that phone;+ * - a `<lid>@lid` input yields the literal and the phone it resolves to (in both user dialects). It+ * deliberately does NOT mint `<lid-digits>@c.us`: a lid's digits are not a phone number, and+ * treating them as one would let `555000111@lid` match a `[email protected]` chat.+ * - a group / status / newsletter / broadcast id has exactly one stored form, so it yields only the+ * literal (expanding a group's digits into the user dialects could match an unrelated person).+ *+ * The last rule is why a non-user kind returns just the input: it fails closed on the literal id.+ */+export interface ContactDirectory {+ /** The phone digits a lid's user-part resolves to, or null/undefined when unmapped. */+ resolveLid(lid: string): string | null | undefined | Promise<string | null | undefined>;+ /** The lid user-parts currently mapped to a phone's digits. */+ lidsForPhone(phone: string): string[] | Promise<string[]>;+}++export async function resolveJidCandidates(value: string, directory?: ContactDirectory): Promise<string[]> {+ const parsed = parseWaId(value);+ if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {+ return [value];+ }+ if (parsed.kind === 'lid') {+ const candidates = new Set<string>([value]);+ const resolved = await directory?.resolveLid(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 directory?.lidsForPhone(phone)) ?? []) {+ candidates.add(`${lid}@lid`);+ }+ return [...candidates];+}diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.tsindex 632c93b99..50d5450cc 100644--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@ -148,6 +148,36 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {return 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.+ */+ async resolveLidPersisted(jid: string): Promise<string | null> {+ const lid = userPart(jid);+ const cached = this.getCached(lid);+ if (cached !== undefined) return cached;+ try {+ const row = await this.repo.findOne({ where: { lid } });+ return row?.phone ?? null;+ } catch {+ return 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));+ 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.+ }+ return [...lids];+ }+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 --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.tsindex de7ca7e6b..1f6bbba97 100644--- a/src/engine/identity/lid-mapping-store.spec.ts+++ b/src/engine/identity/lid-mapping-store.spec.ts@@ -403,3 +403,57 @@ describe('LidMappingStoreService — deterministic preload + repository fallbackexpect(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('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 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']);+ });++ it('lidsForPhonePersisted 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']);+ });+});diff --git a/src/modules/auth/api-key-authorization.ts b/src/modules/auth/api-key-authorization.tsindex ff1652800..9a840189a 100644--- a/src/modules/auth/api-key-authorization.ts+++ b/src/modules/auth/api-key-authorization.ts@@ -1,4 +1,5 @@import type { ApiKey } from './entities/api-key.entity';+import { normalizeChatAllowList } from '../../common/security/chat-scope';/*** Collapse an `allowedSessions` list to the two shapes the enforcement sites actually distinguish.@@ -52,7 +53,7 @@ export function apiKeyAuthorizationFingerprint(key: ApiKeyAuthorization): stringkey.role,scope(key.allowedIps),scope(key.allowedSessions),- scope(key.allowedChats),+ scope(normalizeChatAllowList(key.allowedChats)),apiKeyExpiryTime(key.expiresAt),]);}diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.tsindex d0c327962..0f1404d4c 100644--- a/src/modules/auth/auth.controller.ts+++ b/src/modules/auth/auth.controller.ts@@ -58,6 +58,7 @@ export class AuthController {role: apiKey.role,allowedIps: apiKey.allowedIps || undefined,allowedSessions: apiKey.allowedSessions || undefined,+ allowedChats: apiKey.allowedChats || undefined,isActive: apiKey.isActive,expiresAt: apiKey.expiresAt || undefined,lastUsedAt: apiKey.lastUsedAt || undefined,@@ -84,6 +85,7 @@ export class AuthController {role: k.role,allowedIps: k.allowedIps || undefined,allowedSessions: k.allowedSessions || undefined,+ allowedChats: k.allowedChats || undefined,isActive: k.isActive,expiresAt: k.expiresAt || undefined,lastUsedAt: k.lastUsedAt || undefined,@@ -109,6 +111,7 @@ export class AuthController {role: k.role,allowedIps: k.allowedIps || undefined,allowedSessions: k.allowedSessions || undefined,+ allowedChats: k.allowedChats || undefined,isActive: k.isActive,expiresAt: k.expiresAt || undefined,lastUsedAt: k.lastUsedAt || undefined,@@ -134,6 +137,7 @@ export class AuthController {role: key.role,allowedIps: key.allowedIps,allowedSessions: key.allowedSessions,+ allowedChats: key.allowedChats,expiresAt: key.expiresAt,});await this.auditService.logInfo(AuditAction.API_KEY_UPDATED, {@@ -152,6 +156,7 @@ export class AuthController {role: k.role,allowedIps: k.allowedIps || undefined,allowedSessions: k.allowedSessions || undefined,+ allowedChats: k.allowedChats || undefined,isActive: k.isActive,expiresAt: k.expiresAt || undefined,lastUsedAt: k.lastUsedAt || undefined,@@ -198,6 +203,7 @@ export class AuthController {role: k.role,allowedIps: k.allowedIps || undefined,allowedSessions: k.allowedSessions || undefined,+ allowedChats: k.allowedChats || undefined,isActive: k.isActive,expiresAt: k.expiresAt || undefined,lastUsedAt: k.lastUsedAt || undefined,diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex d94b70440..97c4f8b98 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -202,13 +202,14 @@ describe('AuthService', () => {}/** JS mirror of the guard's "usable admin" row predicate (the SQL definition lives in the- * service): an active, unexpired ADMIN key with no session scope. */+ * service): an active, unexpired ADMIN key with no session OR chat scope. */function isUsableAdminRow(key: ApiKey): boolean {return (key.role === ApiKeyRole.ADMIN &&key.isActive &&(!key.expiresAt || key.expiresAt.getTime() > Date.now()) &&- (!key.allowedSessions || key.allowedSessions.length === 0)+ (!key.allowedSessions || key.allowedSessions.length === 0) &&+ (!key.allowedChats || key.allowedChats.length === 0));}@@ -564,6 +565,10 @@ describe('AuthService', () => {// admin must be rejected like a demotion — otherwise the system locks itself out for good.const unscopedAdmin = (id: string) => createMockApiKey({ id, role: ApiKeyRole.ADMIN });const scopedAdmin = (id: string) => createMockApiKey({ id, role: ApiKeyRole.ADMIN, allowedSessions: ['sess-1'] });+ // A chat-scoped admin is likewise fenced out of key management (its routes are not+ // @ChatScoped, so the guard refuses it), so it must not count as a usable admin either.+ const chatScopedAdmin = (id: string) =>+ createMockApiKey({ id, role: ApiKeyRole.ADMIN, allowedChats: ['[email protected]'] });it('rejects deleting the last unscoped admin even while a session-scoped admin survives', async () => {setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);@@ -606,6 +611,27 @@ describe('AuthService', () => {await expect(service.findOne('admin-a')).resolves.toBeDefined();});+ it('rejects deleting the last unscoped admin even while a chat-scoped admin survives', async () => {+ setupKeys([unscopedAdmin('admin-a'), chatScopedAdmin('admin-chat')]);++ await expect(service.delete('admin-a')).rejects.toThrow(/last active admin/i);+ expect(repository.remove).not.toHaveBeenCalled();+ });++ it('rejects scoping the last unscoped admin to chats — the same capability-stripping', async () => {+ setupKeys([unscopedAdmin('admin-a'), chatScopedAdmin('admin-chat')]);++ await expect(service.update('admin-a', { allowedChats: ['[email protected]'] })).rejects.toThrow(/last active admin/i);+ expect(repository.save).not.toHaveBeenCalled();+ });++ it('lets a chat-scoped admin be deleted — it never counted toward the invariant', async () => {+ setupKeys([unscopedAdmin('admin-a'), chatScopedAdmin('admin-chat')]);++ await expect(service.delete('admin-chat')).resolves.toBeUndefined();+ await expect(service.findOne('admin-a')).resolves.toBeDefined();+ });+it('allows stripping an unscoped admin when another unscoped admin remains', async () => {setupKeys([unscopedAdmin('admin-a'), unscopedAdmin('admin-b'), scopedAdmin('admin-scoped')]);diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 9d19e346e..a4d18ff0a 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -18,6 +18,7 @@ import { createLogger } from '../../common/services/logger.service';import { readBootstrapKey, removeBootstrapKey, writeBootstrapKey } from './bootstrap-key-file';import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';import { apiKeyAuthorizationFingerprint, normalizeScopeList } from './api-key-authorization';+import { normalizeChatAllowList } from '../../common/security/chat-scope';import { EventsGateway, type ApiKeyEvictionReason } from '../events/events.gateway';/**@@ -185,7 +186,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {role: dto.role || ApiKeyRole.OPERATOR,allowedIps: dto.allowedIps || null,allowedSessions: normalizeScopeList(dto.allowedSessions),- allowedChats: normalizeScopeList(dto.allowedChats),+ allowedChats: normalizeChatAllowList(dto.allowedChats),expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,});@@ -221,7 +222,8 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {const removesOrSchedulesLastAdmin =(dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||(dto.expiresAt !== undefined && dto.expiresAt !== null) ||- (normalizeScopeList(dto.allowedSessions)?.length ?? 0) > 0;+ (normalizeScopeList(dto.allowedSessions)?.length ?? 0) > 0 ||+ (normalizeChatAllowList(dto.allowedChats)?.length ?? 0) > 0;// Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,// allowedIps, allowedSessions, or expiry can widen or restrict what an already-connected WebSocket@@ -241,7 +243,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.allowedChats !== undefined) patch.allowedChats = normalizeChatAllowList(dto.allowedChats);if (dto.expiresAt !== undefined) patch.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;let saved: ApiKey;@@ -336,7 +338,8 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {return (`${col('role')} = :adminRole AND ${col('isActive')} = 1 AND ` +`(${col('expiresAt')} IS NULL OR ${col('expiresAt')} > :guardNow) AND ` +- `(${col('allowedSessions')} = '' OR ${col('allowedSessions')} IS NULL)`+ `(${col('allowedSessions')} = '' OR ${col('allowedSessions')} IS NULL) AND ` ++ `(${col('allowedChats')} = '' OR ${col('allowedChats')} IS NULL)`);}diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.tsindex cb3ae8e62..16bd2a291 100644--- a/src/modules/auth/chat-scope-coverage.spec.ts+++ b/src/modules/auth/chat-scope-coverage.spec.ts@@ -1,43 +1,27 @@-// Structural guard for the chat-scope class of bug: an API key restricted with `allowedChats` must-// not reach a chat outside its fence.+// Structural guard for the chat-scope class of bug: a key restricted with `allowedChats` must not+// reach a chat outside its fence.//-// There are two enforcement shapes, and this spec pins both:+// The guard is DEFAULT DENY (api-key.guard.ts): a chat-restricted key is refused with 403 on every+// handler that is not marked @ChatScoped, so surfaces with no chat dimension (webhooks, automation+// rules, status, key management, channels) and every route added later stay closed without being+// enumerated. A marked handler must then be fenceable — the guard inspects the chat id it carries+// (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, or the `chatId` / `fromChatId` /+// `toChatId` / `messages[].chatId` body fields), OR the handler filters its list result through+// ChatScopeService.//-// 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.+// This spec fails when a marked handler is neither fenceable nor filters, so marking a handler can+// never quietly become a bypass.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'],-]);+/** Route params the ApiKeyGuard treats as a chat id. Asserted against the guard's own source below. */+export const GUARD_CHAT_ROUTE_PARAMS = ['chatId', 'groupId', 'contactId'];+/** Body fields the ApiKeyGuard treats as a chat id (bulk send nests `chatId` inside `messages[]`). */+export const GUARD_BODY_CHAT_FIELDS = ['chatId', 'fromChatId', 'toChatId'];-/**- * Request DTOs that carry a chat id, mapped to how the id is named. `chatId`, forward chats, and- * bulk messages are fenced centrally by the ApiKeyGuard's body rule; any other chat-targeting- * property 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'>();+/** Request DTO classes carrying a guard-fenced chat field. */+function chatBearingDtoClasses(dir: string): Set<string> {+ const out = new Set<string>();const walk = (current: string): void => {for (const entry of readdirSync(current, { withFileTypes: true })) {const full = join(current, entry.name);@@ -46,19 +30,16 @@ function chatBearingDtoClasses(dir: string): Map<string, 'chatId' | 'other'> {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)) {+ // Split on class boundaries so a field in one class does not mark an earlier one.+ for (const chunk of readFileSync(full, 'utf8')+ .split(/export\s+class\s+/)+ .slice(1)) {const name = /^([A-Za-z0-9_]+)/.exec(chunk)?.[1];if (!name) continue;- if (- /\b(?:chatId|toChatId|fromChatId)[!?]?\s*:/.test(chunk) ||- /\bmessages[!?]?\s*:\s*BulkMessageItemDto\[\]/.test(chunk)- ) {- out.set(name, 'chatId');- } else if (/\b(?:to|recipient)[!?]?\s*:/.test(chunk)) {- out.set(name, 'other');- }+ const field = GUARD_BODY_CHAT_FIELDS.some(f => new RegExp(`\\b${f}[!?]?\\s*:`).test(chunk));+ // Bulk send carries its recipients in an array field; the guard iterates it.+ const bulkArray = /\bmessages[!?]?\s*:\s*[\w.]*\[\]/.test(chunk);+ if (field || bulkArray) out.add(name);}}};@@ -66,30 +47,28 @@ function chatBearingDtoClasses(dir: string): Map<string, 'chatId' | 'other'> {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[] {+/**+ * Return @ChatScoped handlers in `source` that are neither fenceable by the guard nor filter through+ * ChatScopeService — i.e. marked handlers a chat-restricted key could reach for any chat.+ */+export function markedHandlersWithoutChatFence(source: string, chatDtos: Set<string>): 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 }[] = [];+ const matches: { name: string; from: number; decorators: string }[] = [];for (let m = handlerRe.exec(source); m !== null; m = handlerRe.exec(source)) {- matches.push({ name: m[2], from: m.index });+ matches.push({ name: m[2], from: m.index, decorators: m[1] ?? '' });}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 { name, from, decorators } = matches[i];+ if (!/@ChatScoped\(\)/.test(decorators)) continue;+ const body = source.slice(from, matches[i + 1]?.from ?? source.length);+ const hasPathChat = new RegExp(`@Param\\(\\s*['"](?:${GUARD_CHAT_ROUTE_PARAMS.join('|')})['"]\\s*\\)`).test(body);+ const hasQueryChat = /@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);+ const hasBodyChat = bodyDto !== undefined && chatDtos.has(bodyDto);+ // A list handler names no chat, so it must filter its result through ChatScopeService instead.+ const filtersChatScope = /\bchatScope\b/.test(body);+ if (!hasPathChat && !hasQueryChat && !hasBodyChat && !filtersChatScope) offenders.push(name);}return offenders;}@@ -104,73 +83,78 @@ function listControllerFiles(dir: string): string[] {return out;}-describe('chat-scoped keys cannot reach chats outside their allowedChats', () => {- it('the guard fences both the path chat params, body.chatId, forward chats, and bulk send messages', () => {+describe('a chat-restricted key can only reach a handler fenced to its allowedChats', () => {+ it('the guard denies by default and fences every chat id it can see', () => {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/);- expect(guard).toMatch(/fromChatId/);- expect(guard).toMatch(/toChatId/);- expect(guard).toMatch(/bodyMessages/);+ // Default deny: unmarked route with a restricted key ⇒ 403.+ expect(guard).toContain('CHAT_SCOPED_KEY');+ expect(guard).toContain('API key is restricted to selected chats');+ // The fence reads the route params, the query, and the body fields.+ for (const param of GUARD_CHAT_ROUTE_PARAMS) expect(guard).toContain(`'${param}'`);+ for (const field of GUARD_BODY_CHAT_FIELDS) expect(guard).toContain(`'${field}'`);+ expect(guard).toContain("['chatId']");+ expect(guard).toContain('messages');});- it('flags a handler that reads @Query(chatId) without ChatScopeService', () => {+ it('flags a marked handler with no chat id and no filtering', () => {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> {+ @ChatScoped()+ @Post('everything')+ async sendThing(@Body() dto: ThingDto): Promise<unknown> {return this.svc.send(dto);}`;- expect(handlersMissingChatScope(source, new Map([['SendThingDto', 'chatId']]))).toEqual([]);- expect(handlersMissingChatScope(source, new Map([['SendThingDto', 'other']]))).toEqual(['sendThing']);+ expect(markedHandlersWithoutChatFence(vulnerable, new Set())).toEqual(['sendThing']);});- it('clears a path-param handler (the guard fences it) and a handler using chatScope', () => {+ it('clears a marked handler with a path chat, a query chat, a body chat, or a filter', () => {const fenced = `- async getThing(- @Param('chatId') chatId: string,- ): Promise<unknown> {+ @ChatScoped()+ @Get(':chatId')+ async getOne(@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();+ @ChatScoped()+ @Get()+ async list(@Query('chatId') chatId?: string): Promise<unknown> {+ return this.svc.list(chatId);+ }++ @ChatScoped()+ @Post()+ async send(@Body() dto: SendThingDto): Promise<unknown> {return this.svc.send(dto);}++ @ChatScoped()+ @Get('chats')+ async chats(@CurrentApiKey() apiKey: ApiKey): Promise<unknown> {+ return this.chatScope.filter(apiKey, await this.svc.chats(), c => c.id);+ }`;- expect(handlersMissingChatScope(fenced, new Map([['SendThingDto', 'other']]))).toEqual([]);+ expect(markedHandlersWithoutChatFence(fenced, new Set(['SendThingDto']))).toEqual([]);});- it('no real controller takes a chat id without a fence or an allowlisted reason', () => {+ it('no marked controller handler is unfenced, and the scan is not vacuous', () => {const modulesDir = join(__dirname, '..');- const chatDtos = chatBearingDtoClasses(join(modulesDir));+ const chatDtos = chatBearingDtoClasses(modulesDir);expect(chatDtos.size).toBeGreaterThan(0); // the DTO scan must not silently collapse+ const files = listControllerFiles(modulesDir);+ expect(files.length).toBeGreaterThan(10);+ let marked = 0;const offenders: string[] = [];- for (const file of listControllerFiles(modulesDir)) {+ for (const file of files) {+ const source = readFileSync(file, 'utf8');+ marked += [...source.matchAll(/^ {2}@ChatScoped\(\)$/gm)].length;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}`);+ for (const handler of markedHandlersWithoutChatFence(source, chatDtos)) {+ offenders.push(`${posixPath.replace(/.*\/src\//, 'src/')} :: ${fileName} :: ${handler}`);}}+ // Non-vacuity: a scan that found no marked handlers would pass for the wrong reason.+ expect(marked).toBeGreaterThan(30);expect(offenders).toEqual([]);});});diff --git a/src/modules/auth/chat-scope.service.spec.ts b/src/modules/auth/chat-scope.service.spec.tsnew file mode 100644index 000000000..efce3f7fe--- /dev/null+++ b/src/modules/auth/chat-scope.service.spec.ts@@ -0,0 +1,51 @@+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] : [])),+ } 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(await 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 store = fakeStore();+ const svc = new ChatScopeService(store);+ 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, passing an unrestricted key through', async () => {+ const svc = new ChatScopeService(fakeStore());+ const rows = [{ id: '[email protected]' }, { id: '[email protected]' }];+ expect(await svc.filter({ allowedChats: ['[email protected]'] }, rows, r => r.id)).toEqual([{ id: '[email protected]' }]);+ 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 --git a/src/modules/auth/chat-scope.service.ts b/src/modules/auth/chat-scope.service.tsindex cab409f19..7a67861a1 100644--- a/src/modules/auth/chat-scope.service.ts+++ b/src/modules/auth/chat-scope.service.ts@@ -1,9 +1,9 @@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,chatScopeAllows,filterByChatScope,@@ -15,9 +15,10 @@ import {* 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.+ * controllers/services (list filtering) share one definition of "inside the fence". The directory+ * reads the persisted lid table, not the evictable in-memory mirror, so the answer is deterministic.+ * A missing directory degrades to exact-dialect matching only, which fails CLOSED for an unmapped+ * `@lid` — the documented behaviour.*/@Injectable()export class ChatScopeService {@@ -34,30 +35,30 @@ export class ChatScopeService {}/** The compiled scope for a key, or `null` when unrestricted. */- scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): ChatScope | null {+ scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): Promise<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);+ async allows(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string): Promise<boolean> {+ return chatScopeAllows(await this.scopeFor(apiKey), chatId);}/** The subset of `items` whose chat id is inside the key's fence (unrestricted ⇒ unchanged). */- filter<T>(+ async 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);+ ): Promise<T[]> {+ return filterByChatScope(await this.scopeFor(apiKey), items, chatIdOf);}- private directory(): ChatScopeDirectory | undefined {+ private directory(): ContactDirectory | undefined {const store = this.lidStore;if (!store) return undefined;return {- resolveLid: jid => store.resolveLid(jid),- lidsForPhone: phone => store.lidsForPhone(phone),+ resolveLid: userPart => store.resolveLidPersisted(userPart),+ lidsForPhone: phone => store.lidsForPhonePersisted(phone),};}}diff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.tsindex 1a2e62fee..2d30bffee 100644--- a/src/modules/auth/decorators/auth.decorators.ts+++ b/src/modules/auth/decorators/auth.decorators.ts@@ -7,6 +7,7 @@ export const REQUIRED_ROLE_KEY = 'requiredRole';export const PUBLIC_KEY = 'isPublic';export const SESSION_SCOPED_KEY = 'sessionScoped';export const UNSCOPED_KEY = 'requireUnscopedKey';+export const CHAT_SCOPED_KEY = 'chatScoped';/*** Mark a route as requiring a specific role@@ -38,6 +39,21 @@ export const Public = () => SetMetadata(PUBLIC_KEY, true);*/export const RequireUnscopedKey = () => SetMetadata(UNSCOPED_KEY, true);+/**+ * Mark a handler (or controller) a chat-restricted key — one carrying `allowedChats` — may reach,+ * when the handler's target chat is one the ApiKeyGuard can see: a `:chatId` / `:groupId` /+ * `:contactId` path param, a `chatId` / `fromChatId` / `toChatId` body field, or a `messages[]`+ * entry's `chatId`.+ *+ * This is an ALLOWLIST, not a restriction: a chat-restricted key is refused with 403 on every route+ * that is NOT marked, so surfaces with no chat dimension (webhooks, automation rules, status, key+ * management, channels) — and every route added later — stay closed without having to enumerate+ * them. A marked handler that lists chats instead of naming one must filter its result through+ * ChatScopeService; the structural coverage spec enforces both halves.+ * @example @ChatScoped() @Get(':chatId')+ */+export const ChatScoped = () => SetMetadata(CHAT_SCOPED_KEY, true);+/*** Get the current API key from request* @example @CurrentApiKey() apiKey: ApiKeydiff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 9ba87c4bc..213f29cc4 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -1,4 +1,4 @@-import { ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';+import { ExecutionContext, UnauthorizedException, ForbiddenException, BadRequestException } from '@nestjs/common';import { runWithRequestId, getRequestActor } from '../../../common/services/request-context';import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';@@ -8,6 +8,7 @@ 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';+import { CHAT_SCOPED_KEY } from '../decorators/auth.decorators';function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {return {@@ -34,6 +35,7 @@ function createMockContext(params: Record<string, string> = {},socketIp = '127.0.0.1',body?: unknown,+ query: Record<string, unknown> = {},): ExecutionContext {const request = {headers,@@ -41,6 +43,7 @@ function createMockContext(ip: socketIp,socket: { remoteAddress: socketIp },body,+ query,};return {@@ -58,6 +61,8 @@ describe('ApiKeyGuard', () => {let reflector: jest.Mocked<Reflector>;let configService: jest.Mocked<Partial<ConfigService>>;let auditService: jest.Mocked<Partial<AuditService>>;+ /** Per-call metadata the guard reads via Reflector; tests set only what they need. */+ let metadata: Record<string, unknown>;function buildGuard(trustedProxies: string[] = []): ApiKeyGuard {configService = {@@ -78,8 +83,9 @@ describe('ApiKeyGuard', () => {hasPermission: jest.fn(),};+ metadata = {};reflector = {- getAllAndOverride: jest.fn(),+ getAllAndOverride: jest.fn((key: string) => metadata[key]),} as unknown as jest.Mocked<Reflector>;auditService = {@@ -414,6 +420,12 @@ describe('ApiKeyGuard', () => {});describe('chat scope enforcement', () => {+ // The guard is default deny for a chat-restricted key: the handler must be marked @ChatScoped+ // to be reachable at all. These tests are about the membership fence, so mark the route.+ beforeEach(() => {+ metadata[CHAT_SCOPED_KEY] = true;+ });+const ALLOWED_GROUP = '[email protected]';const FORBIDDEN_GROUP = '[email protected]';const ALLOWED_CONTACT = '[email protected]';@@ -538,6 +550,48 @@ describe('ApiKeyGuard', () => {expect(await guard.canActivate(context)).toBe(true);});+ it('refuses a chat-restricted key on a route that is not marked @ChatScoped', async () => {+ delete metadata[CHAT_SCOPED_KEY];+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ const context = createMockContext({ 'x-api-key': 'key' }, {});+ await expect(guard.canActivate(context)).rejects.toThrow(+ new ForbiddenException('API key is restricted to selected chats'),+ );+ });++ it('fences ?chatId= on the query string', async () => {+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ const denied = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', undefined, { chatId: FORBIDDEN_GROUP });+ await expect(guard.canActivate(denied)).rejects.toThrow(+ new ForbiddenException('API key not authorized for this chat'),+ );++ const allowed = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', undefined, { chatId: ALLOWED_GROUP });+ expect(await guard.canActivate(allowed)).toBe(true);+ });++ it('rejects a present but non-string chat field instead of skipping it', async () => {+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ // The global ValidationPipe coerces with enableImplicitConversion, so a numeric chatId would+ // reach the handler as a string the fence never checked — refuse it here.+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', { chatId: 120363 });+ await expect(guard.canActivate(context)).rejects.toThrow(BadRequestException);+ });++ it('rejects a bulk `messages` field that is present but not an array', async () => {+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', { messages: 'nope' });+ await expect(guard.canActivate(context)).rejects.toThrow(BadRequestException);+ });+it('admits forward and bulk send for an unrestricted key (allowedChats null)', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);const apiKey = createMockApiKey({ allowedChats: null });diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex 4f0236447..399f7f487 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -1,11 +1,25 @@-import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';+import {+ Injectable,+ CanActivate,+ ExecutionContext,+ UnauthorizedException,+ ForbiddenException,+ BadRequestException,+} from '@nestjs/common';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 { ApiKey, ApiKeyRole } from '../entities/api-key.entity';+import {+ REQUIRED_ROLE_KEY,+ PUBLIC_KEY,+ SESSION_SCOPED_KEY,+ UNSCOPED_KEY,+ CHAT_SCOPED_KEY,+} from '../decorators/auth.decorators';+import { ChatScope, chatScopeAllows } from '../../../common/security/chat-scope';import { resolveClientIp } from '../../../common/utils/ip';import { setRequestActor } from '../../../common/services/request-context';import { AuditService } from '../../audit/audit.service';@@ -94,51 +108,20 @@ 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). Single sends name it `chatId`, bulk send names `messages[].chatId`, and- // forward names `fromChatId` and `toChatId`. Fenced centrally here so the whole send surface is- // protected and a handler cannot forget it.- const body: unknown = request.body;- if (body !== null && typeof body === 'object') {- const b = body as Record<string, unknown>;-- const bodyChatId = b.chatId;- if (typeof bodyChatId === 'string' && bodyChatId && !this.chatScope.allows(apiKey, bodyChatId)) {- throw new ForbiddenException('API key not authorized for this chat');- }-- const fromChatId = b.fromChatId;- if (typeof fromChatId === 'string' && fromChatId && !this.chatScope.allows(apiKey, fromChatId)) {- throw new ForbiddenException('API key not authorized for this chat');- }-- const toChatId = b.toChatId;- if (typeof toChatId === 'string' && toChatId && !this.chatScope.allows(apiKey, toChatId)) {- throw new ForbiddenException('API key not authorized for this chat');- }-- const bodyMessages = b.messages;- if (Array.isArray(bodyMessages)) {- for (const item of bodyMessages) {- const itemChatId =- item !== null && typeof item === 'object' ? (item as { chatId?: unknown }).chatId : undefined;- if (typeof itemChatId === 'string' && itemChatId && !this.chatScope.allows(apiKey, itemChatId)) {- throw new ForbiddenException('API key not authorized for this chat');- }- }+ // Chat fence — DEFAULT DENY. A key carrying `allowedChats` may reach only a handler marked+ // @ChatScoped, and only for a chat inside its allowlist. Surfaces with no chat dimension+ // (webhooks, automation rules, status, key management, channels) — and every route added later —+ // are refused without being enumerated. An unrestricted key (no allowlist) skips this entirely,+ // so the model stays fail-open for every key that was not scoped.+ if (this.chatScope.isRestricted(apiKey)) {+ const chatScoped = this.reflector.getAllAndOverride<boolean>(CHAT_SCOPED_KEY, [+ context.getHandler(),+ context.getClass(),+ ]);+ if (!chatScoped) {+ throw new ForbiddenException('API key is restricted to selected chats');}+ await this.assertChatsAllowed(request, apiKey);}// Routes marked @RequireUnscopedKey carry no session dimension, so the allowedSessions check@@ -162,6 +145,52 @@ export class ApiKeyGuard implements CanActivate {return true;}+ /** Route params the guard treats as a chat id. */+ private static readonly CHAT_ROUTE_PARAMS = ['chatId', 'groupId', 'contactId'] as const;+ /** Body fields that name a chat; bulk send nests the same name inside `messages[]`. */+ private static readonly CHAT_BODY_FIELDS = ['chatId', 'fromChatId', 'toChatId'] as const;++ /**+ * Enforce a restricted key's allowlist across every chat id the guard can see: route params,+ * `?chatId=`, and the body fields sends use. A field that is PRESENT but not a string is rejected+ * rather than skipped — the global ValidationPipe coerces afterwards (enableImplicitConversion),+ * so skipping here would let a handler receive a string the fence never checked.+ */+ private async assertChatsAllowed(request: Request, apiKey: ApiKey): Promise<void> {+ const scope = await this.chatScope.scopeFor(apiKey);+ for (const name of ApiKeyGuard.CHAT_ROUTE_PARAMS) {+ this.assertChatAllowed(scope, request.params[name], name);+ }+ this.assertChatAllowed(scope, (request.query ?? {})['chatId'], 'chatId');+ const body: unknown = request.body;+ if (body === null || typeof body !== 'object') return;+ const b = body as Record<string, unknown>;+ for (const field of ApiKeyGuard.CHAT_BODY_FIELDS) {+ this.assertChatAllowed(scope, b[field], field);+ }+ const messages = b.messages;+ if (messages === undefined || messages === null) return;+ if (!Array.isArray(messages)) {+ throw new BadRequestException('messages must be an array');+ }+ for (const item of messages) {+ if (item === null || typeof item !== 'object') continue;+ this.assertChatAllowed(scope, (item as { chatId?: unknown }).chatId, 'messages[].chatId');+ }+ }++ /** Reject an out-of-scope chat; ignore an absent field; refuse a present non-string field. */+ private assertChatAllowed(scope: ChatScope | null, value: unknown, field: string): void {+ if (value === undefined || value === null) return;+ if (typeof value !== 'string') {+ throw new BadRequestException(`${field} must be a single chat id string`);+ }+ if (value.length === 0) return;+ if (!chatScopeAllows(scope, value)) {+ throw new ForbiddenException('API key not authorized for this chat');+ }+ }+private extractApiKey(request: Request): string | undefined {// Support both X-API-Key header and Authorization Bearerconst xApiKey = request.headers['x-api-key'] as string;diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.tsindex 804398865..77f5a49c4 100644--- a/src/modules/catalog/catalog.controller.ts+++ b/src/modules/catalog/catalog.controller.ts@@ -2,7 +2,7 @@ import { Controller, Get, Post, Param, Body, Query } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { CatalogService } from './catalog.service';import { SendProductDto, ProductQueryDto } from './dto/send-product.dto';-import { RequireRole } from '../auth/decorators/auth.decorators';+import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import { CatalogDto, PaginatedProductsDto, ProductDto, ProductMessageResponseDto } from './dto/catalog-response.dto';import { ENGINE_NOT_READY_409, SESSION_NOT_STARTED_404 } from '../../common/openapi/engine-status-responses';@@ -69,6 +69,7 @@ export class CatalogController {return this.catalogService.getProduct(sessionId, productId);}+ @ChatScoped()@Post('messages/send-product')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a product message (Baileys engine only)' })diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex ff578f9a0..8e30608c6 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -1,7 +1,7 @@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 { RequireRole } from '../auth/decorators/auth.decorators';+import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import { UpsertContactDto } from './dto/upsert-contact.dto';import {@@ -82,6 +82,7 @@ export class ContactController {return this.contactService.getBlockedContacts(sessionId);}+ @ChatScoped()@Get(':contactId')@ApiOperation({ summary: 'Get a specific contact by ID' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -141,6 +142,7 @@ export class ContactController {// ========== Gap Quick Wins: Profile Picture, Block/Unblock ==========+ @ChatScoped()@Get(':contactId/profile-picture')@ApiOperation({ summary: 'Get profile picture URL for a contact' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -162,6 +164,7 @@ export class ContactController {return { url };}+ @ChatScoped()@Get(':contactId/phone')@ApiOperation({ summary: 'Resolve a contact id (e.g. an @lid) to a phone number — best-effort' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -177,6 +180,7 @@ export class ContactController {return { contactId, phone };}+ @ChatScoped()@Put(':contactId')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -203,6 +207,7 @@ export class ContactController {// Two path segments on the sibling route (`:contactId/block`) keep this single-segment DELETE// from shadowing the unblock route, whichever order they are declared in.+ @ChatScoped()@Delete(':contactId')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: "Remove a contact from the account's addressbook" })@@ -222,6 +227,7 @@ export class ContactController {return { success: true, message: 'Contact deleted' };}+ @ChatScoped()@Post(':contactId/block')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -245,6 +251,7 @@ export class ContactController {return { success: true, message: 'Contact blocked' };}+ @ChatScoped()@Delete(':contactId/block')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Unblock a contact' })diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex b2090cefb..e99f4bd8c 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -126,6 +126,14 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.data.rawApiKey).toBe('good');});+ it('refuses a chat-restricted key at the handshake (event filtering is a later slice)', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null, allowedChats: ['[email protected]'] });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ expect(sock.disconnect).toHaveBeenCalled();+ expect(sock.emit).toHaveBeenCalled();+ });+it('re-validates on subscribe and disconnects a key revoked after connect', async () => {authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null }); // connectconst sock = makeSocket({ apiKey: 'good' });diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 0e9f4f79b..d4b620a26 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -344,6 +344,19 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// for "Client IP could not be determined".const validKey = await this.authService.validateApiKey(apiKey, clientIp);+ // A chat-restricted key cannot yet be filtered on a live event stream (chat scoping of the+ // event surface is the follow-up slice), so refuse the handshake rather than stream every+ // chat's events to it. Mirrors the REST guard's default-deny for unmarked routes.+ if ((validKey.allowedChats?.length ?? 0) > 0) {+ this.logger.warn(`Client ${client.id} rejected: chat-scoped key ${validKey.id} cannot subscribe to events`);+ client.emit(+ 'message',+ this.createError('UNAUTHORIZED', 'API keys restricted to selected chats cannot subscribe to events'),+ );+ client.disconnect();+ return;+ }+// Cap simultaneous sockets per key: each socket holds rooms, engine fan-out, and memory,// so one key must not open connections without bound. Enough for multi-tab dashboards;// excess connections get a clear error, not a silent drop.diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex 3766a6c54..1f000ab2c 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -11,7 +11,7 @@ import {MembershipRequestActionDto,SetGroupPictureDto,} from './dto/group.dto';-import { RequireRole } from '../auth/decorators/auth.decorators';+import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import {GroupAckResponseDto,@@ -88,6 +88,7 @@ export class GroupController {return this.groupService.getGroupJoinInfo(sessionId, code);}+ @ChatScoped()@Get(':groupId')@ApiOperation({ summary: 'Get detailed group info' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -125,6 +126,7 @@ export class GroupController {return { success: true, groupId };}+ @ChatScoped()@Get(':groupId/settings')@ApiOperation({ summary: 'Get group settings (announce / locked / ephemeral timer)' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -140,6 +142,7 @@ export class GroupController {return this.groupService.getGroupSettings(sessionId, groupId);}+ @ChatScoped()@Put(':groupId/settings')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Update group settings (announce / locked / ephemeral timer)' })@@ -185,6 +188,7 @@ export class GroupController {return this.groupService.createGroup(sessionId, dto.name, dto.participants);}+ @ChatScoped()@Post(':groupId/participants')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Add participants to a group' })@@ -211,6 +215,7 @@ export class GroupController {return { success: true, message: 'Participants added', results };}+ @ChatScoped()@Delete(':groupId/participants')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Remove participants from a group' })@@ -236,6 +241,7 @@ export class GroupController {return { success: true, message: 'Participants removed', results };}+ @ChatScoped()@Post(':groupId/participants/promote')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Promote participants to admin' })@@ -262,6 +268,7 @@ export class GroupController {return { success: true, message: 'Participants promoted to admin', results };}+ @ChatScoped()@Post(':groupId/participants/demote')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Demote participants from admin' })@@ -288,6 +295,7 @@ export class GroupController {return { success: true, message: 'Participants demoted from admin', results };}+ @ChatScoped()@Get(':groupId/membership-requests')@ApiOperation({summary: 'List pending join requests for a group',@@ -306,6 +314,7 @@ export class GroupController {return this.groupService.getGroupMembershipRequests(sessionId, groupId);}+ @ChatScoped()@Post(':groupId/membership-requests/approve')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -338,6 +347,7 @@ export class GroupController {return { success: true, message: 'Membership requests approved', results };}+ @ChatScoped()@Post(':groupId/membership-requests/reject')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -370,6 +380,7 @@ export class GroupController {return { success: true, message: 'Membership requests rejected', results };}+ @ChatScoped()@Put(':groupId/subject')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Change group name/subject' })@@ -394,6 +405,7 @@ export class GroupController {return { success: true, message: 'Group subject updated' };}+ @ChatScoped()@Put(':groupId/description')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Change group description' })@@ -418,6 +430,7 @@ export class GroupController {return { success: true, message: 'Group description updated' };}+ @ChatScoped()@Post(':groupId/leave')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Leave a group' })@@ -439,6 +452,7 @@ export class GroupController {// ========== Gap Quick Wins: Invite Link ==========+ @ChatScoped()@Get(':groupId/picture')@ApiOperation({ summary: "Get the group's picture URL" })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -458,6 +472,7 @@ export class GroupController {return { url: await this.groupService.getGroupPicture(sessionId, groupId) };}+ @ChatScoped()@Put(':groupId/picture')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -488,6 +503,7 @@ export class GroupController {return { success: true, message: 'Group picture updated' };}+ @ChatScoped()@Delete(':groupId/picture')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -512,6 +528,7 @@ export class GroupController {// The invite code is a bearer join capability, not read data: it works outside OpenWA and keeps// working after the key that fetched it is revoked. OPERATOR, like the QR endpoint.+ @ChatScoped()@Get(':groupId/invite-code')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Get group invite code/link' })@@ -529,6 +546,7 @@ export class GroupController {};}+ @ChatScoped()@Post(':groupId/invite-code/revoke')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex b0782a083..586685d2f 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -5,7 +5,7 @@ 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 { RequireRole } from '../auth/decorators/auth.decorators';+import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import {ENGINE_NOT_READY_409,@@ -142,6 +142,7 @@ export class LabelController {return { success: true };}+ @ChatScoped()@Get('chat/:chatId')@ApiOperation({ summary: 'Get labels for a specific chat' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -159,6 +160,7 @@ export class LabelController {return this.labelService.getChatLabels(sessionId, chatId);}+ @ChatScoped()@Post('chat/:chatId')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -195,6 +197,7 @@ export class LabelController {return { success: true };}+ @ChatScoped()@Delete('chat/:chatId/:labelId')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Remove a label from a chat' })diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 75c2cc18c..3fc83582c 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -46,7 +46,7 @@ import {ClickButtonDto,UnpinMessageDto,} from './dto/message-actions.dto';-import { RequireRole } from '../auth/decorators/auth.decorators';+import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import {CHANNEL_MEDIA_501,@@ -131,6 +131,7 @@ export class MessageController {});}+ @ChatScoped()@Post('send-text')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a text message' })@@ -153,6 +154,7 @@ export class MessageController {return this.messageService.sendText(sessionId, dto);}+ @ChatScoped()@Post('send-template')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Render a stored text template and send it as a text message' })@@ -175,6 +177,7 @@ export class MessageController {return this.messageService.sendTemplate(sessionId, dto);}+ @ChatScoped()@Post('send-image')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send an image message' })@@ -201,6 +204,7 @@ export class MessageController {return this.messageService.sendImage(sessionId, dto);}+ @ChatScoped()@Post('send-video')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a video message' })@@ -249,6 +253,7 @@ export class MessageController {return this.messageService.sendAudio(sessionId, dto);}+ @ChatScoped()@Post('send-document')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a document/file' })@@ -275,6 +280,7 @@ export class MessageController {// ========== Phase 3: Extended Messaging ==========+ @ChatScoped()@Post('send-location')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a location message' })@@ -291,6 +297,7 @@ export class MessageController {return this.messageService.sendLocation(sessionId, dto);}+ @ChatScoped()@Post('send-contact')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a contact card message' })@@ -307,6 +314,7 @@ export class MessageController {return this.messageService.sendContact(sessionId, dto);}+ @ChatScoped()@Post('send-sticker')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a sticker message' })@@ -328,6 +336,7 @@ export class MessageController {return this.messageService.sendSticker(sessionId, dto);}+ @ChatScoped()@Post('send-poll')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a native WhatsApp poll' })@@ -344,6 +353,7 @@ export class MessageController {return this.messageService.sendPoll(sessionId, dto);}+ @ChatScoped()@Post('reply')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Reply to a message' })@@ -360,6 +370,7 @@ export class MessageController {return this.messageService.reply(sessionId, dto);}+ @ChatScoped()@Post('click-button')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({@@ -390,6 +401,7 @@ export class MessageController {return this.messageService.clickButton(sessionId, dto);}+ @ChatScoped()@Post('forward')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Forward a message to another chat' })@@ -408,6 +420,7 @@ export class MessageController {// ========== Phase 3: Reactions ==========+ @ChatScoped()@Post('react')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -435,6 +448,7 @@ export class MessageController {return { success: true };}+ @ChatScoped()@Get(':chatId/history')@ApiOperation({summary: 'Fetch chat history live from WhatsApp',@@ -495,6 +509,7 @@ export class MessageController {);}+ @ChatScoped()@Get(':chatId/:messageId/reactions')@ApiOperation({ summary: 'Get reactions for a specific message' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -524,6 +539,7 @@ export class MessageController {// Three path segments, so it never collides with `:chatId/history` (two) regardless of// declaration order — Nest/Express match on segment count first.+ @ChatScoped()@Get(':chatId/:messageId/media')@ApiOperation({ summary: 'Download a message’s stored media' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -563,6 +579,7 @@ export class MessageController {// ========== Delete Message ==========+ @ChatScoped()@Post('delete')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -593,6 +610,7 @@ export class MessageController {return { success: true };}+ @ChatScoped()@Post('vote-poll')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -615,6 +633,7 @@ export class MessageController {// ========== Pin / Unpin ==========+ @ChatScoped()@Post('pin')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -643,6 +662,7 @@ export class MessageController {return this.messageService.pinMessage(sessionId, dto);}+ @ChatScoped()@Post('unpin')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -671,6 +691,7 @@ export class MessageController {return this.messageService.unpinMessage(sessionId, dto);}+ @ChatScoped()@Post('star')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -698,6 +719,7 @@ export class MessageController {// ========== Edit Message ==========+ @ChatScoped()@Post('edit')@HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.OPERATOR)@@ -733,6 +755,7 @@ export class MessageController {// ========== Bulk Messaging ==========+ @ChatScoped()@Post('send-bulk')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.ACCEPTED)diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 690952173..956129f69 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -10,7 +10,7 @@ import { Message, MessageDirection } from './entities/message.entity';import { HookManager, applySendingGate } from '../../core/hooks';import { SendPacingService } from './send-pacing.service';import { createLogger } from '../../common/services/logger.service';-import { parseWaId } from '../../engine/identity/wa-id';+import { resolveJidCandidates as expandJidCandidates } from '../../engine/identity/jid-candidates';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';import { StorageService, isMissingObjectError } from '../../common/storage/storage.service';@@ -296,7 +296,7 @@ export class MessageService implements PluginMessagePort {// Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed// by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same// chat, different dialect. Resolving both sides through the table keeps them equal.- query.andWhere('message.chatId IN (:...chatIds)', { chatIds: this.resolveJidCandidates(chatId) });+ query.andWhere('message.chatId IN (:...chatIds)', { chatIds: await this.resolveJidCandidates(chatId) });}if (from) {@@ -309,7 +309,7 @@ export class MessageService implements PluginMessagePort {// within the (sessionId, createdAt)-narrowed scan exactly as the from-only filter did, so the// OR costs nothing the old plan didn't already pay. No new index: per-session narrowing// dominates selectivity and a single btree cannot serve an OR across two columns anyway.- const froms = this.resolveJidCandidates(from);+ const froms = await this.resolveJidCandidates(from);query.andWhere('(message.from IN (:...froms) OR message.author IN (:...authorFroms))', {froms,authorFroms: froms,@@ -364,26 +364,15 @@ export class MessageService implements PluginMessagePort {* 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): string[] {- const parsed = parseWaId(value);- if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {- return [value];- }- if (parsed.kind === 'lid') {- const candidates = new Set<string>([value]);- const resolved = this.lidMappingStore.getCached(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 this.lidMappingStore.lidsForPhone(phone)) {- candidates.add(`${lid}@lid`);- }- return [...candidates];+ private resolveJidCandidates(value: string): Promise<string[]> {+ // 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),+ });}/**@@ -429,7 +418,7 @@ export class MessageService implements PluginMessagePort {chatId: string,messageId: string,): Promise<{ buffer: Buffer; mimetype: string }> {- const chatIds = this.resolveJidCandidates(chatId);+ const chatIds = await this.resolveJidCandidates(chatId);const media = await this.chatMediaArchive?.getMedia(sessionId, chatIds, messageId);if (media && this.storageService) {try {diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 542be34fc..56add3aa6 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -5,6 +5,7 @@ import type { Session } from './entities/session.entity';import type { SessionService } from './session.service';import type { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';+import { ChatScopeService } from '../auth/chat-scope.service';import type { ApiKey } from '../auth/entities/api-key.entity';import { BadGatewayException, BadRequestException, ConflictException } from '@nestjs/common';@@ -44,6 +45,7 @@ describe('SessionController — create() response contract', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});@@ -128,6 +130,7 @@ describe('SessionController — logout() audit + error forwarding contract', ()controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});@@ -197,6 +200,7 @@ describe('SessionController — start/stop lifecycle', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});@@ -287,6 +291,7 @@ describe('SessionController — muteChat', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});@@ -314,6 +319,7 @@ describe('SessionController findAll name filter', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,{ logInfo: jest.fn() } as unknown as AuditService,+ new ChatScopeService(),);});@@ -355,6 +361,7 @@ describe('SessionController — pinChat', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});@@ -401,6 +408,7 @@ describe('SessionController — proxy() response contract', () => {controller = new SessionControllerClass(sessionService as unknown as SessionService,auditService as unknown as AuditService,+ new ChatScopeService(),);});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 7b8355191..6691273d3 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -44,7 +44,14 @@ import { Session } from './entities/session.entity';import { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';-import { RequireRole, CurrentApiKey, SessionScoped, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import {+ ChatScoped,+ CurrentApiKey,+ RequireRole,+ RequireUnscopedKey,+ SessionScoped,+} from '../auth/decorators/auth.decorators';+import { ChatScopeService } from '../auth/chat-scope.service';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';import {ENGINE_NOT_READY_409,@@ -61,6 +68,7 @@ export class SessionController {constructor(private readonly sessionService: SessionService,private readonly auditService: AuditService,+ private readonly chatScope: ChatScopeService,) {}private transformSession(session: Session): SessionResponseDto {@@ -485,6 +493,7 @@ export class SessionController {});}+ @ChatScoped()@Get(':sessionId/chats')@ApiOperation({ summary: 'Get active chats for a session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@@ -502,15 +511,20 @@ export class SessionController {@ApiQuery({ name: 'offset', required: false, description: 'Number of chats to skip (for paging)' })async getChats(@Param('sessionId', ParseUUIDPipe) id: string,+ @CurrentApiKey() apiKey?: ApiKey,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<ChatSummary[]> {- return this.sessionService.getChats(id, {+ const chats = await this.sessionService.getChats(id, {limit: limit ? parseInt(limit, 10) : undefined,offset: offset ? parseInt(offset, 10) : undefined,});+ // This route is admitted to a chat-restricted key because it FILTERS to the key's chats rather+ // than naming one in the path; the guard has nothing to check here (see the coverage spec).+ return this.chatScope.filter(apiKey, chats, chat => chat.id);}+ @ChatScoped()@Post(':sessionId/chats/read')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -542,6 +556,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Post(':sessionId/presence/subscribe')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -600,6 +615,7 @@ export class SessionController {return { success: true };}+ @ChatScoped()@Get(':sessionId/presence/:chatId')@RequireRole(ApiKeyRole.VIEWER)@ApiOperation({@@ -624,6 +640,7 @@ export class SessionController {return presence ? { ...presence, observedAt: new Date(presence.observedAt) } : null;}+ @ChatScoped()@Post(':sessionId/chats/unread')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -647,6 +664,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Delete(':sessionId/chats/:chatId/messages')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -677,6 +695,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Post(':sessionId/chats/archive')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -706,6 +725,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Post(':sessionId/chats/mute')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -742,6 +762,7 @@ export class SessionController {return { success: true };}+ @ChatScoped()@Post(':sessionId/chats/pin')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -776,6 +797,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Post(':sessionId/chats/delete')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)@@ -799,6 +821,7 @@ export class SessionController {return { success };}+ @ChatScoped()@Post(':sessionId/chats/typing')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)