Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): reject unmatched poll vote options

Yudhi Armyndharis5990f1377c31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67d319a12..d87c16358 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,10 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Preserve webhook outbox payloads until delivery or durable failure storage succeeds.
- Enforce webhook replay retention and keep later eligible failures moving through batches.
- Keep one terminal webhook failure per receiver idempotency key.
-
-### Fixed
-
-- Idempotent sends retain their key after an engine-stage failure, including HTTP 409, so a same-key retry cannot send another copy.
+- Retain send idempotency keys after engine-stage failures, including HTTP 409.
+- Reject poll votes with no matching options while preserving explicit vote clearing.
## [0.24.0] - 2026-10-03
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index eadd32158..fe6b0354d 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1456,6 +1456,11 @@ Cast a vote on a poll.
> **Options are texts, not ids.** whatsapp-web.js matches poll options by name, and no engine
> surfaces a stable per-option id through this API, so the text is the only handle available. A poll
> with two identically-worded options will therefore select **both**.
+>
+> A text that matches no option is ignored. When **none** of the texts match, the route answers `400`
+> with `code: "POLL_OPTION_NOT_FOUND"` and the poll's exact texts in `validOptions`, and nothing is
+> sent, so the current vote stays. (Before, whatsapp-web.js sent an empty selection, which cleared the
+> vote, and the route answered `200`.) Send `[]` to clear the vote on purpose.
> **Only recent polls can be voted on.** The poll must be within the 100-message window the engine
> fetches for the chat — the same limit that applies to react/delete/edit/pin. An older poll comes
@@ -1465,7 +1470,7 @@ Cast a vote on a poll.
> for _receiving_ votes. Sending one requires hand-building a `PollUpdateMessage` with HMAC-SHA256
> vote encryption keyed by the poll creation's `messageSecret`, which is not wired here.
-**Errors:** `400` session not active, or the target message is not a poll · `401` missing/invalid API key · `403` key lacks OPERATOR role · `404` poll not found in recent history · `501` Baileys engine · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)
+**Errors:** `400` session not active, the target message is not a poll, or none of the option texts match the poll (`POLL_OPTION_NOT_FOUND`) · `401` missing/invalid API key · `403` key lacks OPERATOR role · `404` poll not found in recent history · `501` Baileys engine · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)
#### POST /api/sessions/:sessionId/messages/pin
diff --git a/openapi.json b/openapi.json
index e1172224f..493c1d0cf 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6682,7 +6682,7 @@
}
},
"400": {
- "description": "Session not active, or the target message is not a poll",
+ "description": "Session not active, the target message is not a poll, or `POLL_OPTION_NOT_FOUND`: none of the option texts match the poll (the body lists `validOptions`). Nothing is sent, so the current vote stays.",
"content": {
"application/json": {
"schema": {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index d2e9d8721..f5c7820c5 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5247,6 +5247,51 @@ describe('votePoll', () => {
const adapter = ready(chatWith([]));
await expect(adapter.votePoll('[email protected]', 'OLD', ['x'])).rejects.toBeInstanceOf(MessageNotFoundError);
});
+
+ describe('option texts checked against the poll', () => {
+ const poll = (vote: jest.Mock) => ({
+ id: { _serialized: 'P1' },
+ pollOptions: [
+ { name: 'Pizza', localId: 0 },
+ { name: 'Sushi', localId: 1 },
+ ],
+ vote,
+ });
+
+ it('refuses options that match none of the poll texts with 400, never sending the empty vote', async () => {
+ // vote() would send an empty selection here, which clears the account's vote, while the route
+ // answered 200 (the hidden defect behind #1738).
+ const vote = jest.fn().mockResolvedValue(undefined);
+ const adapter = ready(chatWith([poll(vote)]));
+
+ const err = await adapter.votePoll('[email protected]', 'P1', ['pizza', 'Burger']).catch((e: unknown) => e);
+
+ expect(err).toBeInstanceOf(BadRequestException);
+ expect((err as BadRequestException).getResponse()).toEqual(
+ expect.objectContaining({ code: 'POLL_OPTION_NOT_FOUND', validOptions: ['Pizza', 'Sushi'] }),
+ );
+ expect((err as Error).message).toMatch(/"Pizza", "Sushi"/);
+ expect(vote).not.toHaveBeenCalled();
+ });
+
+ it('still votes when at least one text matches, as before', async () => {
+ const vote = jest.fn().mockResolvedValue(undefined);
+ const adapter = ready(chatWith([poll(vote)]));
+
+ await adapter.votePoll('[email protected]', 'P1', ['Pizza', 'Burger']);
+
+ expect(vote).toHaveBeenCalledWith(['Pizza', 'Burger']);
+ });
+
+ it('keeps an explicit empty array as a deliberate clear', async () => {
+ const vote = jest.fn().mockResolvedValue(undefined);
+ const adapter = ready(chatWith([poll(vote)]));
+
+ await adapter.votePoll('[email protected]', 'P1', []);
+
+ expect(vote).toHaveBeenCalledWith([]);
+ });
+ });
});
describe('pinMessage / unpinMessage', () => {
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 53ddf83bc..0150aca12 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -963,6 +963,27 @@ export class WwebjsMessaging {
try {
await this.withPage('votePoll', async () => {
const message = await this.findInFetchWindow(chatId, pollMessageId);
+ // vote() matches option TEXTS exactly and silently drops the ones that match nothing. When
+ // none match it sends an empty selection, the same as `options: []`, which CLEARS the vote
+ // while the route answered 200. Refuse that case with the poll's real options so a typo or a
+ // differently-cased text is reported instead of erasing the account's vote. An explicit `[]`
+ // is still a deliberate clear. A message with no pollOptions is not a poll; vote() below
+ // rejects it with its own error.
+ const pollOptions = (message as unknown as { pollOptions?: Array<{ name?: unknown }> }).pollOptions;
+ if (options.length > 0 && Array.isArray(pollOptions)) {
+ const names = pollOptions.map(o => o?.name).filter((n): n is string => typeof n === 'string');
+ if (!options.some(option => names.includes(option))) {
+ throw new BadRequestException({
+ statusCode: 400,
+ error: 'Bad Request',
+ message: `None of the options match poll ${pollMessageId}; options must be the exact texts: ${names
+ .map(n => JSON.stringify(n))
+ .join(', ')}`,
+ code: 'POLL_OPTION_NOT_FOUND',
+ validOptions: names,
+ });
+ }
+ }
await (message as unknown as { vote(selected: string[]): Promise<void> }).vote(options);
});
} catch (error) {
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index b2c186876..1043624fb 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -749,7 +749,12 @@ export class MessageController {
@ApiOperation({ summary: 'Cast a vote on a poll' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiResponse({ status: 200, description: 'Vote cast', type: MessageActionResponseDto })
- @ApiResponse({ status: 400, description: 'Session not active, or the target message is not a poll' })
+ @ApiResponse({
+ status: 400,
+ description:
+ 'Session not active, the target message is not a poll, or `POLL_OPTION_NOT_FOUND`: none of the ' +
+ 'option texts match the poll (the body lists `validOptions`). Nothing is sent, so the current vote stays.',
+ })
@ApiResponse({ status: 404, description: 'Poll not found in the chat’s recent history' })
@ApiResponse({ status: 501, description: 'Not supported on the Baileys engine' })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })