Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): accept per-item mention placeholders in send-bulk

Yudhi Armyndharise1a38ba413af
diff --git a/src/modules/message/bulk-mentions.spec.ts b/src/modules/message/bulk-mentions.spec.ts
new file mode 100644
index 000000000..6eb0c3f9c
--- /dev/null
+++ b/src/modules/message/bulk-mentions.spec.ts
@@ -0,0 +1,85 @@
+import { DataSource } from 'typeorm';
+import { HookManager } from '../../core/hooks';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import { Session } from '../session/entities/session.entity';
+import { BulkMessageService } from './bulk-message.service';
+import { MessageBatch } from './entities/message-batch.entity';
+import { Message } from './entities/message.entity';
+import type { MessageService } from './message.service';
+import type { SendPacingService } from './send-pacing.service';
+
+describe('bulk mentions', () => {
+ let db: DataSource;
+ let bulk: BulkMessageService;
+ let send: jest.Mock;
+ let hooks: HookManager;
+ beforeEach(async () => {
+ db = await new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message, MessageBatch, Session],
+ synchronize: true,
+ }).initialize();
+ await db.getRepository(Session).save({ id: 's1', name: 'sender', config: {} });
+ const engines = new EngineRegistry();
+ send = jest.fn().mockResolvedValue({ id: 'sent-1', timestamp: 1700000000 });
+ engines.set('s1', { sendImageMessage: send, sendTextMessage: send } as unknown as IWhatsAppEngine);
+ hooks = new HookManager();
+ bulk = new BulkMessageService(
+ db.getRepository(MessageBatch),
+ engines,
+ { saveOutgoingMessage: () => Promise.resolve() } as unknown as MessageService,
+ hooks,
+ {
+ assertSendAllowed: () => Promise.resolve(),
+ recordSendFailure: () => undefined,
+ recordSendSuccess: () => undefined,
+ } as unknown as SendPacingService,
+ );
+ });
+
+ afterEach(async () => {
+ jest.restoreAllMocks();
+ await db.destroy();
+ });
+
+ it('refuses a rendered mention that does not identify a person', async () => {
+ const processing = jest.spyOn(bulk as unknown as { processBatch: () => Promise<void> }, 'processBatch');
+ const batch = await bulk.createBatch('s1', {
+ messages: [
+ {
+ chatId: '[email protected]',
+ type: 'text',
+ content: { text: 'Hi @{{phone}}', mentions: ['{{phone}}@c.us'] },
+ variables: { phone: 'not-a-person' },
+ },
+ ],
+ });
+ await processing.mock.results[0].value;
+
+ const stored = await db.getRepository(MessageBatch).findOneByOrFail({ id: batch.id });
+ expect(stored.results[0].status).toBe('failed');
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a malformed WID', ['[email protected]']],
+ ['an oversized WID', [`${'1'.repeat(65)}@c.us`]],
+ ['an oversized list', Array.from({ length: 1025 }, () => '[email protected]')],
+ ['a sparse list', new Array<string>(1)],
+ ])('refuses a hook rewrite with %s', async (_label, mentions) => {
+ hooks.register('moderation', 'message:sending', () =>
+ Promise.resolve({ continue: true, data: { input: { text: 'Hi', mentions } } }),
+ );
+ const processing = jest.spyOn(bulk as unknown as { processBatch: () => Promise<void> }, 'processBatch');
+ const batch = await bulk.createBatch('s1', {
+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'Hi' } }],
+ });
+ await processing.mock.results[0].value;
+
+ const stored = await db.getRepository(MessageBatch).findOneByOrFail({ id: batch.id });
+ expect(stored.results[0].status).toBe('failed');
+ expect(send).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 2cab0acb8..f72d22e86 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -26,6 +26,8 @@ import {
BatchMessageResult,
} from './entities/message-batch.entity';
import { SendBulkMessageDto } from './dto/bulk-message.dto';
+import { MENTIONS_MAX, MENTION_WID_MAX_LENGTH } from './dto/send-message.dto';
+import { isMentionWid } from './dto/is-mention-wid.validator';
import { isMediaUrl } from '../../common/media/media-url';
import { MessageStatus } from './entities/message.entity';
import { EngineRegistry } from '../../engine/engine-registry.service';
@@ -915,6 +917,20 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,
* creation (a 400) and again per item after variables and the message:sending gate.
*/
private assertItemContent(type: string, content: BulkMessageContent, beforeRender = false): void {
+ // A mention may be a placeholder until it is rendered, so the DTO accepts it unchecked. What is sent is
+ // held to the single-send rule: a malformed WID reaches the engine as an opaque failure otherwise.
+ const mentions = content?.mentions;
+ if (
+ !beforeRender &&
+ mentions != null &&
+ (!Array.isArray(mentions) ||
+ mentions.length > MENTIONS_MAX ||
+ Array.from(mentions).some(
+ wid => typeof wid !== 'string' || wid.length > MENTION_WID_MAX_LENGTH || !isMentionWid(wid),
+ ))
+ ) {
+ throw new BadRequestException('content.mentions must contain bounded individual WIDs');
+ }
if (type === 'text') {
if (typeof content?.text !== 'string' || !content.text) {
throw new BadRequestException('A text item requires a non-empty content.text');
diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.ts
index 4c0c19605..230478a3f 100644
--- a/src/modules/message/dto/bulk-message.dto.spec.ts
+++ b/src/modules/message/dto/bulk-message.dto.spec.ts
@@ -66,6 +66,33 @@ describe('SendBulkMessageDto recipient', () => {
});
});
+describe('SendBulkMessageDto personalized mentions', () => {
+ it.each(['{{phone}}', '{phone}', '{{ phone }}'])('accepts a mention supplied by %s', async placeholder => {
+ await accepts({
+ messages: [
+ {
+ chatId: '[email protected]',
+ type: 'text',
+ content: { text: 'Hi @{{phone}}', mentions: [`${placeholder}@c.us`] },
+ variables: { phone: '62811' },
+ },
+ ],
+ });
+ });
+
+ it('still rejects a malformed literal mention', async () => {
+ await rejects({
+ messages: [
+ {
+ chatId: '[email protected]',
+ type: 'text',
+ content: { text: 'Hi', mentions: ['[email protected]'] },
+ },
+ ],
+ });
+ });
+});
+
// The url scheme is checked by the service after `variables` are applied, because a placeholder may
// stand for the whole URL; the DTO only requires a string.
describe('SendBulkMessageDto media url', () => {
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index 6c69f899f..97e5ce45c 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -13,6 +13,8 @@ import {
Min,
Max,
ArrayMaxSize,
+ ValidatorConstraint,
+ ValidatorConstraintInterface,
} from 'class-validator';
import { Type } from 'class-transformer';
import { Validate } from 'class-validator';
@@ -25,8 +27,24 @@ import {
MENTION_WID_MAX_LENGTH,
MESSAGE_TEXT_MAX_LENGTH,
} from './send-message.dto';
-import { IsMentionWidConstraint } from './is-mention-wid.validator';
+import { isMentionWid } from './is-mention-wid.validator';
import { BatchMessageStatus, BatchStatus } from '../entities/message-batch.entity';
+import { templateVariableNames } from '../batch-media.util';
+
+/**
+ * A bulk mention is a WID or a placeholder that the item's `variables` fill in, so one batch can tag a
+ * different participant per item. The rendered value is checked as a WID when the item runs.
+ */
+@ValidatorConstraint({ name: 'isBulkMentionWid', async: false })
+class IsBulkMentionWidConstraint implements ValidatorConstraintInterface {
+ validate(value: unknown): boolean {
+ return typeof value === 'string' && (isMentionWid(value) || templateVariableNames(value).length > 0);
+ }
+
+ defaultMessage(): string {
+ return 'each mentions entry must be an individual WID or contain a template placeholder';
+ }
+}
class BulkMediaDto {
@ApiPropertyOptional({ description: 'Media URL (http/https)' })
@@ -122,7 +140,7 @@ export class BulkMessageContentDto {
@ArrayMaxSize(MENTIONS_MAX)
@IsString({ each: true })
@MaxLength(MENTION_WID_MAX_LENGTH, { each: true })
- @Validate(IsMentionWidConstraint, { each: true })
+ @Validate(IsBulkMentionWidConstraint, { each: true })
mentions?: string[];
}