Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): refuse a null id list and keep read receipts in their chat
Yudhi Armyndharisd665880f36e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db42eddd2..34ae69fb6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,10 +14,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed- `POST /sessions/{sessionId}/chats/unread` publishes its own `MarkChatUnreadDto` rather than sharing `MarkChatReadDto`. The body is unchanged (`chatId` alone), but a generated client sees the schema under a new name.-- ⚠️ **Breaking (Go and Java clients).** `subscribePresence` takes its own `SubscribePresenceRequest` rather than the shared `MarkChatRequest`, which now serves `markUnread` alone. Swap the type at the call site; the wire body is unchanged. `SubscribePresenceDto` had no contract-gate coverage while one type stood for two routes.+- ⚠️ **Breaking (Go, Java and typed Python callers).** `markRead` and `subscribePresence` each take their own request type rather than the shared `MarkChatRequest`, which now serves `markUnread` alone. Swap the type at both call sites; the wire body is unchanged and the JavaScript and PHP clients are unaffected. `SubscribePresenceDto` had no contract-gate coverage while one type stood for two routes.### Fixed+- `POST /chats/read` answers 400 for `"messageIds": null` instead of 500. `@IsOptional` skips every validator for null as well as undefined, so the value reached the Baileys adapter and was dereferenced there. The published schema now carries `minItems` too, so it no longer advertises an empty array the server refuses.+- A read receipt goes only to the chat the caller named. A message id belonging to another chat in the same session carried that chat's address out of the message store, so the receipt landed there while the route reported success for the chat in the path.+- The Go client can express an empty `messageIds` again. `omitempty` on a plain slice dropped it, so a caller asking for nothing to be acknowledged silently acknowledged the newest message; the field is a pointer, so absent and empty are distinct on the wire.- The dashboard CSP nonce is substituted at every occurrence in the served document, not only the first. One placeholder exists today, so a second would have been left reading the literal text and its script refused by the browser.- Outbound webhook deliveries survive a hard crash. Fan-out was fire-and-forget, so a crash between persisting a message and completing its POST lost the delivery, against a documented at-least-once contract. Deliveries are now recorded before they are attempted, and a bounded sweep replays whatever is stranded under its stored idempotency key.- Settled outbound delivery records are pruned after `WEBHOOK_OUTBOX_RETENTION_DAYS` (default 7). A record that can still be replayed is never pruned on age, and a non-positive window falls back to the default rather than letting the table grow without bound.diff --git a/openapi.json b/openapi.jsonindex fcd120859..ba8ff23e8 100644--- a/openapi.json+++ b/openapi.json@@ -10265,6 +10265,7 @@"messageIds": {"description": "Specific message IDs to mark read. Baileys acknowledges individual messages, so without this only the newest message the engine still holds in memory gets a receipt — a burst leaves its earlier messages unread forever, and a restarted session has no message to acknowledge at all. Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.","maxItems": 100,+ "minItems": 1,"example": ["3EB0C767D26B8A3F1A2B","3EB0C767D26B8A3F1A2C"diff --git a/sdk/go/mark_read_body_test.go b/sdk/go/mark_read_body_test.gonew file mode 100644index 000000000..b73560b36--- /dev/null+++ b/sdk/go/mark_read_body_test.go@@ -0,0 +1,50 @@+package openwa++import (+ "context"+ "strings"+ "testing"+)++// The three states of messageIds differ on the wire, and a plain []string with omitempty could not+// tell two of them apart: an empty slice was dropped, so a caller asking for nothing to be+// acknowledged silently acknowledged the newest message instead. The pointer makes "absent" and+// "empty" distinct, and this pins all three so the tag cannot quietly go back.+func TestMarkReadBodyDistinguishesAbsentFromEmpty(t *testing.T) {+ empty := []string{}+ named := []string{"3EB0C767D26B8A3F1A2B"}++ cases := []struct {+ name string+ body MarkChatReadRequest+ want string+ }{+ {"absent omits the key", MarkChatReadRequest{ChatID: "[email protected]"}, `{"chatId":"[email protected]"}`},+ {"empty sends []", MarkChatReadRequest{ChatID: "[email protected]", MessageIDs: &empty}, `"messageIds":[]`},+ {"named sends the ids", MarkChatReadRequest{ChatID: "[email protected]", MessageIDs: &named}, `"messageIds":["3EB0C767D26B8A3F1A2B"]`},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true}`}+ c := newTestClient(t, rt)++ if _, err := c.Chats.MarkRead(context.Background(), "s1", tc.body); err != nil {+ t.Fatalf("MarkRead: %v", err)+ }+ if got := string(rt.lastRaw); !strings.Contains(got, tc.want) {+ t.Fatalf("body = %s, want it to contain %s", got, tc.want)+ }+ })+ }++ // The absent case must ALSO not carry the key at all, which "contains" cannot express.+ rt := &recordTransport{status: 200, body: `{"success":true}`}+ c := newTestClient(t, rt)+ if _, err := c.Chats.MarkRead(context.Background(), "s1", MarkChatReadRequest{ChatID: "[email protected]"}); err != nil {+ t.Fatalf("MarkRead: %v", err)+ }+ if strings.Contains(string(rt.lastRaw), "messageIds") {+ t.Fatalf("absent body must omit messageIds entirely, got %s", rt.lastRaw)+ }+}diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.goindex 09a46c65c..9f5e7d3a1 100644--- a/sdk/go/types_chat.go+++ b/sdk/go/types_chat.go@@ -35,7 +35,13 @@ type MarkChatReadRequest struct {// MessageIDs are the messages to acknowledge (at most 100; an empty list is refused). Baileys// acknowledges individual messages, so without this only the newest message the engine still// holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.- MessageIDs []string `json:"messageIds,omitempty"`+ //+ // A POINTER because the three states differ on the wire and a plain slice cannot tell two of+ // them apart: nil omits the key (acknowledge the newest), &[]string{} sends [] (the server+ // refuses it with a 400), and a populated slice names the messages. With `[]string` plus+ // omitempty an empty slice was dropped, so a caller asking for nothing to be acknowledged+ // silently acknowledged the newest message instead.+ MessageIDs *[]string `json:"messageIds,omitempty"`}// ChatState is the typing indicator a chat shows.diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex c176bef37..a68bf41cb 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -355,7 +355,9 @@ export class BaileysContacts {* synthesised key, which is what the 1:1 case ran on before.*/private async receiptKeys(chatId: string, messageIds?: string[]): Promise<WAMessageKey[]> {- if (messageIds === undefined) {+ // null as well as undefined: the REST body rejects an explicit null, but this is the engine+ // boundary and an internal caller reaching it with one used to dereference it below as a 500.+ if (messageIds === undefined || messageIds === null) {const last = this.host.lastMessage(chatId);return last ? [last.key] : [];}@@ -364,7 +366,17 @@ export class BaileysContacts {}const remoteJid = this.host.toEngineJid(chatId);const stored = (await this.host.getStoredMessages(messageIds)) ?? [];- const keyById = new Map(stored.filter(msg => msg.key?.id).map(msg => [msg.key.id as string, msg.key]));+ // A stored key is only usable when it belongs to THIS chat. Without the check, an id from+ // another chat in the same session carried that chat's remoteJid into readMessages, so the+ // receipt landed there while the route answered success for the chat the caller named. Both+ // sides fold through toEngineJid so the @c.us and @s.whatsapp.net spellings of one chat still+ // match; anything that still differs falls back to the synthesised key for the ADDRESSED chat,+ // which is exactly what every id ran on before stored keys existed.+ const keyById = new Map(+ stored+ .filter(msg => msg.key?.id && msg.key.remoteJid && this.host.toEngineJid(msg.key.remoteJid) === remoteJid)+ .map(msg => [msg.key.id as string, msg.key]),+ );return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });}diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.tsindex b9e735399..ed7693951 100644--- a/src/engine/adapters/baileys-send-seen.spec.ts+++ b/src/engine/adapters/baileys-send-seen.spec.ts@@ -69,6 +69,48 @@ describe('sendSeen', () => {]);});+ it('never sends the receipt to another chat, even when the store resolves the id', async () => {+ // The stored key carries its own remoteJid. Used unchecked, an id belonging to a different chat+ // in the same session acknowledged THAT chat while the route answered success for the one the+ // caller named, and the caller's own chat stayed unread.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () =>+ Promise.resolve([stored({ id: 'X1', remoteJid: '[email protected]', fromMe: false })]),+ });++ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['X1'])).resolves.toBe(true);++ // Falls back to the synthesised key for the ADDRESSED chat rather than the stored one.+ expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'X1', fromMe: false }]);+ });++ it('still uses a stored key whose chat is spelled in the other dialect', async () => {+ // Control for the check above: the same chat written @c.us must still resolve, or the fix would+ // have cost every receipt its participant and fromMe.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () => Promise.resolve([stored({ id: 'D1', remoteJid: '[email protected]', fromMe: true })]),+ });++ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['D1'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([{ id: 'D1', remoteJid: '[email protected]', fromMe: true }]);+ });++ it('treats a null id list as absent rather than dereferencing it', async () => {+ // The REST body rejects an explicit null, but this is the engine boundary; it used to throw a+ // TypeError here and surface as a 500.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket });++ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', null as unknown as string[])).resolves.toBe(+ true,+ );+ expect(readMessages).toHaveBeenCalledWith([{ id: 'M1', remoteJid: '[email protected]' }]);+ });+it('carries the participant on a group receipt, which a synthesised key cannot', async () => {// A group receipt with no `participant` names no sender, so WhatsApp cannot attribute it and// the message stays unread on the sender's side while the API answers success: true.diff --git a/src/modules/session/dto/mark-chat-read.dto.spec.ts b/src/modules/session/dto/mark-chat-read.dto.spec.tsindex 24a88ff3f..7d65e11e9 100644--- a/src/modules/session/dto/mark-chat-read.dto.spec.ts+++ b/src/modules/session/dto/mark-chat-read.dto.spec.ts@@ -34,6 +34,12 @@ describe('MarkChatReadDto messageIds validation', () => {expect(messageIdErrors(['3EB0C767D26B8A3F1A2B', '3EB0C767D26B8A3F1A2C'])).toBe(0);});+ it('rejects an explicit null instead of letting it reach the engine', () => {+ // @IsOptional() skips every validator for null as well as undefined, so `"messageIds": null`+ // used to pass validation and then dereference in the adapter as a 500.+ expect(messageIdErrors(null)).toBeGreaterThan(0);+ });+it('rejects an empty list rather than reading it as "the newest message"', () => {// The engine treats a missing list as "acknowledge the newest message". A caller that computed// its unread set and got none back must not land in that branch.diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.tsindex e993de6fa..662b43e56 100644--- a/src/modules/session/dto/mark-chat-read.dto.ts+++ b/src/modules/session/dto/mark-chat-read.dto.ts@@ -1,5 +1,5 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { ArrayMaxSize, ArrayNotEmpty, IsArray, IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';+import { ArrayMaxSize, ArrayNotEmpty, IsArray, IsNotEmpty, IsString, Matches, ValidateIf } from 'class-validator';/*** Ceiling on one request's receipt batch, so a single call cannot hand the engine an unbounded key@@ -45,9 +45,15 @@ export class MarkChatReadDto {// this the published schema advertises an unbounded array and a caller batching more than the// cap discovers the limit as a 400.maxItems: MARK_READ_MESSAGE_IDS_MAX,+ // @ArrayNotEmpty rejects [], so the published schema has to say so too; without minItems the+ // contract advertised an empty array as valid against a server that answers 400.+ minItems: 1,example: ['3EB0C767D26B8A3F1A2B', '3EB0C767D26B8A3F1A2C'],})- @IsOptional()+ // Not @IsOptional: that skips every validator for null as well as undefined, so an explicit+ // `"messageIds": null` reached the engine unchecked and dereferenced there as a 500. Absent stays+ // absent; present-but-null falls through to @IsArray and answers 400.+ @ValidateIf((_object, value) => value !== undefined)@IsArray()// An empty array asks for nothing to be acknowledged. Rejected rather than accepted, because the// engine reads a missing list as "the newest message" and the two must not collapse: a caller that