Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(mcp): check the form of a chat id on three tools
Yudhi Armyndharisf8681987c1fc
diff --git a/src/core/agent-tools/chat-id-schema.ts b/src/core/agent-tools/chat-id-schema.tsindex 1c1e80a36..f53ad8c35 100644--- a/src/core/agent-tools/chat-id-schema.ts+++ b/src/core/agent-tools/chat-id-schema.ts@@ -1,5 +1,5 @@import { z } from 'zod';-import { CHAT_ID_MAX_LENGTH } from '../../modules/message/dto/send-message.dto';+import { CHAT_ID_MAX_LENGTH, CHAT_JID_MESSAGE, CHAT_JID_PATTERN } from '../../modules/message/dto/send-message.dto';/*** A chat id taken by a tool, bounded as the REST bodies bound it: the id is stored under a btree index,@@ -7,3 +7,9 @@ import { CHAT_ID_MAX_LENGTH } from '../../modules/message/dto/send-message.dto';* tool error.*/export const chatIdSchema = z.string().min(1).max(CHAT_ID_MAX_LENGTH);++/**+ * A chat id for a tool whose REST body also checks the form of the id (localpart@host, no whitespace),+ * so a malformed id is refused here as it is there instead of failing in the engine.+ */+export const chatJidSchema = chatIdSchema.regex(CHAT_JID_PATTERN, CHAT_JID_MESSAGE);diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex 18652a09f..58da04b6c 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -7,7 +7,7 @@ import {MARK_READ_MESSAGE_ID_MESSAGE,MARK_READ_MESSAGE_ID_PATTERN,} from '../../../modules/session/dto/mark-chat-read.dto';-import { chatIdSchema } from '../chat-id-schema';+import { chatIdSchema, chatJidSchema } from '../chat-id-schema';import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';import { paginate } from '../../../common/utils/paginate';@@ -79,7 +79,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {sessionScoped: true,inputSchema: z.object({sessionId,- chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),+ chatId: chatJidSchema.describe('Chat JID (e.g. [email protected])'),}),handler: input => session.subscribeToPresence(input.sessionId, input.chatId).then(() => ({ success: true })),}),@@ -107,7 +107,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {sessionScoped: true,inputSchema: z.object({sessionId,- chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),+ chatId: chatJidSchema.describe('Chat JID (e.g. [email protected])'),messageIds: z// The element rule comes from the DTO rather than being restated here: the REST body// rejects a whitespace-only id, and this path reaches the engine without the DTO at all.@@ -132,7 +132,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {sessionScoped: true,inputSchema: z.object({sessionId,- chatId: chatIdSchema.describe('Chat JID (e.g. [email protected])'),+ chatId: chatJidSchema.describe('Chat JID (e.g. [email protected])'),}),handler: input => session.markUnread(input.sessionId, input.chatId).then(success => ({ success })),}),diff --git a/src/core/agent-tools/tools/tool-input-caps.spec.ts b/src/core/agent-tools/tools/tool-input-caps.spec.tsindex 1bbe977fe..281b119e8 100644--- a/src/core/agent-tools/tools/tool-input-caps.spec.ts+++ b/src/core/agent-tools/tools/tool-input-caps.spec.ts@@ -27,6 +27,9 @@ import {GroupSubjectDto,ParticipantsDto,} from '../../../modules/group/dto/group.dto';+import { MarkChatReadDto } from '../../../modules/session/dto/mark-chat-read.dto';+import { MarkChatUnreadDto } from '../../../modules/session/dto/mark-chat-unread.dto';+import { SubscribePresenceDto } from '../../../modules/session/dto/presence.dto';import { z } from 'zod';import type { AnyToolDescriptor } from '../tool-descriptor';import { allAgentTools } from '.';@@ -264,8 +267,48 @@ describe('agent-tool chat ids are capped as the REST bodies cap them', () => {);});+ // A JID of the given length, so the cap is what accepts or rejects it on the fields that also check the shape.+ const jidOfLength = (length: number): string => `${'x'.repeat(length - 2)}@c`;+it.each(chatFields)('%s accepts an id at the cap and rejects one past it', (_label, schema) => {- expect(schema.safeParse('x'.repeat(CHAT_ID_MAX_LENGTH)).success).toBe(true);- expect(schema.safeParse('x'.repeat(CHAT_ID_MAX_LENGTH + 1)).success).toBe(false);+ expect(schema.safeParse(jidOfLength(CHAT_ID_MAX_LENGTH)).success).toBe(true);+ expect(schema.safeParse(jidOfLength(CHAT_ID_MAX_LENGTH + 1)).success).toBe(false);+ });+});++/**+ * Three chat routes also require the form localpart@host with no whitespace, and the tools call the+ * service directly, so without the same rule a malformed id reaches the engine as a failed call where+ * REST answers 400. Each tool must accept and reject exactly the ids its REST body does.+ */+describe('MCP tool chat ids take the shape the REST bodies require', () => {+ const tools = allAgentTools({} as never);+ const CASES: Array<[string, new () => object]> = [+ ['SessionSubscribePresence', SubscribePresenceDto],+ ['SessionMarkChatRead', MarkChatReadDto],+ ['SessionMarkChatUnread', MarkChatUnreadDto],+ ];+ const MALFORMED = [+ 'abc',+ '@c.us',+ '628123@',+ ' [email protected]',+ '[email protected] ',+ '[email protected]\n',+ 'a [email protected]',+ '@@',+ '[email protected]@g.us',+ ];++ it.each(CASES)('%s accepts and rejects the same chat ids as its REST body', async (name, dtoClass) => {+ const tool = tools.find(t => t.name === name)!;+ for (const chatId of [...WELL_FORMED, ...MALFORMED]) {+ const toolAccepts = tool.inputSchema.safeParse({ sessionId: 's1', chatId }).success;+ const errors = await validate(plainToInstance(dtoClass, { chatId }, PIPE_TRANSFORM_OPTS));+ const restAccepts = !errors.some(e => e.property === 'chatId');+ expect({ chatId, toolAccepts }).toEqual({ chatId, toolAccepts: restAccepts });+ expect(restAccepts).toBe(WELL_FORMED.includes(chatId));+ }});});diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 65f530b2e..9cb6d0ca9 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -50,6 +50,15 @@ export const MESSAGE_TEXT_MAX_LENGTH = 4096;export const CHAT_ID_MAX_LENGTH = 255;export const BATCH_ID_MAX_LENGTH = 255;+/**+ * The structural check on a chat id for the chat routes that also verify its form: localpart@host with+ * no whitespace, engine-neutral so another engine's JID scheme (Baileys' `@s.whatsapp.net`) passes and+ * the adapter normalises further. Exported so the MCP tools that reach the same operations hold the+ * rule too: they call the service directly, and a restated pattern is how the two drift apart.+ */+export const CHAT_JID_PATTERN = /^[^\s@]+@[^\s@]+$/;+export const CHAT_JID_MESSAGE = 'chatId must be a valid chat JID in the form localpart@host';+// The cap on a prompt choice's id. It must equal BUTTON_TEXT_MAX_LENGTH in the Baileys message// mapper, which refuses to offer any inbound choice whose id is longer, so an id past this bound// can never name a choice that exists. Validating it against the text cap instead accepted such adiff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.tsindex dcde985f3..694b9ba06 100644--- a/src/modules/session/dto/mark-chat-read.dto.ts+++ b/src/modules/session/dto/mark-chat-read.dto.ts@@ -9,7 +9,7 @@ import {ValidateIf,MaxLength,} from 'class-validator';-import { CHAT_ID_MAX_LENGTH } from '../../message/dto/send-message.dto';+import { CHAT_ID_MAX_LENGTH, CHAT_JID_MESSAGE, CHAT_JID_PATTERN } from '../../message/dto/send-message.dto';/*** Ceiling on one request's receipt batch, so a single call cannot hand the engine an unbounded key@@ -40,9 +40,7 @@ export class MarkChatReadDto {// Engine-neutral structural check (localpart@host, no whitespace) so a different engine's JID// scheme (e.g. Baileys [email protected]) is accepted too; the adapter validates/normalises// further for its own engine. Keeps the early-400 on obvious garbage without coupling to wwebjs.- @Matches(/^[^\s@]+@[^\s@]+$/, {- message: 'chatId must be a valid chat JID in the form localpart@host',- })+ @Matches(CHAT_JID_PATTERN, { message: CHAT_JID_MESSAGE })chatId!: string;@ApiPropertyOptional({diff --git a/src/modules/session/dto/mark-chat-unread.dto.ts b/src/modules/session/dto/mark-chat-unread.dto.tsindex 6a1806b80..193b29b5e 100644--- a/src/modules/session/dto/mark-chat-unread.dto.ts+++ b/src/modules/session/dto/mark-chat-unread.dto.ts@@ -1,6 +1,6 @@import { ApiProperty } from '@nestjs/swagger';import { IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator';-import { CHAT_ID_MAX_LENGTH } from '../../message/dto/send-message.dto';+import { CHAT_ID_MAX_LENGTH, CHAT_JID_MESSAGE, CHAT_JID_PATTERN } from '../../message/dto/send-message.dto';/*** Deliberately separate from {@link MarkChatReadDto}, which the unread route used to share. The read@@ -18,8 +18,6 @@ export class MarkChatUnreadDto {@MaxLength(CHAT_ID_MAX_LENGTH)// Engine-neutral structural check (localpart@host, no whitespace) so a different engine's JID// scheme (e.g. Baileys [email protected]) is accepted too; the adapter normalises further.- @Matches(/^[^\s@]+@[^\s@]+$/, {- message: 'chatId must be a valid chat JID in the form localpart@host',- })+ @Matches(CHAT_JID_PATTERN, { message: CHAT_JID_MESSAGE })chatId!: string;}diff --git a/src/modules/session/dto/presence.dto.ts b/src/modules/session/dto/presence.dto.tsindex 1070e0079..13a6bac7b 100644--- a/src/modules/session/dto/presence.dto.ts+++ b/src/modules/session/dto/presence.dto.ts@@ -1,7 +1,7 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';import { IsBoolean, IsNotEmpty, IsString, Matches, MaxLength } from 'class-validator';import { ToStrictBoolean } from '../../../common/utils/strict-boolean';-import { CHAT_ID_MAX_LENGTH } from '../../message/dto/send-message.dto';+import { CHAT_ID_MAX_LENGTH, CHAT_JID_MESSAGE, CHAT_JID_PATTERN } from '../../message/dto/send-message.dto';export class SetOwnPresenceDto {@ApiProperty({@@ -25,9 +25,7 @@ export class SubscribePresenceDto {@MaxLength(CHAT_ID_MAX_LENGTH)// Same engine-neutral structural check the other chat-scoped DTOs use: localpart@host, no// whitespace, so a different engine's JID scheme is accepted and the adapter normalises further.- @Matches(/^[^\s@]+@[^\s@]+$/, {- message: 'chatId must be a valid chat JID in the form localpart@host',- })+ @Matches(CHAT_JID_PATTERN, { message: CHAT_JID_MESSAGE })chatId!: string;}