Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): unmark participant routes, exempt reply, cap bulk, align id spelling

Bhavya Chopra6f73496f6a9c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3dba63a2..df8caa78e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- API keys carry an optional `allowedChats` allowlist next to `allowedSessions`: a curated set of chats (groups and/or contacts) a key may 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)).
+- API keys can carry an `allowedChats` allowlist next to `allowedSessions`, scoping a key to a chosen set of groups and contacts (omit or leave empty for unrestricted). A restricted key is refused with `403` on every route not explicitly marked safe, and on a marked route each chat it names is checked against the allowlist, with identity resolved through the `lid_mappings` table so a phone entry also matches its resolved `@lid` form; of the list routes only `GET /sessions/:sessionId/chats` is usable, and it filters before paginating. Thanks @bhavyachopra99 and @lasithadilshan.
- 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.ts
index 5fd3574f5..82a0c3c35 100644
--- a/src/common/security/chat-scope.spec.ts
+++ b/src/common/security/chat-scope.spec.ts
@@ -72,6 +72,13 @@ describe('chat-scope', () => {
expect(await chatIdAllowed(scope, `${LID}@lid`, single)).toBe(true);
});
+ it('a phone entry does not admit the same-digits @lid in the expanded filter scope either', async () => {
+ const scope = await buildExpandedChatScope([`${PHONE}@c.us`], batch);
+ expect(chatScopeAllows(scope, `${PHONE}@lid`)).toBe(false);
+ const rows = [{ id: `${PHONE}@lid` }, { id: `${PHONE}@c.us` }];
+ expect(filterByChatScope(scope, rows, r => r.id)).toEqual([{ id: `${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);
diff --git a/src/engine/identity/jid-candidates.spec.ts b/src/engine/identity/jid-candidates.spec.ts
index 73447d71f..7620972d8 100644
--- a/src/engine/identity/jid-candidates.spec.ts
+++ b/src/engine/identity/jid-candidates.spec.ts
@@ -20,6 +20,13 @@ describe('resolveJidCandidates', () => {
expect(out).not.toContain(`${LID}@c.us`);
});
+ it('normalizes lid and group spellings so the guard and the list filter agree', async () => {
+ // A `:device` suffix and an upper-case domain must still match the stored neutral form.
+ expect(await resolveJidCandidates('777000111:5@lid', directory)).toEqual(['777000111@lid']);
+ expect(await resolveJidCandidates('555000111@LID', directory)).toContain('555000111@lid');
+ expect(await resolveJidCandidates('[email protected]', directory)).toEqual(['[email protected]']);
+ });
+
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']);
diff --git a/src/engine/identity/jid-candidates.ts b/src/engine/identity/jid-candidates.ts
index 28c30da23..5f61b5b05 100644
--- a/src/engine/identity/jid-candidates.ts
+++ b/src/engine/identity/jid-candidates.ts
@@ -23,11 +23,16 @@ export interface ContactDirectory {
export async function resolveJidCandidates(value: string, directory?: ContactDirectory): Promise<string[]> {
const parsed = parseWaId(value);
+ // Group ids are stored in the neutral `<id>@g.us` form, so normalize rather than echo the input:
+ // an upper-case domain must not make the guard's answer disagree with the list filter's.
+ if (parsed.kind === 'group') return [`${parsed.userPart}@g.us`];
if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {
return [value];
}
if (parsed.kind === 'lid') {
- const candidates = new Set<string>([value]);
+ // Start from the neutral `<lid>@lid`, not the raw input, for the same reason (an upper-case
+ // domain or a `:device` suffix must still match the stored form).
+ const candidates = new Set<string>([`${parsed.userPart}@lid`]);
const resolved = await directory?.resolveLid(parsed.userPart);
if (resolved) {
candidates.add(`${resolved}@c.us`);
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index b800c16eb..9320b8bf6 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -11,6 +11,19 @@ import { resolveNonNegativeIntEnv } from '../../config/configuration';
// back to engine re-resolution, so the cap trades a re-resolution for bounded memory, never data loss.
export const LID_MAPPING_CACHE_DEFAULT = 5000;
+/**
+ * SQLite binds at most 32766 variables in one statement (Postgres 65535), so an `IN (...)` over a
+ * large allowlist is chunked. Small enough to stay well inside both, large enough that a realistic
+ * allowlist is one round trip.
+ */
+const LID_QUERY_CHUNK = 500;
+
+function chunk<T>(items: T[], size = LID_QUERY_CHUNK): T[][] {
+ const out: T[][] = [];
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
+ return out;
+}
+
/**
* Narrow read/write port over the `lid -> phone` table. The Baileys session store depends on this (sync
* reads on the resolution hot path + write-through) and the message from-filter depends on the reverse
@@ -156,14 +169,15 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
*/
async resolveLidPersisted(jid: string): Promise<string | null> {
const lid = userPart(jid);
- const cached = this.getCached(lid);
- if (cached !== undefined) return cached;
+ // The TABLE is authoritative, not the mirror: a node can hold a stale negative for a lid another
+ // node has since mapped, and answering from the cache would refuse a chat the table admits.
try {
const row = await this.repo.findOne({ where: { lid } });
- return row?.phone ?? null;
+ if (row) return row.phone;
} catch {
- return null;
+ // The table may not exist yet (migration pending); fall back to the mirror.
}
+ return this.getCached(lid) ?? null;
}
/** Deterministic reverse lookup, companion to {@link resolveLidPersisted}: cache ∪ persisted table. */
@@ -179,24 +193,22 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
}
/**
- * 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.
+ * Batched forward lookup for a list filter: lid user-part -> phone digits. Chunked queries for the
+ * whole allowlist instead of one per entry, and the TABLE wins over the mirror so a stale cached
+ * negative cannot shadow a mapping another node persisted.
*/
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;
- }
+ for (const lid of lids) out[lid] = this.getCached(lid) ?? null;
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;
+ for (const batch of chunk(lids)) {
+ const rows = await this.repo.find({ where: { lid: In(batch) } });
+ // The table WINS: a stale cached negative must not shadow a mapping another node persisted.
+ for (const row of rows) out[row.lid] = row.phone;
}
} catch {
- // The table may not exist yet (migration pending); the cache is the best available answer.
+ // The table may not exist yet (migration pending); the mirror is the best available answer.
}
return out;
}
@@ -207,12 +219,14 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
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;
+ for (const batch of chunk(phones)) {
+ const rows = await this.repo.find({ where: { phone: In(batch) } });
+ 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.
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index b76b364b3..c5cd6ea1a 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -427,6 +427,15 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
}
});
+ it('a stale cached negative never shadows a mapping the table has', async () => {
+ const repo = makeFakeRepo();
+ const store = await newStore(repo);
+ await store.remember('222', null); // this node cached a negative
+ repo.rows[0].phone = '628888'; // another node has since mapped it in the table
+ expect(await store.resolveLidPersisted('222@lid')).toBe('628888');
+ expect(await store.phonesForLidsPersisted(['222'])).toEqual({ 222: '628888' });
+ });
+
it('resolveLidPersisted returns null for a lid with no persisted row', async () => {
const repo = makeFakeRepo();
const store = await newStore(repo);
diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.ts
index 0064410ce..5ebfd7a76 100644
--- a/src/modules/auth/chat-scope-coverage.spec.ts
+++ b/src/modules/auth/chat-scope-coverage.spec.ts
@@ -39,6 +39,16 @@ export const AGNOSTIC_GRANTS: ReadonlyArray<readonly [string, string]> = [
['session.controller.ts', 'findOne'],
];
+/**
+ * The complete set of handlers granted `@ChatQuotedAllowed()`: routes whose `quotedMessageId` is
+ * bound to the chat they send into, so a quote cannot name a chat outside the allowlist. Every entry
+ * is a deliberate decision; the spec fails if a grant is unused or unlisted.
+ */
+export const QUOTED_ALLOWED_GRANTS: ReadonlyArray<readonly [string, string]> = [
+ // Reply requires a quotedMessageId and both engines resolve it inside the named chat.
+ ['message.controller.ts', 'reply'],
+];
+
const REQUIRED_GUARD_FIELD = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})!\\s*:`);
const REQUIRED_BULK_FIELD = /\bmessages!\s*:/;
@@ -84,6 +94,16 @@ function requiredGuardChatDtos(dir: string): Set<string> {
return out;
}
+/** Every handler carrying `@ChatQuotedAllowed()` in `source`. */
+export function quotedAllowedHandlers(source: string): string[] {
+ const out: string[] = [];
+ const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(/gm;
+ for (let m = handlerRe.exec(source); m !== null; m = handlerRe.exec(source)) {
+ if (/@ChatQuotedAllowed\(\)/.test(m[1] ?? '')) out.push(m[2]);
+ }
+ return out;
+}
+
/** 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 }> = [];
@@ -232,6 +252,7 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedCh
expect(files.length).toBeGreaterThan(10);
const offenders: string[] = [];
const seenGrants = new Set<string>();
+ const seenQuoted = new Set<string>();
let marked = 0;
for (const file of files) {
const source = readFileSync(file, 'utf8');
@@ -251,6 +272,7 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedCh
});
marked += paired.length;
for (const { name, kind } of paired) if (kind === 'agnostic') seenGrants.add(`${fileName} :: ${name}`);
+ for (const name of quotedAllowedHandlers(source)) seenQuoted.add(`${fileName} :: ${name}`);
for (const violation of chatScopeViolations(source, fileName, requiredDtos)) {
offenders.push(`${posixPath} :: ${fileName} :: ${violation}`);
}
@@ -259,5 +281,6 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedCh
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());
+ expect([...seenQuoted].sort()).toEqual(QUOTED_ALLOWED_GRANTS.map(([f, h]) => `${f} :: ${h}`).sort());
});
});
diff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.ts
index 5d955776b..be56a2364 100644
--- a/src/modules/auth/decorators/auth.decorators.ts
+++ b/src/modules/auth/decorators/auth.decorators.ts
@@ -8,6 +8,7 @@ export const PUBLIC_KEY = 'isPublic';
export const SESSION_SCOPED_KEY = 'sessionScoped';
export const UNSCOPED_KEY = 'requireUnscopedKey';
export const CHAT_SCOPED_KEY = 'chatScoped';
+export const CHAT_QUOTED_ALLOWED_KEY = 'chatQuotedAllowed';
/**
* Mark a route as requiring a specific role
@@ -63,6 +64,16 @@ export type ChatScopeKind = 'fenced' | 'filtered' | 'agnostic';
*/
export const ChatScoped = (kind: ChatScopeKind) => SetMetadata(CHAT_SCOPED_KEY, kind);
+/**
+ * Exempt a handler from the chat fence's blanket refusal of `quotedMessageId`. Only mark a route
+ * whose quote is bound to the chat it is sent into: `POST .../messages/reply` requires a
+ * `quotedMessageId` and BOTH engines resolve it inside the named chat (Baileys asserts the stored
+ * message belongs to it, whatsapp-web.js fetches it from that chat), so the quote cannot name a
+ * chat outside the allowlist. Every other route refuses a quote outright, because a quote is a chat
+ * reference the guard cannot see.
+ */
+export const ChatQuotedAllowed = () => SetMetadata(CHAT_QUOTED_ALLOWED_KEY, true);
+
/**
* Get the current API key from request
* @example @CurrentApiKey() apiKey: ApiKey
diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.ts
index 20d16c2cd..5ceba8c66 100644
--- a/src/modules/auth/guards/api-key.guard.spec.ts
+++ b/src/modules/auth/guards/api-key.guard.spec.ts
@@ -8,7 +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';
+import { CHAT_QUOTED_ALLOWED_KEY, CHAT_SCOPED_KEY } from '../decorators/auth.decorators';
function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {
return {
@@ -576,6 +576,28 @@ describe('ApiKeyGuard', () => {
expect(await guard.canActivate(allowed)).toBe(true);
});
+ it('admits a quotedMessageId on a route marked @ChatQuotedAllowed (the reply route)', async () => {
+ metadata[CHAT_QUOTED_ALLOWED_KEY] = true;
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ // Both engines bind the reply's quote to the named chat, so it cannot reach another one.
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', {
+ chatId: ALLOWED_GROUP,
+ quotedMessageId: 'm-in-this-chat',
+ });
+ expect(await guard.canActivate(context)).toBe(true);
+ });
+
+ it('rejects an oversized bulk body before any per-entry lookup', async () => {
+ const apiKey = createMockApiKey({ allowedChats: [ALLOWED_GROUP] });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const messages = Array.from({ length: 101 }, () => ({ chatId: ALLOWED_GROUP, type: 'text' }));
+ const context = createMockContext({ 'x-api-key': 'key' }, {}, '127.0.0.1', { messages });
+ await expect(guard.canActivate(context)).rejects.toThrow(BadRequestException);
+ });
+
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);
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index 067f62b14..30023ce4c 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -11,6 +11,7 @@ import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { AuthService } from '../auth.service';
import { ChatScopeService } from '../chat-scope.service';
+import { BULK_MESSAGES_MAX } from '../../message/dto/bulk-message.dto';
import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';
import {
REQUIRED_ROLE_KEY,
@@ -18,6 +19,7 @@ import {
SESSION_SCOPED_KEY,
UNSCOPED_KEY,
CHAT_SCOPED_KEY,
+ CHAT_QUOTED_ALLOWED_KEY,
ChatScopeKind,
} from '../decorators/auth.decorators';
import { resolveClientIp } from '../../../common/utils/ip';
@@ -121,7 +123,7 @@ export class ApiKeyGuard implements CanActivate {
if (!chatScoped) {
throw new ForbiddenException('API key is restricted to selected chats');
}
- await this.assertChatsAllowed(request, apiKey);
+ await this.assertChatsAllowed(request, apiKey, context);
}
// Routes marked @RequireUnscopedKey carry no session dimension, so the allowedSessions check
@@ -149,6 +151,8 @@ export class ApiKeyGuard implements CanActivate {
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;
+ /** The bulk cap, shared with the DTO so the two cannot drift; applied BEFORE any per-entry lookup. */
+ private static readonly CHAT_BULK_MAX = BULK_MESSAGES_MAX;
/**
* Every chat id the guard can see in the request: route params, `?chatId=`, the body fields sends
@@ -167,6 +171,12 @@ export class ApiKeyGuard implements CanActivate {
const messages = b.messages;
if (messages === undefined || messages === null) return out;
if (!Array.isArray(messages)) throw new BadRequestException('messages must be an array');
+ // Reject an oversized batch here, before the per-entry lid lookups below: the pipe's
+ // @ArrayMaxSize(100) only runs after the guard, so without this one request could drive
+ // thousands of sequential table queries.
+ if (messages.length > ApiKeyGuard.CHAT_BULK_MAX) {
+ throw new BadRequestException(`messages must contain at most ${ApiKeyGuard.CHAT_BULK_MAX} entries`);
+ }
messages.forEach((item, i) => {
if (item === null || typeof item !== 'object') return;
out.push([`messages[${i}].chatId`, (item as { chatId?: unknown }).chatId]);
@@ -178,7 +188,7 @@ export class ApiKeyGuard implements CanActivate {
* 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> {
+ private async assertChatsAllowed(request: Request, apiKey: ApiKey, context: ExecutionContext): Promise<void> {
for (const [field, value] of this.chatIdsIn(request)) {
if (value === undefined || value === null) continue;
if (typeof value !== 'string') {
@@ -192,9 +202,14 @@ export class ApiKeyGuard implements CanActivate {
// `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.
+ // its allowlist into an allowed one. Refuse it outright, unless the handler is marked
+ // @ChatQuotedAllowed because it binds the quote to the chat it sends into (the reply route).
+ const quotedAllowed = this.reflector.getAllAndOverride<boolean>(CHAT_QUOTED_ALLOWED_KEY, [
+ context.getHandler(),
+ context.getClass(),
+ ]);
const body: unknown = request.body;
- if (body !== null && typeof body === 'object') {
+ if (!quotedAllowed && 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/group/group.controller.ts b/src/modules/group/group.controller.ts
index d3b097e79..54406378e 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -211,7 +211,6 @@ export class GroupController {
return { success: true, message: 'Participants added', results };
}
- @ChatScoped('fenced')
@Delete(':groupId/participants')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Remove participants from a group' })
@@ -237,7 +236,6 @@ export class GroupController {
return { success: true, message: 'Participants removed', results };
}
- @ChatScoped('fenced')
@Post(':groupId/participants/promote')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Promote participants to admin' })
@@ -264,7 +262,6 @@ export class GroupController {
return { success: true, message: 'Participants promoted to admin', results };
}
- @ChatScoped('fenced')
@Post(':groupId/participants/demote')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Demote participants from admin' })
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index f1e15304c..0bc0fba1f 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -154,6 +154,9 @@ class BulkMessageOptionsDto {
stopOnError?: boolean;
}
+/** Max recipients in one bulk request. The guard applies the same cap BEFORE its per-chat lookups. */
+export const BULK_MESSAGES_MAX = 100;
+
export class SendBulkMessageDto {
@ApiPropertyOptional({ description: 'Custom batch ID (auto-generated if not provided)' })
@IsOptional()
@@ -166,7 +169,7 @@ export class SendBulkMessageDto {
type: [BulkMessageItemDto],
})
@IsArray()
- @ArrayMaxSize(100)
+ @ArrayMaxSize(BULK_MESSAGES_MAX)
@ValidateNested({ each: true })
@Type(() => BulkMessageItemDto)
messages!: BulkMessageItemDto[];
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 0b0b5ea4b..7f878a6ee 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 { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';
+import { ChatQuotedAllowed, ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
import {
CHANNEL_MEDIA_501,
@@ -354,6 +354,7 @@ export class MessageController {
return this.messageService.sendPoll(sessionId, dto);
}
+ @ChatQuotedAllowed()
@ChatScoped('fenced')
@Post('reply')
@RequireRole(ApiKeyRole.OPERATOR)