Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): read Baileys polls sent under the V4 and V5 keys

Yudhi Armyndhariseecb3f819b5b
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index 493247922..b843f2674 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -55,6 +55,10 @@ describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)',
['pollCreationMessage', false, 'poll'],
['pollCreationMessageV2', false, 'poll'],
['pollCreationMessageV3', false, 'poll'],
+ ['pollCreationMessageV4', false, 'poll'],
+ ['pollCreationMessageV5', false, 'poll'],
+ // A vote changes a poll and carries nothing of its own; it is never a poll itself.
+ ['pollUpdateMessage', false, 'unknown'],
// Regression trap: calls arrive via the `call` socket event, never as a message content type,
// so any call-ish token must stay 'unknown' (no accidental mapping).
['callLogMessage', false, 'unknown'],
@@ -171,6 +175,23 @@ describe('extractBaileysBody (inbound text/caption + interactive shapes)', () =>
expect(extractBaileysBody({ pollCreationMessage: { name: 'Lunch order?' } })).toBe('Lunch order?');
expect(extractBaileysBody({ pollCreationMessageV2: { name: 'Team offsite?' } })).toBe('Team offsite?');
expect(extractBaileysBody({ pollCreationMessageV3: { name: 'Standup time?' } })).toBe('Standup time?');
+ expect(extractBaileysBody({ pollCreationMessageV5: { name: 'Quiz?' } })).toBe('Quiz?');
+ expect(
+ extractBaileysBody({ pollCreationMessageV4: { message: { pollCreationMessage: { name: 'Wrapped?' } } } }),
+ ).toBe('Wrapped?');
+ });
+
+ it('reads a V4 poll one level down only, and nothing but a poll from inside it', () => {
+ expect(
+ extractBaileysBody({
+ pollCreationMessageV4: {
+ message: { pollCreationMessageV4: { message: { pollCreationMessage: { name: 'Deep' } } } },
+ },
+ } as BaileysBodyContent),
+ ).toBe('');
+ expect(
+ extractBaileysBody({ pollCreationMessageV4: { message: { conversation: 'not a poll' } } } as BaileysBodyContent),
+ ).toBe('');
});
it('returns empty for a poll with no name rather than falling through to other sources', () => {
@@ -272,6 +293,13 @@ describe('extractBaileysContext (quoted body shares the live body extractor)', (
expect(extractBaileysContext(content).ephemeralDuration).toBe(86400);
});
+ it('reads the disappearing-messages timer off the poll inside a pollCreationMessageV4', () => {
+ const content = {
+ pollCreationMessageV4: { message: { pollCreationMessage: { contextInfo: { expiration: 604800 } } } },
+ } as BaileysContextContent;
+ expect(extractBaileysContext(content).ephemeralDuration).toBe(604800);
+ });
+
it('reads no timer when no content node carries one', () => {
expect(extractBaileysContext({ conversation: 'hi' } as BaileysContextContent).ephemeralDuration).toBeUndefined();
});
@@ -1170,20 +1198,56 @@ describe('isBaileysCatalogShare (the productMessage arm with no product)', () =>
});
describe('native poll choice metadata', () => {
- it.each(['pollCreationMessage', 'pollCreationMessageV2', 'pollCreationMessageV3'] as const)(
- 'reads %s without changing option texts',
- key => {
- expect(
- extractBaileysPoll({
- [key]: {
- name: 'Where?',
- options: [{ optionName: ' Park ' }, { optionName: 'Beach' }],
- selectableOptionsCount: 1,
- },
+ type PollNode = { name?: string; options?: Array<{ optionName?: string }>; selectableOptionsCount?: number };
+ // Every content key a poll travels under. pollCreationMessageV4 wraps a whole message, with the poll inside it.
+ const shapes: Array<[string, (poll: PollNode) => Record<string, unknown>]> = [
+ ['pollCreationMessage', poll => ({ pollCreationMessage: poll })],
+ ['pollCreationMessageV2', poll => ({ pollCreationMessageV2: poll })],
+ ['pollCreationMessageV3', poll => ({ pollCreationMessageV3: poll })],
+ ['pollCreationMessageV5', poll => ({ pollCreationMessageV5: poll })],
+ ...(
+ ['pollCreationMessage', 'pollCreationMessageV2', 'pollCreationMessageV3', 'pollCreationMessageV5'] as const
+ ).map((inner): [string, (poll: PollNode) => Record<string, unknown>] => [
+ `pollCreationMessageV4 around ${inner}`,
+ poll => ({ pollCreationMessageV4: { message: { [inner]: poll } } }),
+ ]),
+ ];
+
+ it.each(shapes)('reads %s without changing option texts', (_label, wrap) => {
+ expect(
+ extractBaileysPoll(
+ wrap({
+ name: 'Where?',
+ options: [{ optionName: ' Park ' }, { optionName: 'Beach' }],
+ selectableOptionsCount: 1,
}),
- ).toEqual({ name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: false });
- },
- );
+ ),
+ ).toEqual({ name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: false });
+ });
+
+ it('reads a V5 quiz as its question and options, with the correct answer kept out of the options', () => {
+ expect(
+ extractBaileysPoll({
+ pollCreationMessageV5: {
+ name: 'Capital of France?',
+ options: [{ optionName: 'Paris' }, { optionName: 'Lyon' }],
+ selectableOptionsCount: 1,
+ pollType: 1,
+ correctAnswer: { optionName: 'Paris' },
+ },
+ }),
+ ).toEqual({ name: 'Capital of France?', options: ['Paris', 'Lyon'], allowMultipleAnswers: false });
+ });
+
+ it('opens a V4 wrapper one level only', () => {
+ const poll = { name: 'Deep', options: [{ optionName: 'a' }, { optionName: 'b' }] };
+ expect(
+ extractBaileysPoll({
+ pollCreationMessageV4: { message: { pollCreationMessageV4: { message: { pollCreationMessage: poll } } } },
+ }),
+ ).toBeUndefined();
+ expect(extractBaileysPoll({ pollCreationMessageV4: {} })).toBeUndefined();
+ });
it('reports multiple choices and omits unavailable poll data', () => {
expect(
extractBaileysPoll({
@@ -1198,55 +1262,51 @@ describe('native poll choice metadata', () => {
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 },
- });
+ describe.each(shapes)('bounds on %s', (_label, wrap) => {
+ const content = (name: string, optionNames: string[]) =>
+ wrap({ 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('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);
+ });
- // The numbers are written out here, not read from the constants, so moving either by one shows up.
- it('keeps a poll of 32 options with 1024 characters in each text whole', () => {
- const text = (i: number) => `${i}`.padEnd(1024, 'x');
- const options = Array.from({ length: 32 }, (_, i) => text(i));
- expect(extractBaileysPoll(content(text(99), options))).toEqual({
- name: text(99),
- options,
- allowMultipleAnswers: false,
- });
- expect(extractBaileysBody(content(text(99), options) as BaileysBodyContent)).toBe(text(99));
+ // The numbers are written out here, not read from the constants, so moving either by one shows up.
+ it('keeps a poll of 32 options with 1024 characters in each text whole', () => {
+ const text = (i: number) => `${i}`.padEnd(1024, 'x');
+ const options = Array.from({ length: 32 }, (_, i) => text(i));
+ expect(extractBaileysPoll(content(text(99), options))).toEqual({
+ name: text(99),
+ options,
+ allowMultipleAnswers: false,
});
+ expect(extractBaileysBody(content(text(99), options) as BaileysBodyContent)).toBe(text(99));
+ });
- it('cuts a poll at its 33rd option and at the 1025th character of a text', () => {
- const text = (i: number) => `${i}`.padEnd(1025, 'x');
- const options = Array.from({ length: 33 }, (_, i) => text(i));
- const poll = extractBaileysPoll(content(text(99), options))!;
- expect(poll.options).toEqual(options.slice(0, 32).map(option => option.slice(0, 1024)));
- expect(poll.name).toBe(text(99).slice(0, 1024));
- expect(extractBaileysBody(content(text(99), options) as BaileysBodyContent)).toBe(text(99).slice(0, 1024));
- });
+ it('cuts a poll at its 33rd option and at the 1025th character of a text', () => {
+ const text = (i: number) => `${i}`.padEnd(1025, 'x');
+ const options = Array.from({ length: 33 }, (_, i) => text(i));
+ const poll = extractBaileysPoll(content(text(99), options))!;
+ expect(poll.options).toEqual(options.slice(0, 32).map(option => option.slice(0, 1024)));
+ expect(poll.name).toBe(text(99).slice(0, 1024));
+ expect(extractBaileysBody(content(text(99), options) as BaileysBodyContent)).toBe(text(99).slice(0, 1024));
+ });
- 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);
- });
- },
- );
+ 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 b60caba23..ebd47af6d 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -85,7 +85,10 @@ export function mapBaileysMessageType(
case 'pollCreationMessage':
case 'pollCreationMessageV2':
case 'pollCreationMessageV3':
+ case 'pollCreationMessageV4':
+ case 'pollCreationMessageV5':
// Native polls; WhatsApp bumps the content key across versions, all map to the same neutral type.
+ // V4 and V5 are read from the pinned library's proto schema (see pollCreationOf).
return 'poll';
case 'interactiveMessage':
case 'buttonsMessage':
@@ -145,6 +148,9 @@ export interface BaileysBodyContent {
pollCreationMessage?: { name?: string | null } | null;
pollCreationMessageV2?: { name?: string | null } | null;
pollCreationMessageV3?: { name?: string | null } | null;
+ pollCreationMessageV5?: { name?: string | null } | null;
+ /** A wrapper whose inner message carries the poll under one of the keys above. */
+ pollCreationMessageV4?: { message?: PollCreationKeys<{ name?: string | null }> | null } | null;
/** A shared WhatsApp event; only its display name is surfaced as text. */
eventMessage?: { name?: string | null } | null;
/** The user tapping a business message button: which visible label they pressed. */
@@ -170,6 +176,28 @@ export interface BaileysBodyContent {
const pollQuestion = (name: string | null | undefined): string | undefined =>
name == null ? undefined : boundPollText(name);
+/** The content keys that carry a PollCreationMessage directly. */
+interface PollCreationKeys<P> {
+ pollCreationMessage?: P | null;
+ pollCreationMessageV2?: P | null;
+ pollCreationMessageV3?: P | null;
+ pollCreationMessageV5?: P | null;
+}
+
+/**
+ * The poll a message carries under one of {@link PollCreationKeys}. `pollCreationMessageV4` is a
+ * FutureProofMessage that the library's normalizeMessageContent does not open, so callers read its
+ * inner message with this once, one level down. V4 and V5 (a PollCreationMessage with quiz fields)
+ * are handled from the proto schema of the pinned library; no inbound message under either key has
+ * been captured from a live account.
+ */
+const pollCreationOf = <P>(content: PollCreationKeys<P> | null | undefined): P | undefined =>
+ content?.pollCreationMessage ??
+ content?.pollCreationMessageV2 ??
+ content?.pollCreationMessageV3 ??
+ content?.pollCreationMessageV5 ??
+ undefined;
+
/**
* 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-
@@ -199,6 +227,8 @@ export function extractBaileysBody(content: BaileysBodyContent): string {
pollQuestion(content.pollCreationMessage?.name) ??
pollQuestion(content.pollCreationMessageV2?.name) ??
pollQuestion(content.pollCreationMessageV3?.name) ??
+ pollQuestion(content.pollCreationMessageV5?.name) ??
+ pollQuestion(pollCreationOf(content.pollCreationMessageV4?.message)?.name) ??
content.eventMessage?.name ??
content.buttonsResponseMessage?.selectedDisplayText ??
content.templateButtonReplyMessage?.selectedDisplayText ??
@@ -851,6 +881,8 @@ export interface BaileysContextContent {
templateButtonReplyMessage?: BaileysContextCarrier | null;
listResponseMessage?: BaileysContextCarrier | null;
interactiveResponseMessage?: BaileysContextCarrier | null;
+ /** A poll wrapper; the poll inside it carries the `contextInfo`. */
+ pollCreationMessageV4?: { message?: object | null } | null;
}
/** Everything the context region of an inbound message yields — not just the quote. */
@@ -894,9 +926,11 @@ export function extractBaileysContext(content: BaileysContextContent): BaileysMe
const contextInfo = subForContext?.contextInfo;
// WhatsApp stamps the timer on every message in a disappearing chat, a product, poll, contact card, live
// location, order or event included, so any content node answers when the carriers above have none.
+ // A V4 poll's node is one level down, inside its wrapper.
const expiration =
contextInfo?.expiration ??
Object.values(content)
+ .concat(Object.values(content.pollCreationMessageV4?.message ?? {}))
.map(node => (node as BaileysContextCarrier | null | undefined)?.contextInfo?.expiration)
.find((e): e is number => typeof e === 'number' && e > 0);
@@ -944,7 +978,7 @@ export function mapBaileysStatus(status: number | null | undefined): DeliverySta
/** Extract native poll versions from content already normalized by Baileys. */
export function extractBaileysPoll(content: proto.IMessage): IncomingMessage['poll'] {
- const poll = content.pollCreationMessage ?? content.pollCreationMessageV2 ?? content.pollCreationMessageV3;
+ const poll = pollCreationOf(content) ?? pollCreationOf(content.pollCreationMessageV4?.message);
if (!poll) return undefined;
const options = (poll.options ?? [])
.map(option => option.optionName)
diff --git a/test/engine-real/baileys-inbound.spec.mjs b/test/engine-real/baileys-inbound.spec.mjs
index b5a9e531c..8ea485b8a 100644
--- a/test/engine-real/baileys-inbound.spec.mjs
+++ b/test/engine-real/baileys-inbound.spec.mjs
@@ -33,8 +33,10 @@ const silent = { log() {}, debug() {}, verbose() {}, warn() {}, error() {} };
* Feed one message through the upsert handler and resolve with whichever callback it reaches first.
* A message that reaches none resolves as 'none' once the handler has had time to settle.
*/
-function deliver(object) {
- const message = lib.proto.WebMessageInfo.fromObject({ messageTimestamp: 1_700_000_000, ...object });
+function deliver(object, { wire = false } = {}) {
+ let message = lib.proto.WebMessageInfo.fromObject({ messageTimestamp: 1_700_000_000, ...object });
+ // Encoded and decoded again, the message is in the form the socket hands over after reading the bytes.
+ if (wire) message = lib.proto.WebMessageInfo.decode(lib.proto.WebMessageInfo.encode(message).finish());
return new Promise(resolve => {
const to = kind => payload => resolve({ kind, payload });
const noop = () => undefined;
@@ -187,6 +189,55 @@ test('a delete for everyone reaches the revoked callback', async () => {
assert.equal(payload.revokedId, 'TARGET3');
});
+// pollCreationMessageV4 wraps a whole message that the library's normalizeMessageContent does not open, and
+// pollCreationMessageV5 adds quiz fields. Both come from the proto schema; no live capture of either exists.
+const POLL = {
+ name: 'Lunch?',
+ options: [{ optionName: 'Rice' }, { optionName: 'Noodles' }],
+ selectableOptionsCount: 1,
+};
+for (const [label, message] of [
+ ['pollCreationMessage', { pollCreationMessage: POLL }],
+ ['pollCreationMessageV2', { pollCreationMessageV2: POLL }],
+ ['pollCreationMessageV3', { pollCreationMessageV3: POLL }],
+ ['pollCreationMessageV4', { pollCreationMessageV4: { message: { pollCreationMessage: POLL } } }],
+ [
+ 'pollCreationMessageV5',
+ {
+ pollCreationMessageV5: {
+ ...POLL,
+ pollType: lib.proto.Message.PollType.QUIZ,
+ correctAnswer: { optionName: 'Rice' },
+ },
+ },
+ ],
+]) {
+ test(`a poll under ${label}, read from its wire bytes, is a poll with its question and options`, async () => {
+ const { kind, payload } = await deliver(inbound(`P-${label}`, message), { wire: true });
+ assert.equal(kind, 'message');
+ assert.equal(payload.type, 'poll');
+ assert.equal(payload.body, 'Lunch?');
+ assert.deepEqual(payload.poll, { name: 'Lunch?', options: ['Rice', 'Noodles'], allowMultipleAnswers: false });
+ });
+}
+
+test('a poll vote does not reach onMessage', async () => {
+ // deliver's settle timer is unref'd, so hold the event loop open until it fires.
+ const hold = setTimeout(() => undefined, 3000);
+ const { kind } = await deliver(
+ inbound('P-vote', {
+ pollUpdateMessage: {
+ pollCreationMessageKey: { id: 'POLL1', remoteJid: PEER, fromMe: true },
+ vote: { encPayload: Buffer.alloc(16, 1), encIv: Buffer.alloc(12, 2) },
+ senderTimestampMs: 1_700_000_000_000,
+ },
+ }),
+ { wire: true },
+ );
+ clearTimeout(hold);
+ assert.equal(kind, 'none');
+});
+
test('a group message from an @lid participant names its author and flags the lid sender', async () => {
const { payload } = await deliver(
inbound('A13', { conversation: 'hi group' }, { remoteJid: GROUP, participant: LID }),