Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): bound the options and text of an inbound poll

Yudhi Armyndharis3a7a8570f824
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index eb3b28c37..3c18fb28a 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -1,4 +1,6 @@
+import { POLL_MAX_OPTIONS, POLL_TEXT_MAX_LENGTH } from './message-mapper';
import {
+ BaileysBodyContent,
BaileysContextContent,
BaileysIncomingFields,
baileysChatJid,
@@ -1195,4 +1197,35 @@ describe('native poll choice metadata', () => {
expect(extractBaileysPoll({})).toBeUndefined();
expect(extractBaileysPoll({ pollCreationMessage: {} })).toBeUndefined();
});
+
+ describe.each(['pollCreationMessage', 'pollCreationMessageV2', 'pollCreationMessageV3'] as const)(
+ 'bounds on %s',
+ key => {
+ const content = (name: string, optionNames: string[]) => ({
+ [key]: { name, options: optionNames.map(optionName => ({ optionName })), selectableOptionsCount: 1 },
+ });
+
+ it('keeps a poll WhatsApp itself could send exactly as it is', () => {
+ const question = 'q'.repeat(255);
+ const options = Array.from({ length: 12 }, (_, i) => `${i}`.padEnd(100, 'o'));
+ expect(extractBaileysPoll(content(question, options))).toEqual({
+ name: question,
+ options,
+ allowMultipleAnswers: false,
+ });
+ expect(extractBaileysBody(content(question, options) as BaileysBodyContent)).toBe(question);
+ });
+
+ it('truncates an oversized poll, in the poll and in the body, and keeps it a poll', () => {
+ const long = 'x'.repeat(POLL_TEXT_MAX_LENGTH * 3);
+ const optionNames = Array.from({ length: POLL_MAX_OPTIONS * 50 }, (_, i) => `${i}${long}`);
+ const poll = extractBaileysPoll(content(long, optionNames))!;
+ expect(poll.options).toHaveLength(POLL_MAX_OPTIONS);
+ expect(poll.options.every(option => option.length === POLL_TEXT_MAX_LENGTH)).toBe(true);
+ expect(poll.options[1].startsWith('1xxx')).toBe(true);
+ expect(poll.name).toHaveLength(POLL_TEXT_MAX_LENGTH);
+ expect(extractBaileysBody(content(long, optionNames) as BaileysBodyContent)).toHaveLength(POLL_TEXT_MAX_LENGTH);
+ });
+ },
+ );
});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index c2382a985..b60caba23 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -6,6 +6,7 @@ import {
MessageType,
} from '../interfaces/whatsapp-engine.interface';
import { chatKind } from '../identity/wa-id';
+import { boundPollOptions, boundPollText } from './message-mapper';
/**
* Content types that change or annotate another message and carry nothing of their own: a poll vote,
@@ -165,6 +166,10 @@ export interface BaileysBodyContent {
} | null;
}
+/** A poll's question as it reaches the body, bounded like the poll's own copy of it. */
+const pollQuestion = (name: string | null | undefined): string | undefined =>
+ name == null ? undefined : boundPollText(name);
+
/**
* Extract the display text of an inbound Baileys message: plain text first, then a media caption,
* then the WhatsApp Business interactive shapes (interactive / buttons / template / interactive-
@@ -191,9 +196,9 @@ export function extractBaileysBody(content: BaileysBodyContent): string {
content.interactiveResponseMessage?.body?.text ??
content.listMessage?.description ??
content.listMessage?.title ??
- content.pollCreationMessage?.name ??
- content.pollCreationMessageV2?.name ??
- content.pollCreationMessageV3?.name ??
+ pollQuestion(content.pollCreationMessage?.name) ??
+ pollQuestion(content.pollCreationMessageV2?.name) ??
+ pollQuestion(content.pollCreationMessageV3?.name) ??
content.eventMessage?.name ??
content.buttonsResponseMessage?.selectedDisplayText ??
content.templateButtonReplyMessage?.selectedDisplayText ??
@@ -945,7 +950,11 @@ export function extractBaileysPoll(content: proto.IMessage): IncomingMessage['po
.map(option => option.optionName)
.filter((option): option is string => typeof option === 'string');
if (!options.length) return undefined;
- return { name: poll.name ?? '', options, allowMultipleAnswers: poll.selectableOptionsCount !== 1 };
+ return {
+ name: boundPollText(poll.name ?? ''),
+ options: boundPollOptions(options),
+ allowMultipleAnswers: poll.selectableOptionsCount !== 1,
+ };
}
/**
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index b43a444f2..d54b0c652 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -2,6 +2,8 @@ import {
buildIncomingMessageBase,
mapContactFields,
mapWwebjsMessageType,
+ POLL_MAX_OPTIONS,
+ POLL_TEXT_MAX_LENGTH,
RawContactFields,
RawMessageFields,
} from './message-mapper';
@@ -300,4 +302,40 @@ describe('poll choice metadata', () => {
});
expect(mapped.poll).toEqual({ name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: true });
});
+
+ describe('bounds', () => {
+ const poll = (over: Partial<RawMessageFields>): RawMessageFields => ({
+ id: { _serialized: 'P2' },
+ to: 'me',
+ body: 'Where?',
+ type: 'poll_creation',
+ timestamp: 100,
+ fromMe: false,
+ pollName: 'Where?',
+ pollOptions: ['Park', 'Beach'],
+ allowMultipleAnswers: false,
+ ...over,
+ });
+
+ it('keeps a poll WhatsApp itself could send exactly as it is', () => {
+ const question = 'q'.repeat(255);
+ const options = Array.from({ length: 12 }, (_, i) => `${i}`.padEnd(100, 'o'));
+ const mapped = buildIncomingMessageBase(poll({ body: question, pollName: question, pollOptions: options }));
+ expect(mapped.poll).toEqual({ name: question, options, allowMultipleAnswers: false });
+ expect(mapped.body).toBe(question);
+ });
+
+ it('truncates an oversized poll, in the poll and in the body, and keeps it a poll', () => {
+ const long = 'x'.repeat(POLL_TEXT_MAX_LENGTH * 3);
+ const pollOptions = Array.from({ length: POLL_MAX_OPTIONS * 50 }, (_, i) => ({ name: `${i}${long}` }));
+ const mapped = buildIncomingMessageBase(poll({ body: long, pollName: long, pollOptions }));
+ expect(mapped.type).toBe('poll');
+ expect(mapped.poll?.options).toHaveLength(POLL_MAX_OPTIONS);
+ expect(mapped.poll?.options.every(option => option.length === POLL_TEXT_MAX_LENGTH)).toBe(true);
+ expect(mapped.poll?.options[1].startsWith('1xxx')).toBe(true);
+ expect(mapped.poll?.name).toHaveLength(POLL_TEXT_MAX_LENGTH);
+ expect(mapped.body).toHaveLength(POLL_TEXT_MAX_LENGTH);
+ });
+ });
});
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index 1f658c645..e170a9b12 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -2,6 +2,25 @@ import { EditedMessage, IncomingMessage, MessageContact, MessageType } from '../
import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';
import { chatKind } from '../identity/wa-id';
+/**
+ * Bounds on an inbound poll, applied by both engines. WhatsApp itself allows 12 options of 100
+ * characters under a 255-character question; these sit well above that, so nothing a client can send
+ * is cut, while a malformed poll cannot bloat a stored row, a webhook payload or a socket frame. A poll
+ * over a bound is truncated, not dropped.
+ */
+export const POLL_MAX_OPTIONS = 32;
+export const POLL_TEXT_MAX_LENGTH = 1024;
+
+/** A poll question or option text, cut to {@link POLL_TEXT_MAX_LENGTH}. */
+export function boundPollText(text: string): string {
+ return text.slice(0, POLL_TEXT_MAX_LENGTH);
+}
+
+/** A poll's options, cut to {@link POLL_MAX_OPTIONS} entries of at most {@link POLL_TEXT_MAX_LENGTH}. */
+export function boundPollOptions(options: string[]): string[] {
+ return options.slice(0, POLL_MAX_OPTIONS).map(boundPollText);
+}
+
/**
* Map a whatsapp-web.js `MessageTypes` token to the engine-neutral {@link MessageType}, so no
* consumer outside the adapter sees wwebjs-specific type strings. Notably `chat` -> `text` (aligning
@@ -162,16 +181,20 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
};
}
- if (incoming.type === 'poll' && Array.isArray(msg.pollOptions)) {
- const options = msg.pollOptions
- .map(option => (typeof option === 'string' ? option : option?.name))
- .filter((option): option is string => typeof option === 'string');
- if (options.length) {
- incoming.poll = {
- name: msg.pollName ?? msg.body,
- options,
- allowMultipleAnswers: msg.allowMultipleAnswers === true,
- };
+ if (incoming.type === 'poll') {
+ // The question is the body of a poll, so it is bounded with the poll.
+ incoming.body = boundPollText(incoming.body);
+ if (Array.isArray(msg.pollOptions)) {
+ const options = msg.pollOptions
+ .map(option => (typeof option === 'string' ? option : option?.name))
+ .filter((option): option is string => typeof option === 'string');
+ if (options.length) {
+ incoming.poll = {
+ name: boundPollText(msg.pollName ?? msg.body),
+ options: boundPollOptions(options),
+ allowMultipleAnswers: msg.allowMultipleAnswers === true,
+ };
+ }
}
}