Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(auth): explicit chat-scope categories, Bull Board refusal, per-request cost

Bhavya Chopra1f1de65117e8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f757e01f..a3dba63a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,8 +9,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 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`.
+- 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**: `ApiKeyGuard` answers `403` on every route not marked `@ChatScoped`, so webhooks, automation rules, status, key management, channels and every route added later stay closed without enumerating them, and such a key cannot manage API keys (a chat-scoped admin no longer counts toward the last-admin invariant). A marked route declares how it is safe — `'fenced'` (the `:chatId` / `:groupId` / `:contactId` path param, or a required `chatId` / `fromChatId` / `toChatId` / `messages[].chatId` body field), `'filtered'` (returns through `ChatScopeService.filter`), or `'agnostic'` (no chat reach, granted explicitly). An out-of-scope chat is `403`, a present-but-non-string chat field is `400`, and `quotedMessageId` is refused outright (a quote resolves from the global store, outside the allowlist). `send-bulk` verifies every recipient in `messages[].chatId`, while its batch status and cancel routes stay unmarked — a restricted key gets `403` from the returned `statusUrl`. Identity resolves through the `lid_mappings` table (read persistently, not 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. `/events`, the MCP mount (per tool call) and the Bull Board queue dashboard refuse such a key. Of the list routes, only `GET /sessions/:sessionId/chats` is usable — and it filters before paginating. A structural coverage spec checks every mark against its declared category ([#1634](https://github.com/rmyndharis/OpenWA/issues/1634)).
- 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/openapi.json b/openapi.json
index c26e1821a..f5305b924 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3800,6 +3800,9 @@
}
}
},
+ "403": {
+ "description": "The calling key is restricted with `allowedChats`. A batch row has no key owner, so the status cannot be checked against the key's allowlist and a chat-restricted key is refused; use the single-send routes instead."
+ },
"404": {
"description": "Batch not found"
}
@@ -3847,6 +3850,9 @@
"400": {
"description": "Batch already completed, cancelled, or failed (terminal statuses are exclusive)"
},
+ "403": {
+ "description": "The calling key is restricted with `allowedChats`. A batch row has no key owner, so the cancel cannot be checked against the key's allowlist and a chat-restricted key is refused."
+ },
"404": {
"description": "Batch not found"
}
diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.ts
index 29b7d8c9b..c25861caf 100644
--- a/src/common/security/bull-board-auth.middleware.spec.ts
+++ b/src/common/security/bull-board-auth.middleware.spec.ts
@@ -81,6 +81,27 @@ describe('BullBoardAuthMiddleware', () => {
expect((forwarded as ForbiddenException).message).toContain('restricted');
});
+ it('rejects an ADMIN key that is restricted to specific chats', async () => {
+ authService.validateApiKey.mockResolvedValue({
+ id: 'key-chat',
+ name: 'chat-scoped-admin',
+ role: ApiKeyRole.ADMIN,
+ allowedSessions: null,
+ allowedChats: ['[email protected]'],
+ });
+ authService.hasPermission.mockReturnValue(true);
+
+ const req = reqWith({ 'x-api-key': 'raw-key' });
+ const next = jest.fn();
+
+ await mw.use(req, res, next);
+
+ expect(next).toHaveBeenCalledTimes(1);
+ const forwarded = (next.mock.calls as Array<Array<unknown>>)[0]?.[0];
+ expect(forwarded).toBeInstanceOf(ForbiddenException);
+ expect((forwarded as ForbiddenException).message).toContain('restricted to selected chats');
+ });
+
it('admits an ADMIN key with an empty allowedSessions list', async () => {
authService.validateApiKey.mockResolvedValue({
id: 'key-2',
diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.ts
index 74faf5f5c..1164451ce 100644
--- a/src/common/security/bull-board-auth.middleware.ts
+++ b/src/common/security/bull-board-auth.middleware.ts
@@ -92,6 +92,14 @@ export class BullBoardAuthMiddleware implements NestMiddleware {
throw new ForbiddenException('API keys restricted to specific sessions cannot access the queue dashboard');
}
+ // A key restricted to selected chats is refused here too. This mount is the third surface
+ // outside ApiKeyGuard (beside /events and the MCP mount), and the board shows and mutates the
+ // webhook job queue, whose payloads carry every chat's events — so it has no chat dimension to
+ // scope against and must refuse such a key outright.
+ if ((apiKey.allowedChats?.length ?? 0) > 0) {
+ throw new ForbiddenException('API keys restricted to selected chats cannot access the queue dashboard');
+ }
+
// Boundary trace of queue-mutation attempts. GET/HEAD are the UI's read/poll traffic; every
// other method reaching the Bull Board router mutates queue state, so record it with the
// authenticated key, the resolved client IP, and the method + full path (no query string).
diff --git a/src/common/security/chat-scope.spec.ts b/src/common/security/chat-scope.spec.ts
index 5736af241..5fd3574f5 100644
--- a/src/common/security/chat-scope.spec.ts
+++ b/src/common/security/chat-scope.spec.ts
@@ -1,5 +1,7 @@
import {
buildChatScope,
+ buildExpandedChatScope,
+ chatIdAllowed,
chatScopeAllows,
filterByChatScope,
isChatScopeRestricted,
@@ -8,22 +10,28 @@ import {
const PHONE = '919999999999';
const LID = '555000111';
-const directory = {
- resolveLid: (lid: string) => (lid === LID ? PHONE : null),
- lidsForPhone: (phone: string) => (phone === PHONE ? [LID] : []),
+const single = {
+ resolveLid: (lid: string) => Promise.resolve(lid === LID ? PHONE : null),
+ lidsForPhone: (phone: string) => Promise.resolve(phone === PHONE ? [LID] : []),
+};
+const batch = {
+ phonesForLids: (lids: string[]) =>
+ Promise.resolve(Object.fromEntries(lids.map(lid => [lid, lid === LID ? PHONE : null]))),
+ lidsForPhones: (phones: string[]) =>
+ Promise.resolve(Object.fromEntries(phones.map(phone => [phone, phone === PHONE ? [LID] : []]))),
};
describe('chat-scope', () => {
- it('treats NULL/empty as unrestricted', async () => {
+ it('treats NULL/empty as unrestricted', () => {
expect(isChatScopeRestricted(null)).toBe(false);
expect(isChatScopeRestricted([])).toBe(false);
- expect(await buildChatScope(null)).toBeNull();
- expect(await buildChatScope([])).toBeNull();
+ expect(buildChatScope(null)).toBeNull();
+ expect(buildChatScope([])).toBeNull();
expect(chatScopeAllows(null, '[email protected]')).toBe(true);
});
- it('admits an allowlisted group and rejects any other', async () => {
- const scope = await buildChatScope(['[email protected]']);
+ it('admits an allowlisted group and rejects any other', () => {
+ const scope = buildChatScope(['[email protected]']);
expect(chatScopeAllows(scope, '[email protected]')).toBe(true);
expect(chatScopeAllows(scope, '[email protected]')).toBe(false);
// A group entry must not admit a contact, and vice versa.
@@ -31,44 +39,59 @@ describe('chat-scope', () => {
});
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);
+ const scope = buildChatScope([`${PHONE}@c.us`]);
+ expect(await chatIdAllowed(scope, `${PHONE}@c.us`, single)).toBe(true);
+ expect(await chatIdAllowed(scope, `${PHONE}@s.whatsapp.net`, single)).toBe(true);
+ expect(await chatIdAllowed(scope, `${LID}@lid`, single)).toBe(true);
+ expect(await chatIdAllowed(scope, '888000222@lid', single)).toBe(false);
+ });
+
+ it('does NOT let a phone entry admit the @lid with the same digits', async () => {
+ const scope = buildChatScope([`${PHONE}@c.us`]);
+ // A lid's digits are not a phone number: `<phone>@lid` is a different entity unless the table
+ // maps it, and this lid is not mapped to this phone.
+ expect(await chatIdAllowed(scope, `${PHONE}@lid`, single)).toBe(false);
});
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);
+ const scope = buildChatScope([`${LID}@lid`]);
+ expect(await chatIdAllowed(scope, `${LID}@lid`, single)).toBe(true);
+ expect(await chatIdAllowed(scope, `${LID}@c.us`, single)).toBe(false);
+ expect(await chatIdAllowed(scope, `${PHONE}@c.us`, single)).toBe(true);
});
it('leaves an unmapped @lid outside the fence', async () => {
- const scope = await buildChatScope([`${PHONE}@c.us`], directory);
- expect(chatScopeAllows(scope, '777000333@lid')).toBe(false);
+ const scope = buildChatScope([`${PHONE}@c.us`]);
+ expect(await chatIdAllowed(scope, '777000333@lid', single)).toBe(false);
});
it('accepts a bare phone number and matches its canonical chat', async () => {
- const scope = await buildChatScope([PHONE], directory);
+ const scope = buildChatScope([PHONE]);
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(await chatIdAllowed(scope, `${LID}@lid`, single)).toBe(true);
});
- it('never admits status, channels or broadcast lists', async () => {
- const scope = await buildChatScope(['[email protected]', `${PHONE}@c.us`]);
+ it('never admits status, channels or broadcast lists', () => {
+ const scope = buildChatScope(['[email protected]', `${PHONE}@c.us`]);
expect(chatScopeAllows(scope, 'status@broadcast')).toBe(false);
expect(chatScopeAllows(scope, '123@newsletter')).toBe(false);
expect(chatScopeAllows(scope, '123@broadcast')).toBe(false);
});
+ it('expands the allowlist once for a list filter (batched directory)', async () => {
+ const phoneScope = await buildExpandedChatScope([`${PHONE}@c.us`], batch);
+ expect(chatScopeAllows(phoneScope, `${LID}@lid`)).toBe(true);
+ const lidScope = await buildExpandedChatScope([`${LID}@lid`], batch);
+ expect(chatScopeAllows(lidScope, `${PHONE}@c.us`)).toBe(true);
+ // The literal scope is returned unchanged without a directory.
+ expect(await buildExpandedChatScope([`${LID}@lid`])).toEqual(buildChatScope([`${LID}@lid`]));
+ });
+
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(await buildChatScope(['[email protected]']), rows, r => r.id)).toEqual([{ id: '[email protected]' }]);
+ const scope = await buildExpandedChatScope(['[email protected]'], batch);
+ expect(filterByChatScope(scope, rows, r => r.id)).toEqual([{ id: '[email protected]' }]);
expect(filterByChatScope(null, rows, r => r.id)).toEqual(rows);
});
});
diff --git a/src/common/security/chat-scope.ts b/src/common/security/chat-scope.ts
index 740d91dc2..9b41cf629 100644
--- a/src/common/security/chat-scope.ts
+++ b/src/common/security/chat-scope.ts
@@ -5,24 +5,36 @@
* contacts — independent of `allowedSessions`. A key with no allowlist (NULL/empty) is unrestricted;
* with one, it may reach only the chats inside the fence.
*
- * 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
+ * Matching is expansion, not string comparison, and it is deliberately asymmetric so the cost lands
+ * on the small side:
*
- * 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.
+ * - the allowlist is compiled to its LITERAL address forms (both user dialects for a phone, the
+ * `@lid` form for a lid, the `@g.us` form for a group) — no lookups;
+ * - a SINGLE requested chat id is expanded once, through the lid table, into every JID that refers
+ * to the same entity, and tested against those literals. That is at most two lookups per request
+ * (the guard's path), not one per allowlist entry;
+ * - a LIST filter is the other way round: the allowlist is expanded once with the table (batched),
+ * and each row is then a pure literal membership test.
+ *
+ * Keeping phones and lids apart is what stops `555000111@lid` admitting `[email protected]`: a lid's
+ * digits are not a phone number, so the two only cross where the table maps them.
*/
import { parseWaId } from '../../engine/identity/wa-id';
import { ContactDirectory, resolveJidCandidates } from '../../engine/identity/jid-candidates';
-/** A compiled allowlist: the exact JIDs a key may reach (an entry expands to several). */
+/** A compiled allowlist: the exact JIDs a key may reach (an entry expands to its dialects). */
export interface ChatScope {
allowed: Set<string>;
}
+/** Batched lid<->phone lookups, used to expand the ALLOWLIST once for a list filter. */
+export interface ChatScopeDirectory {
+ /** lid user-part -> phone digits, for the lids that are mapped. */
+ phonesForLids(lids: string[]): Promise<Record<string, string | null>>;
+ /** phone digits -> the lid user-parts mapped to it. */
+ lidsForPhones(phones: string[]): Promise<Record<string, string[]>>;
+}
+
/** A bare phone number (MSISDN digits) — accepted as a convenience in place of `<phone>@c.us`. */
const BARE_NUMBER = /^\d{5,}$/;
@@ -43,22 +55,19 @@ export function normalizeChatAllowList(list: string[] | null | undefined): strin
return qualified.length > 0 ? qualified : null;
}
-/**
- * Compile an `allowedChats` allowlist into a {@link ChatScope}, or `null` for "unrestricted"
- * (NULL/empty). Each entry expands through `directory` — see {@link resolveJidCandidates}.
- */
-export async function buildChatScope(
- allowedChats: string[] | null | undefined,
- directory?: ContactDirectory,
-): Promise<ChatScope | null> {
- if (!isChatScopeRestricted(allowedChats)) return null;
- const allowed = new Set<string>();
- for (const raw of allowedChats as string[]) {
- const entry = raw.trim();
- if (!entry) continue;
- for (const jid of await resolveJidCandidates(entry, directory)) allowed.add(jid);
+/** The stored address forms of one allowlist entry. No directory: literal dialects only. */
+function literalForms(entry: string): string[] {
+ const parsed = parseWaId(entry);
+ 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 { allowed };
}
/**
@@ -80,14 +89,74 @@ function addressForms(chatId: string): string[] {
}
}
+/** Compile an `allowedChats` allowlist into a {@link ChatScope}, or `null` for "unrestricted". */
+export function buildChatScope(allowedChats: string[] | null | undefined): ChatScope | null {
+ if (!isChatScopeRestricted(allowedChats)) return null;
+ const allowed = new Set<string>();
+ for (const entry of normalizeChatAllowList(allowedChats) ?? []) {
+ for (const form of literalForms(entry)) allowed.add(form);
+ }
+ return { allowed };
+}
+
/**
- * Whether `chatId` falls inside `scope`. A `null` scope is unrestricted and admits everything.
+ * Whether `chatId` falls inside `scope` by LITERAL address form. A `null` scope is unrestricted and
+ * admits everything. Use {@link chatIdAllowed} when the lid table should be consulted.
*/
export function chatScopeAllows(scope: ChatScope | null, chatId: string): boolean {
if (scope === null) return true;
return addressForms(chatId).some(form => scope.allowed.has(form));
}
+/**
+ * Whether a single requested `chatId` is inside the allowlist, expanding the REQUESTED id (once)
+ * through the lid table rather than the allowlist. `directory` may be omitted, in which case only
+ * exact dialects match.
+ */
+export async function chatIdAllowed(
+ scope: ChatScope | null,
+ chatId: string,
+ directory?: ContactDirectory,
+): Promise<boolean> {
+ if (scope === null) return true;
+ const candidates = await resolveJidCandidates(chatId, directory);
+ return candidates.some(candidate => scope.allowed.has(candidate));
+}
+
+/**
+ * Expand the allowlist once with the lid table (batched: two queries at most) so a list filter can
+ * then be a pure membership test per row. Returns the literal scope when there is no directory.
+ */
+export async function buildExpandedChatScope(
+ allowedChats: string[] | null | undefined,
+ directory?: ChatScopeDirectory,
+): Promise<ChatScope | null> {
+ const scope = buildChatScope(allowedChats);
+ if (scope === null || !directory) return scope;
+ const phones = new Set<string>();
+ const lids = new Set<string>();
+ for (const entry of normalizeChatAllowList(allowedChats) ?? []) {
+ const parsed = parseWaId(entry);
+ if (parsed.kind === 'user') phones.add(parsed.userPart);
+ else if (parsed.kind === 'lid') lids.add(parsed.userPart);
+ }
+ const [lidToPhone, phoneToLids] = await Promise.all([
+ directory.phonesForLids([...lids]),
+ directory.lidsForPhones([...phones]),
+ ]);
+ const allowed = new Set(scope.allowed);
+ for (const phone of Object.values(lidToPhone)) {
+ if (phone) {
+ allowed.add(`${phone}@c.us`);
+ allowed.add(`${phone}@s.whatsapp.net`);
+ }
+ }
+ for (const mapped of Object.values(phoneToLids)) {
+ for (const lid of mapped) allowed.add(`${lid}@lid`);
+ }
+ return { allowed };
+}
+
/**
* Filter `items` down to the chats a scope admits, keyed by `chatIdOf`. A `null` scope returns the
* list unchanged. List endpoints use this instead of rejecting, because they have no single chat in
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 50d5450cc..b800c16eb 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -1,6 +1,6 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import { LidMapping } from './lid-mapping.entity';
import { userPart } from './wa-id';
import { createLogger } from '../../common/services/logger.service';
@@ -178,6 +178,48 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
return [...lids];
}
+ /**
+ * Batched forward lookup for a list filter: lid user-part -> phone digits. One query for the whole
+ * allowlist instead of one per entry, and the cache is merged in so a mapping the table holds but
+ * the mirror evicted is still answered.
+ */
+ async phonesForLidsPersisted(lids: string[]): Promise<Record<string, string | null>> {
+ const out: Record<string, string | null> = {};
+ if (lids.length === 0) return out;
+ for (const lid of lids) {
+ const cached = this.getCached(lid);
+ if (cached !== undefined) out[lid] = cached;
+ }
+ try {
+ const rows = await this.repo.find({ where: { lid: In(lids) } });
+ for (const row of rows) {
+ if (!(row.lid in out)) out[row.lid] = row.phone;
+ }
+ } catch {
+ // The table may not exist yet (migration pending); the cache is the best available answer.
+ }
+ return out;
+ }
+
+ /** Batched reverse lookup, companion to {@link phonesForLidsPersisted}: phone digits -> lids. */
+ async lidsForPhonesPersisted(phones: string[]): Promise<Record<string, string[]>> {
+ const out: Record<string, string[]> = {};
+ if (phones.length === 0) return out;
+ for (const phone of phones) out[phone] = this.lidsForPhone(phone);
+ try {
+ const rows = await this.repo.find({ where: { phone: In(phones) } });
+ for (const row of rows) {
+ if (!row.phone) continue;
+ const list = out[row.phone] ?? [];
+ if (!list.includes(row.lid)) list.push(row.lid);
+ out[row.phone] = list;
+ }
+ } catch {
+ // The table may not exist yet (migration pending); the cache is the best available answer.
+ }
+ return out;
+ }
+
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 updatedAt
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index 1f6bbba97..b76b364b3 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -441,6 +441,22 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
expect(await store.resolveLidPersisted('555@lid')).toBeNull();
});
+ it('lidsForPhonePersisted reads the table for a lid evicted from the LRU cache', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ try {
+ // Preload keeps one of the two lids; the reverse map then holds only that one, so the second
+ // can only come from the table.
+ const repo = makeFakeRepo([
+ { lid: '111', phone: '628999' },
+ { lid: '222', phone: '628999' },
+ ]);
+ const store = await newStore(repo);
+ expect((await store.lidsForPhonePersisted('628999')).sort()).toEqual(['111', '222']);
+ } finally {
+ delete process.env.LID_MAPPING_CACHE_MAX;
+ }
+ });
+
it('lidsForPhonePersisted unions the cache with the persisted table', async () => {
const repo = makeFakeRepo([
{ lid: '111', phone: '628999' },
@@ -450,6 +466,51 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
expect((await store.lidsForPhonePersisted('628999')).sort()).toEqual(['111', '222']);
});
+ it('phonesForLidsPersisted reads the table for a lid evicted from the LRU cache', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ try {
+ const repo = makeFakeRepo([
+ { lid: '111', phone: '628999' },
+ { lid: '222', phone: '628888' },
+ ]);
+ const store = await newStore(repo);
+ expect(await store.phonesForLidsPersisted(['111', '222'])).toEqual({ 111: '628999', 222: '628888' });
+ } finally {
+ delete process.env.LID_MAPPING_CACHE_MAX;
+ }
+ });
+
+ it('lidsForPhonesPersisted reads the table for a lid evicted from the LRU cache', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ try {
+ const repo = makeFakeRepo([
+ { lid: '111', phone: '628999' },
+ { lid: '222', phone: '628999' },
+ ]);
+ const store = await newStore(repo);
+ expect((await store.lidsForPhonesPersisted(['628999']))['628999'].sort()).toEqual(['111', '222']);
+ } finally {
+ delete process.env.LID_MAPPING_CACHE_MAX;
+ }
+ });
+
+ it('batched lookups handle an empty input, a null-phone row, and a read error', async () => {
+ const repo = makeFakeRepo([
+ { lid: '111', phone: '628999' },
+ { lid: '333', phone: null },
+ ]);
+ const store = await newStore(repo);
+ expect(await store.phonesForLidsPersisted([])).toEqual({});
+ expect(await store.lidsForPhonesPersisted([])).toEqual({});
+ // The null-phone row is skipped rather than indexed under a null key.
+ expect((await store.lidsForPhonesPersisted(['628999']))['628999']).toEqual(['111']);
+ // A read error falls back to the cache, which the preload filled.
+ repo.find.mockRejectedValueOnce(new Error('no such table'));
+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: '628999' });
+ repo.find.mockRejectedValueOnce(new Error('no such table'));
+ expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: ['111'] });
+ });
+
it('lidsForPhonePersisted falls back to the cache when the table read throws', async () => {
const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);
const store = await newStore(repo);
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 97c4f8b98..378782646 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -97,6 +97,8 @@ describe('AuthService', () => {
/** Statements whose write committed (affected = 1), newest last, with whether the last-admin
* guard clause was bound — for assertions on what actually landed, and how. */
let committedWrites: Array<{ mode: 'update' | 'delete'; patch?: Record<string, unknown>; guarded: boolean }>;
+ /** The raw AND-fragment the last-admin guard binds, so the SQL predicate itself is asserted. */
+ let lastAdminFragments: string[];
beforeEach(async () => {
repository = {
@@ -140,6 +142,7 @@ describe('AuthService', () => {
function setupKeys(seed: ApiKey[]): void {
keys = new Map(seed.map(k => [k.id, k]));
committedWrites = [];
+ lastAdminFragments = [];
(repository.findOne as jest.Mock).mockImplementation((options: { where: { id: string } }) =>
Promise.resolve(keys.get(options.where.id) ?? null),
);
@@ -176,8 +179,9 @@ describe('AuthService', () => {
this.targetId = params.id;
return this;
},
- andWhere() {
+ andWhere(fragment: string) {
this.guarded = true;
+ lastAdminFragments.push(fragment);
return this;
},
setParameters() {
@@ -611,6 +615,16 @@ describe('AuthService', () => {
await expect(service.findOne('admin-a')).resolves.toBeDefined();
});
+ it('the guard SQL excludes a chat-scoped key (the predicate the database actually runs)', async () => {
+ // The isUsableAdminRow mirror above cannot prove the SQL: the string is never executed by the
+ // mock. Assert the AND-fragment the guard binds names allowedChats, so dropping the clause
+ // fails here rather than in production.
+ setupKeys([unscopedAdmin('admin-a'), chatScopedAdmin('admin-chat')]);
+
+ await expect(service.update('admin-a', { role: ApiKeyRole.OPERATOR })).rejects.toThrow(/last active admin/i);
+ expect(lastAdminFragments.join(' ')).toContain('allowedChats');
+ });
+
it('rejects deleting the last unscoped admin even while a chat-scoped admin survives', async () => {
setupKeys([unscopedAdmin('admin-a'), chatScopedAdmin('admin-chat')]);
diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.ts
index f6178de13..0064410ce 100644
--- a/src/modules/auth/chat-scope-coverage.spec.ts
+++ b/src/modules/auth/chat-scope-coverage.spec.ts
@@ -3,23 +3,23 @@
//
// 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.
+// rules, status, key management, channels, Bull Board) and every route added later stay closed
+// without being enumerated.
//
-// Marking a handler is the operator's assertion that it is safe for such a key, and it is safe in
-// one of three ways:
+// Marking carries the reason, and this spec checks each one:
//
-// 1. fenced — it names a chat the guard inspects (a `:chatId` / `:groupId` / `:contactId` path
-// param, `?chatId=`, or the `chatId` / `fromChatId` / `toChatId` / `messages[].chatId` body
-// fields);
-// 2. filtered — it lists chats and filters them through ChatScopeService;
-// 3. chat-agnostic — it names no chat at all.
+// @ChatScoped('fenced') the handler names a chat the guard inspects — a `:chatId` / `:groupId` /
+// `:contactId` path param, or a REQUIRED guard-read body field
+// (`chatId` / `fromChatId` / `toChatId` / `messages[]`). An optional
+// `?chatId=` does NOT qualify: the guard would have nothing to check when
+// it is omitted.
+// @ChatScoped('filtered') the handler lists chats and returns through ChatScopeService.filter.
+// @ChatScoped('agnostic') the handler cannot reach a chat at all. This is the one category the
+// spec cannot derive (a webhook with `events: ['*']` also names no chat),
+// so every grant must also appear in AGNOSTIC_GRANTS.
//
-// This spec fails when a marked handler reaches chats by a field the guard does NOT read (a
-// `recipients[]`, `participants[]`, `channelId`, …) while naming no guard-visible chat — the class of
-// route the design calls out (status posts, group creation). A chat-agnostic handler is accepted: the
-// mark is the assertion, and the spec cannot derive it, since a webhook with `events: ['*']` also
-// names no chat.
+// Every @ChatScoped decorator must pair with a parsed handler (the non-vacuity check below), so a
+// decorator the parser cannot see fails rather than silently going unchecked.
import { readdirSync, readFileSync } from 'fs';
import { basename, join, sep } from 'path';
@@ -27,19 +27,25 @@ import { basename, join, sep } from 'path';
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'];
-/** Chat-targeting field names the guard does NOT read — reaching a chat through one is the hazard. */
-const UNFENCED_CHAT_FIELDS = ['recipients', 'participants', 'channelId', 'chatIds', 'groupIds', 'contactIds'];
-
-const GUARD_FIELD_RE = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})[!?]?\\s*:`);
-const UNFENCED_FIELD_RE = new RegExp(`\\b(?:${UNFENCED_CHAT_FIELDS.join('|')})[!?]?\\s*:`);
-const BULK_ARRAY_RE = /\bmessages[!?]?\s*:\s*[\w.]*\[\]/;
/**
- * Request DTO classes that carry a chat id, classified by whether the guard fences the field it
- * carries. `guard` wins over `other`: a DTO the guard can fence is safe to mark.
+ * The complete set of handlers granted `@ChatScoped('agnostic')`. Each entry is a deliberate access
+ * decision, so the spec fails if a grant is missing from here OR listed here without the mark.
+ * Key format: `<controller file basename> :: <handler name>`.
*/
-export function chatBearingDtoClasses(dir: string): Map<string, 'guard' | 'other'> {
- const out = new Map<string, 'guard' | 'other'>();
+export const AGNOSTIC_GRANTS: ReadonlyArray<readonly [string, string]> = [
+ // Reports the session's own state and account: no chat data, changes nothing, and an integration
+ // needs it to know whether its session is connected.
+ ['session.controller.ts', 'findOne'],
+];
+
+const REQUIRED_GUARD_FIELD = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})!\\s*:`);
+const REQUIRED_BULK_FIELD = /\bmessages!\s*:/;
+
+/** Request DTO classes carrying a REQUIRED guard-read chat field. */
+function requiredGuardChatDtos(dir: string): Set<string> {
+ const own = new Set<string>();
+ const parents = new Map<string, string>();
const walk = (current: string): void => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const full = join(current, entry.name);
@@ -48,51 +54,74 @@ export function chatBearingDtoClasses(dir: string): Map<string, 'guard' | 'other
continue;
}
if (!entry.name.endsWith('.ts') || entry.name.endsWith('.spec.ts')) continue;
- // 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 (GUARD_FIELD_RE.test(chunk) || BULK_ARRAY_RE.test(chunk)) out.set(name, 'guard');
- else if (UNFENCED_FIELD_RE.test(chunk)) out.set(name, 'other');
+ const parent = /^[A-Za-z0-9_]+\s+extends\s+([A-Za-z0-9_]+)/.exec(chunk)?.[1];
+ if (parent) parents.set(name, parent);
+ if (REQUIRED_GUARD_FIELD.test(chunk) || REQUIRED_BULK_FIELD.test(chunk)) own.add(name);
}
}
};
walk(dir);
+ // Resolve `extends` transitively: a DTO inheriting a fenced `chatId` counts (send-audio extends the
+ // media DTO). Anything unresolved or cyclic is simply not required.
+ const out = new Set<string>();
+ for (const name of [...own, ...parents.keys()]) {
+ let cursor: string | undefined = name;
+ const seen = new Set<string>();
+ while (cursor && !seen.has(cursor)) {
+ seen.add(cursor);
+ if (own.has(cursor)) {
+ out.add(name);
+ break;
+ }
+ cursor = parents.get(cursor);
+ }
+ }
return out;
}
-/**
- * Return @ChatScoped handlers in `source` that reach chats through a field the guard does not read
- * while naming no guard-visible chat — marked handlers a chat-restricted key could use to reach any
- * chat. A marked handler that names a guard-visible chat is fenced by the guard; one that names no
- * chat at all is chat-agnostic and accepted (the mark is the assertion).
- */
-export function markedHandlersReachingUnfencedChats(
- source: string,
- chatDtos: Map<string, 'guard' | 'other'>,
-): string[] {
- const offenders: string[] = [];
+/** Every @ChatScoped decorator in `source` paired with the handler it decorates. */
+export function chatScopedHandlers(source: string): Array<{ name: string; kind: string; body: string }> {
+ const out: Array<{ name: string; kind: string; body: string }> = [];
const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)\s*[:{]/gm;
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, decorators: m[1] ?? '' });
}
for (let i = 0; i < matches.length; i++) {
- const { name, from, decorators } = matches[i];
- if (!/@ChatScoped\(\)/.test(decorators)) continue;
- const body = source.slice(from, matches[i + 1]?.from ?? source.length);
+ const kind = /@ChatScoped\(\s*'([a-z]+)'\s*\)/.exec(matches[i].decorators)?.[1];
+ if (kind === undefined) continue;
+ out.push({
+ name: matches[i].name,
+ kind,
+ body: source.slice(matches[i].from, matches[i + 1]?.from ?? source.length),
+ });
+ }
+ return out;
+}
+
+/** Return a description of every marked handler that does not hold up its declared category. */
+export function chatScopeViolations(
+ source: string,
+ file: string,
+ requiredDtos: Set<string>,
+ agnosticGrants: ReadonlyArray<readonly [string, string]> = AGNOSTIC_GRANTS,
+): string[] {
+ const offenders: string[] = [];
+ for (const { name, kind, body } of chatScopedHandlers(source)) {
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];
- const hasGuardBodyChat = bodyDto !== undefined && chatDtos.get(bodyDto) === 'guard';
- // A chat-agnostic handler names no chat: accepted, the mark is the assertion.
- const namesGuardChat = hasPathChat || hasQueryChat || hasGuardBodyChat;
- const unfencedQuery = new RegExp(`@Query\\(\\s*['"](?:${UNFENCED_CHAT_FIELDS.join('|')})['"]\\s*\\)`).test(body);
- const unfencedBody = bodyDto !== undefined && chatDtos.get(bodyDto) === 'other';
- const filtersChatScope = /\bchatScope\b/.test(body);
- if (!namesGuardChat && (unfencedQuery || unfencedBody) && !filtersChatScope) offenders.push(name);
+ const hasRequiredBodyChat = bodyDto !== undefined && requiredDtos.has(bodyDto);
+ if (kind === 'fenced' && !(hasPathChat || hasRequiredBodyChat))
+ offenders.push(`${name} (fenced, no guard-read chat)`);
+ else if (kind === 'filtered' && !/chatScope\.filter\(/.test(body)) offenders.push(`${name} (filtered, no filter)`);
+ else if (kind === 'agnostic' && !agnosticGrants.some(([f, h]) => f === file && h === name))
+ offenders.push(`${name} (agnostic, not on AGNOSTIC_GRANTS)`);
+ else if (!['fenced', 'filtered', 'agnostic'].includes(kind)) offenders.push(`${name} (unknown kind '${kind}')`);
}
return offenders;
}
@@ -110,99 +139,125 @@ function listControllerFiles(dir: string): string[] {
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');
- // 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');
+ // A chat reference the guard cannot fence is refused outright.
+ expect(guard).toContain('quotedMessageId');
});
- it('flags a marked handler that reaches chats by a field the guard does not read', () => {
- const vulnerable = `
- @ChatScoped()
+ it("flags a 'fenced' handler that names no guard-read chat", () => {
+ const source = `
+ @ChatScoped('fenced')
@Post('status')
- async postStatus(@Body() dto: SendStatusDto): Promise<unknown> {
+ async postStatus(@Body() dto: StatusDto): Promise<unknown> {
return this.svc.post(dto);
}
`;
- expect(markedHandlersReachingUnfencedChats(vulnerable, new Map([['SendStatusDto', 'other']]))).toEqual([
- 'postStatus',
+ expect(chatScopeViolations(source, 'x.controller.ts', new Set())).toEqual([
+ 'postStatus (fenced, no guard-read chat)',
]);
});
- it('clears a marked chat-agnostic handler (it names no chat — the mark is the assertion)', () => {
- const agnostic = `
- @ChatScoped()
+ it("flags a 'fenced' handler whose only chat is an optional query param", () => {
+ const source = `
+ @ChatScoped('fenced')
+ @Get()
+ async list(@Query('chatId') chatId?: string): Promise<unknown> {
+ return this.svc.list(chatId);
+ }
+`;
+ expect(chatScopeViolations(source, 'x.controller.ts', new Set())).toEqual(['list (fenced, no guard-read chat)']);
+ });
+
+ it("flags a 'filtered' handler that does not filter and an unlisted 'agnostic'", () => {
+ const source = `
+ @ChatScoped('filtered')
+ @Get('chats')
+ async chats(): Promise<unknown> {
+ return this.svc.chats();
+ }
+
+ @ChatScoped('agnostic')
@Get('profile')
- async profile(@Param('sessionId') sessionId: string): Promise<unknown> {
- return this.svc.profile(sessionId);
+ async profile(): Promise<unknown> {
+ return this.svc.profile();
}
`;
- expect(markedHandlersReachingUnfencedChats(agnostic, new Map())).toEqual([]);
+ expect(chatScopeViolations(source, 'x.controller.ts', new Set())).toEqual([
+ 'chats (filtered, no filter)',
+ 'profile (agnostic, not on AGNOSTIC_GRANTS)',
+ ]);
});
- it('clears a marked handler fenced by a path chat, a query chat, a body chat, or a filter', () => {
- const fenced = `
- @ChatScoped()
+ it('clears a fenced path chat, a required body chat, a filter, and a listed agnostic grant', () => {
+ const source = `
+ @ChatScoped('fenced')
@Get(':chatId')
async getOne(@Param('chatId') chatId: string): Promise<unknown> {
return this.svc.get(chatId);
}
- @ChatScoped()
- @Get()
- async list(@Query('chatId') chatId?: string): Promise<unknown> {
- return this.svc.list(chatId);
- }
-
- @ChatScoped()
+ @ChatScoped('fenced')
@Post()
async send(@Body() dto: SendThingDto): Promise<unknown> {
return this.svc.send(dto);
}
- @ChatScoped()
+ @ChatScoped('filtered')
@Get('chats')
async chats(@CurrentApiKey() apiKey: ApiKey): Promise<unknown> {
return this.chatScope.filter(apiKey, await this.svc.chats(), c => c.id);
}
-`;
- expect(markedHandlersReachingUnfencedChats(fenced, new Map([['SendThingDto', 'guard']]))).toEqual([]);
- });
- it('clears a marked group route: the :groupId in the path fences the participants it carries', () => {
- const group = `
- @ChatScoped()
- @Post(':groupId/participants')
- async addParticipants(@Param('groupId') groupId: string, @Body() dto: AddParticipantsDto): Promise<unknown> {
- return this.svc.add(groupId, dto);
+ @ChatScoped('agnostic')
+ @Get('granted')
+ async granted(): Promise<unknown> {
+ return this.svc.granted();
}
`;
- expect(markedHandlersReachingUnfencedChats(group, new Map([['AddParticipantsDto', 'other']]))).toEqual([]);
+ expect(
+ chatScopeViolations(source, 'x.controller.ts', new Set(['SendThingDto']), [['x.controller.ts', 'granted']]),
+ ).toEqual([]);
});
- it('no marked controller handler reaches an unfenced chat, and the scan is not vacuous', () => {
+ it('pairs every decorator with a parsed handler, and the scan is not vacuous', () => {
const modulesDir = join(__dirname, '..');
- const chatDtos = chatBearingDtoClasses(modulesDir);
- expect(chatDtos.size).toBeGreaterThan(0); // the DTO scan must not silently collapse
+ const requiredDtos = requiredGuardChatDtos(modulesDir);
+ expect(requiredDtos.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[] = [];
+ const seenGrants = new Set<string>();
+ let marked = 0;
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 markedHandlersReachingUnfencedChats(source, chatDtos)) {
- offenders.push(`${posixPath.replace(/.*\/src\//, 'src/')} :: ${fileName} :: ${handler}`);
+ const posixPath = file
+ .split(sep)
+ .join('/')
+ .replace(/.*\/src\//, 'src/');
+ // Non-vacuity: every @ChatScoped decorator in the file must pair with a parsed handler, or the
+ // parser is blind to it and the category checks never run.
+ const decorators = [...source.matchAll(/@ChatScoped\(/g)].length;
+ const paired = chatScopedHandlers(source);
+ expect({ file: posixPath, decorators, paired: paired.length }).toEqual({
+ file: posixPath,
+ decorators: paired.length,
+ paired: paired.length,
+ });
+ marked += paired.length;
+ for (const { name, kind } of paired) if (kind === 'agnostic') seenGrants.add(`${fileName} :: ${name}`);
+ for (const violation of chatScopeViolations(source, fileName, requiredDtos)) {
+ offenders.push(`${posixPath} :: ${fileName} :: ${violation}`);
}
}
- // Non-vacuity: a scan that found no marked handlers would pass for the wrong reason.
expect(marked).toBeGreaterThan(30);
expect(offenders).toEqual([]);
+ // Every declared grant is used, and every used grant is declared.
+ expect([...seenGrants].sort()).toEqual(AGNOSTIC_GRANTS.map(([f, h]) => `${f} :: ${h}`).sort());
});
});
diff --git a/src/modules/auth/chat-scope.service.spec.ts b/src/modules/auth/chat-scope.service.spec.ts
index efce3f7fe..b09f3b3f7 100644
--- a/src/modules/auth/chat-scope.service.spec.ts
+++ b/src/modules/auth/chat-scope.service.spec.ts
@@ -9,6 +9,12 @@ 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] : [])),
+ phonesForLidsPersisted: jest.fn((lids: string[]) =>
+ Promise.resolve(Object.fromEntries(lids.map(lid => [lid, lid === LID ? PHONE : null]))),
+ ),
+ lidsForPhonesPersisted: jest.fn((phones: string[]) =>
+ Promise.resolve(Object.fromEntries(phones.map(phone => [phone, phone === PHONE ? [LID] : []]))),
+ ),
} as unknown as LidMappingStoreService;
}
@@ -17,13 +23,12 @@ describe('ChatScopeService', () => {
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(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);
+ const svc = new ChatScopeService(fakeStore());
expect(svc.isRestricted({ allowedChats: [`${PHONE}@c.us`] })).toBe(true);
expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, `${LID}@lid`)).toBe(true);
expect(await svc.allows({ allowedChats: [`${PHONE}@c.us`] }, '888000222@lid')).toBe(false);
@@ -36,10 +41,10 @@ describe('ChatScopeService', () => {
expect(await svc.allows({ allowedChats: [`${LID}@lid`] }, `${PHONE}@c.us`)).toBe(true);
});
- it('filters a list, passing an unrestricted key through', async () => {
+ it('filters a list through the batched expansion, passing an unrestricted key through', async () => {
const svc = new ChatScopeService(fakeStore());
- const rows = [{ id: '[email protected]' }, { id: '[email protected]' }];
- expect(await svc.filter({ allowedChats: ['[email protected]'] }, rows, r => r.id)).toEqual([{ id: '[email protected]' }]);
+ const rows = [{ id: '[email protected]' }, { id: `${LID}@lid` }, { id: '[email protected]' }];
+ expect(await svc.filter({ allowedChats: [`${PHONE}@c.us`] }, rows, r => r.id)).toEqual([{ id: `${LID}@lid` }]);
expect(await svc.filter({ allowedChats: null }, rows, r => r.id)).toEqual(rows);
});
diff --git a/src/modules/auth/chat-scope.service.ts b/src/modules/auth/chat-scope.service.ts
index 7a67861a1..8a25612c8 100644
--- a/src/modules/auth/chat-scope.service.ts
+++ b/src/modules/auth/chat-scope.service.ts
@@ -4,21 +4,22 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.
import { ContactDirectory } from '../../engine/identity/jid-candidates';
import {
ChatScope,
+ ChatScopeDirectory,
buildChatScope,
- chatScopeAllows,
+ buildExpandedChatScope,
+ chatIdAllowed,
filterByChatScope,
isChatScopeRestricted,
} from '../../common/security/chat-scope';
/**
* Compiles an API key's `allowedChats` into an enforceable {@link ChatScope} and answers membership,
- * wiring the shared lid<->phone directory so a phone entry matches its `@lid` form and vice versa.
+ * wiring the lid<->phone table so a phone entry matches its `@lid` form and vice versa.
*
- * Provided by the global AuthModule so both the ApiKeyGuard (route-param fence) and the feature
- * 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.
+ * Provided by the global AuthModule so both the ApiKeyGuard (single requested id) and the list
+ * endpoints (whole result set) share one definition of "inside the fence". The table is read
+ * persistently rather than from the evictable in-memory mirror, so the answer is deterministic. A
+ * missing store degrades to exact-dialect matching only, which fails CLOSED for an unmapped `@lid`.
*/
@Injectable()
export class ChatScopeService {
@@ -34,14 +35,22 @@ export class ChatScopeService {
return isChatScopeRestricted(apiKey?.allowedChats);
}
- /** The compiled scope for a key, or `null` when unrestricted. */
- scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): Promise<ChatScope | null> {
- return buildChatScope(apiKey?.allowedChats ?? null, this.directory());
+ /** The literal scope for a key (no lookups), or `null` when unrestricted. */
+ scopeFor(apiKey?: Pick<ApiKey, 'allowedChats'> | null): ChatScope | null {
+ return buildChatScope(apiKey?.allowedChats ?? null);
}
- /** Whether `chatId` is inside the key's fence (an unrestricted key admits every chat). */
- async allows(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string): Promise<boolean> {
- return chatScopeAllows(await this.scopeFor(apiKey), chatId);
+ /**
+ * Whether a single requested `chatId` is inside the key's fence. Expands the REQUESTED id once
+ * through the lid table (at most two lookups) instead of expanding the whole allowlist.
+ */
+ allows(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined, chatId: string): Promise<boolean> {
+ return chatIdAllowed(this.scopeFor(apiKey), chatId, this.singleDirectory());
+ }
+
+ /** The allowlist expanded once with the lid table (batched), for filtering a whole list. */
+ scopeForFilter(apiKey: Pick<ApiKey, 'allowedChats'> | null | undefined): Promise<ChatScope | null> {
+ return buildExpandedChatScope(apiKey?.allowedChats ?? null, this.batchDirectory());
}
/** The subset of `items` whose chat id is inside the key's fence (unrestricted ⇒ unchanged). */
@@ -50,10 +59,10 @@ export class ChatScopeService {
items: readonly T[],
chatIdOf: (item: T) => string | null | undefined,
): Promise<T[]> {
- return filterByChatScope(await this.scopeFor(apiKey), items, chatIdOf);
+ return filterByChatScope(await this.scopeForFilter(apiKey), items, chatIdOf);
}
- private directory(): ContactDirectory | undefined {
+ private singleDirectory(): ContactDirectory | undefined {
const store = this.lidStore;
if (!store) return undefined;
return {
@@ -61,4 +70,13 @@ export class ChatScopeService {
lidsForPhone: phone => store.lidsForPhonePersisted(phone),
};
}
+
+ private batchDirectory(): ChatScopeDirectory | undefined {
+ const store = this.lidStore;
+ if (!store) return undefined;
+ return {
+ phonesForLids: lids => store.phonesForLidsPersisted(lids),
+ lidsForPhones: phones => store.lidsForPhonesPersisted(phones),
+ };
+ }
}
diff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.ts
index c2e97c93b..5d955776b 100644
--- a/src/modules/auth/decorators/auth.decorators.ts
+++ b/src/modules/auth/decorators/auth.decorators.ts
@@ -39,26 +39,29 @@ export const Public = () => SetMetadata(PUBLIC_KEY, true);
*/
export const RequireUnscopedKey = () => SetMetadata(UNSCOPED_KEY, true);
+/** How a handler is safe for a chat-restricted key. See {@link ChatScoped}. */
+export type ChatScopeKind = 'fenced' | 'filtered' | 'agnostic';
+
/**
- * Mark a handler (or controller) a chat-restricted key — one carrying `allowedChats` — may reach.
- *
- * 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 handler is safe to mark in one of three ways:
+ * Mark a handler (or controller) a chat-restricted key — one carrying `allowedChats` — may reach,
+ * and say WHICH way it is safe. 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, Bull Board) — and every route added later —
+ * stay closed without having to enumerate them.
*
- * - **fenced by path, body or query** — it names a chat the ApiKeyGuard inspects (`:chatId` /
- * `:groupId` / `:contactId`, `?chatId=`, or the `chatId` / `fromChatId` / `toChatId` /
- * `messages[].chatId` body fields);
- * - **filtered** — it lists chats instead of naming one, and filters the result through
- * ChatScopeService;
- * - **chat-agnostic** — it names no chat at all, so the mark itself is the assertion that it cannot
- * reach one. This is the one category the structural coverage spec cannot derive (a webhook with
- * `events: ['*']` also names no chat), so the mark is a deliberate operator decision.
+ * - `'fenced'` — names a chat the ApiKeyGuard inspects: a `:chatId` / `:groupId` / `:contactId`
+ * path param, or a REQUIRED guard-read body field (`chatId` / `fromChatId` / `toChatId` /
+ * `messages[]`). An optional `?chatId=` does not qualify — the guard would have nothing to check
+ * when it is omitted.
+ * - `'filtered'` — lists chats instead of naming one, and filters the result through
+ * ChatScopeService.
+ * - `'agnostic'` — names no chat and cannot reach one, so the mark itself is the assertion. This is
+ * the one category the structural coverage spec cannot derive (a webhook with `events: ['*']` also
+ * names no chat), so every `'agnostic'` grant must also be listed in the spec's AGNOSTIC_GRANTS.
*
- * @example @ChatScoped() @Get(':chatId')
+ * @example @ChatScoped('fenced') @Get(':chatId')
*/
-export const ChatScoped = () => SetMetadata(CHAT_SCOPED_KEY, true);
+export const ChatScoped = (kind: ChatScopeKind) => SetMetadata(CHAT_SCOPED_KEY, kind);
/**
* Get the current API key from request
diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.ts
index 213f29cc4..20d16c2cd 100644
--- a/src/modules/auth/guards/api-key.guard.spec.ts
+++ b/src/modules/auth/guards/api-key.guard.spec.ts
@@ -423,7 +423,7 @@ describe('ApiKeyGuard', () => {
// 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;
+ metadata[CHAT_SCOPED_KEY] = 'fenced';
});
const ALLOWED_GROUP = '[email protected]';
@@ -550,6 +550,47 @@ describe('ApiKeyGuard', () => {
expect(await guard.canActivate(context)).toBe(true);
});
+ it('fences a :groupId path param', async () => {
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const denied = createMockContext({ 'x-api-key': 'key' }, { groupId: 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' }, { groupId: ALLOWED_GROUP });
+ expect(await guard.canActivate(allowed)).toBe(true);
+ });
+
+ it('fences a :contactId path param', async () => {
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_CONTACT] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const denied = createMockContext({ 'x-api-key': 'key' }, { contactId: FORBIDDEN_CONTACT });
+ await expect(guard.canActivate(denied)).rejects.toThrow(
+ new ForbiddenException('API key not authorized for this chat'),
+ );
+
+ const allowed = createMockContext({ 'x-api-key': 'key' }, { contactId: ALLOWED_CONTACT });
+ expect(await guard.canActivate(allowed)).toBe(true);
+ });
+
+ it('refuses a quotedMessageId — a chat reference the guard cannot fence', async () => {
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ // The chat is allowed, but the quote resolves from the global store and could be a message
+ // from a chat outside the allowlist.
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ chatId: ALLOWED_GROUP,
+ quotedMessageId: 'm-from-elsewhere',
+ });
+ await expect(guard.canActivate(context)).rejects.toThrow(
+ new ForbiddenException('API key is restricted to selected chats'),
+ );
+ });
+
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] });
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index 399f7f487..067f62b14 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -18,8 +18,8 @@ import {
SESSION_SCOPED_KEY,
UNSCOPED_KEY,
CHAT_SCOPED_KEY,
+ ChatScopeKind,
} 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';
@@ -114,7 +114,7 @@ export class ApiKeyGuard implements CanActivate {
// 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, [
+ const chatScoped = this.reflector.getAllAndOverride<ChatScopeKind>(CHAT_SCOPED_KEY, [
context.getHandler(),
context.getClass(),
]);
@@ -151,43 +151,54 @@ export class ApiKeyGuard implements CanActivate {
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.
+ * Every chat id the guard can see in the request: route params, `?chatId=`, the body fields sends
+ * use, and each `messages[].chatId`. 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');
+ private chatIdsIn(request: Request): Array<[string, unknown]> {
+ const out: Array<[string, unknown]> = [];
+ for (const name of ApiKeyGuard.CHAT_ROUTE_PARAMS) out.push([name, request.params[name]]);
+ out.push(['chatId', (request.query ?? {})['chatId']]);
const body: unknown = request.body;
- if (body === null || typeof body !== 'object') return;
+ if (body === null || typeof body !== 'object') return out;
const b = body as Record<string, unknown>;
- for (const field of ApiKeyGuard.CHAT_BODY_FIELDS) {
- this.assertChatAllowed(scope, b[field], field);
- }
+ for (const field of ApiKeyGuard.CHAT_BODY_FIELDS) out.push([field, b[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');
- }
+ if (messages === undefined || messages === null) return out;
+ if (!Array.isArray(messages)) throw new BadRequestException('messages must be an array');
+ messages.forEach((item, i) => {
+ if (item === null || typeof item !== 'object') return;
+ out.push([`messages[${i}].chatId`, (item as { chatId?: unknown }).chatId]);
+ });
+ return out;
}
- /** 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`);
+ /**
+ * Enforce a restricted key's allowlist. Only the chat ids actually present are expanded (at most
+ * two lid-table lookups each), so a route that names no chat costs nothing.
+ */
+ private async assertChatsAllowed(request: Request, apiKey: ApiKey): Promise<void> {
+ for (const [field, value] of this.chatIdsIn(request)) {
+ if (value === undefined || value === null) continue;
+ if (typeof value !== 'string') {
+ throw new BadRequestException(`${field} must be a single chat id string`);
+ }
+ if (value.length === 0) continue;
+ if (!(await this.chatScope.allows(apiKey, value))) {
+ throw new ForbiddenException('API key not authorized for this chat');
+ }
}
- if (value.length === 0) return;
- if (!chatScopeAllows(scope, value)) {
- throw new ForbiddenException('API key not authorized for this chat');
+
+ // `quotedMessageId` is a chat reference the guard does not otherwise read: the quote resolves
+ // from the global message store, so a restricted key could quote a message from a chat outside
+ // its allowlist into an allowed one. Refuse it outright rather than resolve the quote's chat.
+ const body: unknown = request.body;
+ if (body !== null && typeof body === 'object') {
+ const quoted = (body as { quotedMessageId?: unknown }).quotedMessageId;
+ if (quoted !== undefined && quoted !== null && quoted !== '') {
+ throw new ForbiddenException('API key is restricted to selected chats');
+ }
}
}
diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.ts
index 77f5a49c4..be9aa98d4 100644
--- a/src/modules/catalog/catalog.controller.ts
+++ b/src/modules/catalog/catalog.controller.ts
@@ -69,7 +69,7 @@ export class CatalogController {
return this.catalogService.getProduct(sessionId, productId);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@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.ts
index 8e30608c6..130d9e521 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -82,7 +82,7 @@ export class ContactController {
return this.contactService.getBlockedContacts(sessionId);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':contactId')
@ApiOperation({ summary: 'Get a specific contact by ID' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -142,7 +142,7 @@ export class ContactController {
// ========== Gap Quick Wins: Profile Picture, Block/Unblock ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':contactId/profile-picture')
@ApiOperation({ summary: 'Get profile picture URL for a contact' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -164,7 +164,7 @@ export class ContactController {
return { url };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@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' })
@@ -180,7 +180,7 @@ export class ContactController {
return { contactId, phone };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Put(':contactId')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -207,7 +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()
+ @ChatScoped('fenced')
@Delete(':contactId')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: "Remove a contact from the account's addressbook" })
@@ -227,7 +227,7 @@ export class ContactController {
return { success: true, message: 'Contact deleted' };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':contactId/block')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -251,7 +251,7 @@ export class ContactController {
return { success: true, message: 'Contact blocked' };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Delete(':contactId/block')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Unblock a contact' })
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index 1f000ab2c..d3b097e79 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -88,7 +88,6 @@ export class GroupController {
return this.groupService.getGroupJoinInfo(sessionId, code);
}
- @ChatScoped()
@Get(':groupId')
@ApiOperation({ summary: 'Get detailed group info' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -126,7 +125,6 @@ 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' })
@@ -142,7 +140,6 @@ 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)' })
@@ -188,7 +185,6 @@ 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' })
@@ -215,7 +211,7 @@ export class GroupController {
return { success: true, message: 'Participants added', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Delete(':groupId/participants')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Remove participants from a group' })
@@ -241,7 +237,7 @@ export class GroupController {
return { success: true, message: 'Participants removed', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':groupId/participants/promote')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Promote participants to admin' })
@@ -268,7 +264,7 @@ export class GroupController {
return { success: true, message: 'Participants promoted to admin', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':groupId/participants/demote')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Demote participants from admin' })
@@ -295,7 +291,7 @@ export class GroupController {
return { success: true, message: 'Participants demoted from admin', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':groupId/membership-requests')
@ApiOperation({
summary: 'List pending join requests for a group',
@@ -314,7 +310,7 @@ export class GroupController {
return this.groupService.getGroupMembershipRequests(sessionId, groupId);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':groupId/membership-requests/approve')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -347,7 +343,7 @@ export class GroupController {
return { success: true, message: 'Membership requests approved', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':groupId/membership-requests/reject')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -380,7 +376,7 @@ export class GroupController {
return { success: true, message: 'Membership requests rejected', results };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Put(':groupId/subject')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Change group name/subject' })
@@ -405,7 +401,7 @@ export class GroupController {
return { success: true, message: 'Group subject updated' };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Put(':groupId/description')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Change group description' })
@@ -430,7 +426,7 @@ export class GroupController {
return { success: true, message: 'Group description updated' };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':groupId/leave')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Leave a group' })
@@ -452,7 +448,7 @@ export class GroupController {
// ========== Gap Quick Wins: Invite Link ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':groupId/picture')
@ApiOperation({ summary: "Get the group's picture URL" })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -472,7 +468,7 @@ export class GroupController {
return { url: await this.groupService.getGroupPicture(sessionId, groupId) };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Put(':groupId/picture')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -503,7 +499,7 @@ export class GroupController {
return { success: true, message: 'Group picture updated' };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Delete(':groupId/picture')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -528,7 +524,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()
+ @ChatScoped('fenced')
@Get(':groupId/invite-code')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Get group invite code/link' })
@@ -546,7 +542,7 @@ export class GroupController {
};
}
- @ChatScoped()
+ @ChatScoped('fenced')
@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.ts
index 586685d2f..77404a3c4 100644
--- a/src/modules/label/label.controller.ts
+++ b/src/modules/label/label.controller.ts
@@ -142,7 +142,7 @@ export class LabelController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get('chat/:chatId')
@ApiOperation({ summary: 'Get labels for a specific chat' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -160,7 +160,7 @@ export class LabelController {
return this.labelService.getChatLabels(sessionId, chatId);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('chat/:chatId')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -197,7 +197,7 @@ export class LabelController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@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.ts
index 3fc83582c..0b0b5ea4b 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -131,7 +131,7 @@ export class MessageController {
});
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-text')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a text message' })
@@ -154,7 +154,7 @@ export class MessageController {
return this.messageService.sendText(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-template')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Render a stored text template and send it as a text message' })
@@ -177,7 +177,7 @@ export class MessageController {
return this.messageService.sendTemplate(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-image')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send an image message' })
@@ -204,7 +204,7 @@ export class MessageController {
return this.messageService.sendImage(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-video')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a video message' })
@@ -229,6 +229,7 @@ export class MessageController {
return this.messageService.sendVideo(sessionId, dto);
}
+ @ChatScoped('fenced')
@Post('send-audio')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send an audio/voice message' })
@@ -253,7 +254,7 @@ export class MessageController {
return this.messageService.sendAudio(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-document')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a document/file' })
@@ -280,7 +281,7 @@ export class MessageController {
// ========== Phase 3: Extended Messaging ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-location')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a location message' })
@@ -297,7 +298,7 @@ export class MessageController {
return this.messageService.sendLocation(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-contact')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a contact card message' })
@@ -314,7 +315,7 @@ export class MessageController {
return this.messageService.sendContact(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-sticker')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a sticker message' })
@@ -336,7 +337,7 @@ export class MessageController {
return this.messageService.sendSticker(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-poll')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a native WhatsApp poll' })
@@ -353,7 +354,7 @@ export class MessageController {
return this.messageService.sendPoll(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('reply')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Reply to a message' })
@@ -370,7 +371,7 @@ export class MessageController {
return this.messageService.reply(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('click-button')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({
@@ -401,7 +402,7 @@ export class MessageController {
return this.messageService.clickButton(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('forward')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Forward a message to another chat' })
@@ -420,7 +421,7 @@ export class MessageController {
// ========== Phase 3: Reactions ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('react')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -448,7 +449,7 @@ export class MessageController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':chatId/history')
@ApiOperation({
summary: 'Fetch chat history live from WhatsApp',
@@ -509,7 +510,7 @@ export class MessageController {
);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':chatId/:messageId/reactions')
@ApiOperation({ summary: 'Get reactions for a specific message' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -539,7 +540,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()
+ @ChatScoped('fenced')
@Get(':chatId/:messageId/media')
@ApiOperation({ summary: 'Download a message’s stored media' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -579,7 +580,7 @@ export class MessageController {
// ========== Delete Message ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('delete')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -610,7 +611,7 @@ export class MessageController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('vote-poll')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -633,7 +634,7 @@ export class MessageController {
// ========== Pin / Unpin ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('pin')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -662,7 +663,7 @@ export class MessageController {
return this.messageService.pinMessage(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('unpin')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -691,7 +692,7 @@ export class MessageController {
return this.messageService.unpinMessage(sessionId, dto);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('star')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -719,7 +720,7 @@ export class MessageController {
// ========== Edit Message ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('edit')
@HttpCode(HttpStatus.OK)
@RequireRole(ApiKeyRole.OPERATOR)
@@ -755,7 +756,7 @@ export class MessageController {
// ========== Bulk Messaging ==========
- @ChatScoped()
+ @ChatScoped('fenced')
@Post('send-bulk')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.ACCEPTED)
@@ -803,6 +804,13 @@ export class MessageController {
status: 404,
description: 'Batch not found',
})
+ @ApiResponse({
+ status: 403,
+ description:
+ 'The calling key is restricted with `allowedChats`. A batch row has no key owner, so the ' +
+ "status cannot be checked against the key's allowlist and a chat-restricted key is refused; " +
+ 'use the single-send routes instead.',
+ })
async getBatchStatus(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {
const batch = await this.bulkMessageService.getBatchStatus(sessionId, batchId);
return {
@@ -826,6 +834,12 @@ export class MessageController {
description: 'Batch cancelled',
type: BatchCancelResponseDto,
})
+ @ApiResponse({
+ status: 403,
+ description:
+ 'The calling key is restricted with `allowedChats`. A batch row has no key owner, so the ' +
+ "cancel cannot be checked against the key's allowlist and a chat-restricted key is refused.",
+ })
@ApiResponse({
status: 400,
description: 'Batch already completed, cancelled, or failed (terminal statuses are exclusive)',
diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.ts
index 56add3aa6..856d6c42c 100644
--- a/src/modules/session/session.controller.spec.ts
+++ b/src/modules/session/session.controller.spec.ts
@@ -6,6 +6,7 @@ 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 { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';
import type { ApiKey } from '../auth/entities/api-key.entity';
import { BadGatewayException, BadRequestException, ConflictException } from '@nestjs/common';
@@ -437,3 +438,48 @@ describe('SessionController — proxy() response contract', () => {
);
});
});
+
+// GET /sessions/:sessionId/chats is the one list route a chat-restricted key may use, and it must
+// FILTER BEFORE paginating: filtering the page instead hands back a short or empty window while an
+// allowed chat sits just past it.
+describe('SessionController — GET .../chats filters before paginating', () => {
+ const chat = (id: string, timestamp: number): ChatSummary => ({
+ id,
+ name: id,
+ isGroup: id.endsWith('@g.us'),
+ kind: id.endsWith('@g.us') ? 'group' : 'individual',
+ unreadCount: 0,
+ timestamp,
+ archived: false,
+ pinned: false,
+ muted: false,
+ });
+
+ let sessionService: { listChats: jest.Mock };
+ let controller: SessionController;
+
+ beforeEach(() => {
+ sessionService = { listChats: jest.fn() };
+ controller = new SessionControllerClass(
+ sessionService as unknown as SessionService,
+ { logInfo: jest.fn() } as unknown as AuditService,
+ new ChatScopeService(),
+ );
+ });
+
+ it('filters the full list before the window (a page-first filter would return nothing here)', async () => {
+ // The disallowed chat is NEWEST, so a page of 1 taken before filtering would be all-disallowed.
+ sessionService.listChats.mockResolvedValue([chat('[email protected]', 3), chat('[email protected]', 2), chat('[email protected]', 1)]);
+ const apiKey = { allowedChats: ['[email protected]'] } as ApiKey;
+
+ const out = await controller.getChats('sess-uuid-1', apiKey, '1', '0');
+
+ expect(out.map(c => c.id)).toEqual(['[email protected]']);
+ });
+
+ it('passes the whole list through for an unrestricted key', async () => {
+ sessionService.listChats.mockResolvedValue([chat('[email protected]', 3), chat('[email protected]', 2)]);
+ const out = await controller.getChats('sess-uuid-1', { allowedChats: null } as ApiKey, undefined, undefined);
+ expect(out).toHaveLength(2);
+ });
+});
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 6691273d3..5eef5aad1 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -42,6 +42,7 @@ import {
} from './dto';
import { Session } from './entities/session.entity';
import { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';
+import { paginate } from '../../common/utils/paginate';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import {
@@ -137,6 +138,7 @@ export class SessionController {
return sessions.map(s => this.transformSession(s));
}
+ @ChatScoped('agnostic')
@Get(':sessionId')
@ApiOperation({ summary: 'Get session by ID' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -493,7 +495,7 @@ export class SessionController {
});
}
- @ChatScoped()
+ @ChatScoped('filtered')
@Get(':sessionId/chats')
@ApiOperation({ summary: 'Get active chats for a session' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@@ -515,16 +517,14 @@ export class SessionController {
@Query('limit') limit?: string,
@Query('offset') offset?: string,
): Promise<ChatSummary[]> {
- 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);
+ // than naming one in the path. Filter BEFORE paginating: filtering the page instead would give a
+ // restricted key a short or empty window while an allowed chat sat just past it.
+ const visible = await this.chatScope.filter(apiKey, await this.sessionService.listChats(id), chat => chat.id);
+ return paginate(visible, limit ? parseInt(limit, 10) : undefined, offset ? parseInt(offset, 10) : undefined);
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/read')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -556,7 +556,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/presence/subscribe')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -615,7 +615,7 @@ export class SessionController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Get(':sessionId/presence/:chatId')
@RequireRole(ApiKeyRole.VIEWER)
@ApiOperation({
@@ -640,7 +640,7 @@ export class SessionController {
return presence ? { ...presence, observedAt: new Date(presence.observedAt) } : null;
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/unread')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -664,7 +664,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Delete(':sessionId/chats/:chatId/messages')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -695,7 +695,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/archive')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -725,7 +725,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/mute')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -762,7 +762,7 @@ export class SessionController {
return { success: true };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/pin')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -797,7 +797,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/delete')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
@@ -821,7 +821,7 @@ export class SessionController {
return { success };
}
- @ChatScoped()
+ @ChatScoped('fenced')
@Post(':sessionId/chats/typing')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 7138189a1..fc4144373 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -731,14 +731,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return paginate(mapped, opts.limit, opts.offset);
}
- async getChats(id: string, opts: ListOptions = {}): Promise<ChatSummary[]> {
+ /**
+ * Every chat for a session, most-recent first, WITHOUT the response window. Callers that must
+ * filter before paging (a chat-restricted API key) use this, then paginate themselves: filtering
+ * after paginate() would hand back short or empty pages for an allowed chat past the window.
+ */
+ async listChats(id: string): Promise<ChatSummary[]> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- // Most-recent first, then bound the response window. Sorting before the cap means a capped
- // response is the N newest chats (what clients show first) rather than an arbitrary slice.
- const chats = [...(await engine.getChats())].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
- return paginate(chats, opts.limit, opts.offset);
+ // Most-recent first. Sorting before the cap means a capped response is the N newest chats (what
+ // clients show first) rather than an arbitrary slice.
+ return [...(await engine.getChats())].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
+ }
+
+ async getChats(id: string, opts: ListOptions = {}): Promise<ChatSummary[]> {
+ return paginate(await this.listChats(id), opts.limit, opts.offset);
}
/**