Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(group): reject participant ids WhatsApp cannot address
Yudhi Armyndharis7b718cb211d9
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex 62d0f33f1..d880ccd5c 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -44,6 +44,12 @@ const PARTICIPANTS_503 ='Deliberately not folded into the 200 above — a participant WhatsApp turned down is reported inside ' +'`results` and is an answer; an update that never came back is not.';+// Shared by group creation and the four participant writes: an entry that does not name an individual+// is rejected here rather than handed to the engine, where it produced an unnamed page-side failure.+const PARTICIPANT_ID_400 =+ 'A participant does not name an individual. Pass a phone number, `<phone>@c.us` or `<lid>@lid`; ' ++ 'a group id or free text is rejected.';+// NOTE: the session→groups LIST lives on the SessionController at GET /sessions/:id/groups (it// registered first and owns the canonical narrow projection). A bare @Get() here would collide on// the same path pattern (/sessions/{x}/groups) and be shadowed, so this controller owns only the@@ -168,6 +174,7 @@ export class GroupController {@ApiResponse({ status: 201, description: 'Group created', type: GroupSummaryDto })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ @ApiResponse({ status: 400, description: PARTICIPANT_ID_400 })async create(@Param('sessionId') sessionId: string, @Body() dto: CreateGroupDto) {return this.groupService.createGroup(sessionId, dto.name, dto.participants);}@@ -187,6 +194,7 @@ export class GroupController {@ApiResponse({ status: 503, description: PARTICIPANTS_503 })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ @ApiResponse({ status: 400, description: PARTICIPANT_ID_400 })@HttpCode(HttpStatus.OK)async addParticipants(@Param('sessionId') sessionId: string,@@ -212,6 +220,7 @@ export class GroupController {@ApiResponse({ status: 503, description: PARTICIPANTS_503 })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ @ApiResponse({ status: 400, description: PARTICIPANT_ID_400 })async removeParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@@ -237,6 +246,7 @@ export class GroupController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })@HttpCode(HttpStatus.OK)+ @ApiResponse({ status: 400, description: PARTICIPANT_ID_400 })async promoteParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@@ -262,6 +272,7 @@ export class GroupController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })@HttpCode(HttpStatus.OK)+ @ApiResponse({ status: 400, description: PARTICIPANT_ID_400 })async demoteParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex b571e1f84..5a40046d6 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -304,3 +304,76 @@ describe('GroupService membership requests', () => {expect(() => svc.getGroupMembershipRequests('s1', 'g1')).toThrow(BadRequestException);});});++describe('GroupService participant id validation (#1220)', () => {+ const GROUP = '[email protected]';++ const makeService = (engine: Partial<IWhatsAppEngine>, pacing: SendPacingService = inertPacing()) => {+ const engines = new EngineRegistry();+ engines.set('s1', engine as IWhatsAppEngine);+ return new GroupService(engines, pacing);+ };++ /**+ * The three status-only writes are synchronous forwarders, so their guard throws synchronously,+ * while createGroup/addParticipants are async. Routing both through a promise lets one table+ * cover all five without asserting the wrong failure mode for half of them.+ */+ const call = (svc: GroupService, op: string, participants: string[]) =>+ Promise.resolve().then(() =>+ op === 'createGroup'+ ? svc.createGroup('s1', 'Team', participants)+ : (svc as unknown as Record<string, (s: string, g: string, p: string[]) => Promise<unknown>>)[op](+ 's1',+ GROUP,+ participants,+ ),+ );++ it.each([+ ['removeParticipants'],+ ['promoteParticipants'],+ ['demoteParticipants'],+ ['addParticipants'],+ ['createGroup'],+ ])('%s rejects an unaddressable id with 400 before reaching the engine', async op => {+ const engineOp = jest.fn();+ const svc = makeService({ [op]: engineOp });++ await expect(call(svc, op, ['NOT A USER'])).rejects.toBeInstanceOf(BadRequestException);+ expect(engineOp).not.toHaveBeenCalled();+ });++ it('names every offending entry and leaves the valid ones out of the message', async () => {+ const svc = makeService({ removeParticipants: jest.fn() });++ const err = await call(svc, 'removeParticipants', ['[email protected]', 'NOT A USER', '[email protected]']).catch(+ (e: unknown) => e,+ );++ expect((err as Error).message).toContain('NOT A USER');+ expect((err as Error).message).toContain('[email protected]');+ expect((err as Error).message).not.toContain('[email protected]');+ });++ it('accepts a bare number, a c.us id and a lid, forwarding them verbatim', async () => {+ const removeParticipants = jest.fn().mockResolvedValue([]);+ const svc = makeService({ removeParticipants });++ await call(svc, 'removeParticipants', ['628123456789', '[email protected]', '12345678901234567890@lid']);++ expect(removeParticipants).toHaveBeenCalledWith(GROUP, ['628123456789', '[email protected]', '12345678901234567890@lid']);+ });++ it('rejects a malformed participant before it can consume reachout budget', async () => {+ // createGroup and addParticipants are paced; a batch that can never reach WhatsApp must not+ // draw on the cold-reachout budget on its way to a 400.+ const assertReachoutAllowed = jest.fn().mockResolvedValue(undefined);+ const svc = makeService({ addParticipants: jest.fn() }, {+ assertReachoutAllowed,+ } as unknown as SendPacingService);++ await expect(call(svc, 'addParticipants', ['NOT A USER'])).rejects.toBeInstanceOf(BadRequestException);+ expect(assertReachoutAllowed).not.toHaveBeenCalled();+ });+});diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex 503d4b901..e8cef6b6e 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -2,6 +2,7 @@ import { Injectable, BadRequestException, HttpException, HttpStatus, NotFoundExcimport { EngineRegistry } from '../../engine/engine-registry.service';import { GroupMemberAddMode, IWhatsAppEngine, MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';+import { isAddressableParticipant } from '../../engine/identity/wa-id';import { SetGroupPictureDto } from './dto/group.dto';import { paginate, ListOptions } from '../../common/utils/paginate';import { SendPacingService } from '../message/send-pacing.service';@@ -23,6 +24,26 @@ export class GroupService {return this.engines.require(sessionId);}+ /**+ * Reject participant ids WhatsApp cannot act on, before they reach an engine.+ *+ * This lives in the service rather than in ParticipantsDto because the MCP agent tools+ * (src/core/agent-tools/tools/group.tools.ts) call createGroup and addParticipants directly with a+ * plain `z.array(z.string())`, so a DTO-only check would leave that path unguarded. Mirrors+ * ContactService.assertAddressable.+ *+ * Runs before pacing on the two paced writes: a batch that can never reach WhatsApp must not draw+ * on the cold-reachout budget on its way to a 400.+ */+ private assertAddressableParticipants(participants: string[]): void {+ const invalid = participants.filter(p => !isAddressableParticipant(p));+ if (invalid.length) {+ throw new BadRequestException(+ `Not an individual participant id: ${invalid.join(', ')} — pass a phone number, <phone>@c.us or <lid>@lid`,+ );+ }+ }+getGroups(sessionId: string, opts: ListOptions = {}) {// getEngine throws synchronously (sync 400 guard); the engine returns the full set and we// bound the HTTP response window via paginate().@@ -44,6 +65,7 @@ export class GroupService {* reachout cost as adding them one by one — and is paced accordingly.*/async createGroup(sessionId: string, name: string, participants: string[]) {+ this.assertAddressableParticipants(participants);await this.pacing.assertReachoutAllowed(sessionId, participants);return this.getEngine(sessionId).createGroup(name, participants);}@@ -54,19 +76,23 @@ export class GroupService {* draws on the same cold-reachout budget a first message does.*/async addParticipants(sessionId: string, groupId: string, participants: string[]) {+ this.assertAddressableParticipants(participants);await this.pacing.assertReachoutAllowed(sessionId, participants);return this.getEngine(sessionId).addParticipants(groupId, participants);}removeParticipants(sessionId: string, groupId: string, participants: string[]) {+ this.assertAddressableParticipants(participants);return this.getEngine(sessionId).removeParticipants(groupId, participants);}promoteParticipants(sessionId: string, groupId: string, participants: string[]) {+ this.assertAddressableParticipants(participants);return this.getEngine(sessionId).promoteParticipants(groupId, participants);}demoteParticipants(sessionId: string, groupId: string, participants: string[]) {+ this.assertAddressableParticipants(participants);return this.getEngine(sessionId).demoteParticipants(groupId, participants);}