Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Merge main into feat/message-receipt-event

Yudhi Armyndharis37980b80dcee
diff --cc CHANGELOG.md
index 90e2b73b6,65ee0c426..9247356b3
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,17 -7,52 +7,53 @@@ and this project adheres to [Semantic V
## [Unreleased]
+ ### Fixed
+
+ - Refuse media exports and file counts when local directories cannot be fully enumerated.
+
+ ## [0.25.0] - 2026-10-15
+
### Added
- - Filter stored messages by time, direction, type or message reference, with stable message-time pagination.
- - Expose poll choices and selection mode in message events, stored messages, history, and dashboard chats.
- - Expose optional last-message types in chat lists and SDKs.
- - Add bounded webhook failure redrive with optional payload retention.
- - Expose caller-supplied send idempotency keys in all five SDKs.
+ - Allow chat-restricted API keys to subscribe to chat WebSocket events.
+ - Allow chat-restricted MCP keys to read and send within their chat allowlist using the REST authorization rules.
+ - Carry `chatId` in `message.ack` and `message.failed` payloads so a webhook `chatId` or `kind` filter scopes delivery events per chat.
+ - Filter stored messages by time, direction, type or message reference, with stable message-time pagination; the JavaScript, Python, Java and Go SDKs take these filters from SDK 0.6.0, and the PHP SDK already forwards any query key.
+ - Scope built-in message search and group detail/settings to a chat-restricted key's allowed chats; reject plugin search for these keys.
+ - Expose poll choices and selection mode in message events, stored messages and history, and poll choices in dashboard chats; the SDKs type the poll of a live history message from SDK 0.6.0.
+ - Expose optional last-message types in chat lists and, from SDK 0.6.0, in the SDKs.
+ - Add bounded webhook failure redrive with optional payload retention; the SDKs expose it from SDK 0.6.0.
+ - Add `startupProbe.periodSeconds` and `startupProbe.failureThreshold` to the Helm chart's values, defaulting to the 5 s and 60 the chart rendered before, so a large messages table can be given a longer boot budget.
+ - Expose caller-supplied send idempotency keys in all five SDKs from SDK 0.6.0; the 0.5.1 JavaScript and PHP packages ignore the extra argument.
- Add optional 24-hour idempotency keys to twelve single-recipient send routes.
+- Add the opt-in `message.receipt` event for per-recipient group and status receipts on Baileys (#1748).
-
- Add opt-in archive-only chat media with dashboard previews.
+ - Report RSVPs to WhatsApp events as an `event.response` webhook and WebSocket event on Baileys; the JavaScript, Python, Go and Java SDKs list the event name from SDK 0.6.0 (#1788, thanks @jelasus).
+
+ ### Changed
+
+ - On PostgreSQL, inbound media that waits `2 x MEDIA_DOWNLOAD_TIMEOUT_MS` without a free slot arrives with the omitted marker instead of being downloaded.
+ - On PostgreSQL, a chat's messages are stored in arrival order, so a text waits for earlier media in its chat.
+ - On PostgreSQL with whatsapp-web.js, a held message's contact and quoted-message lookups wait at most `MEDIA_DOWNLOAD_TIMEOUT_MS`.
+ - The JavaScript SDK release job runs `npm audit` over the SDK tree before it installs, tests and publishes.
+ - The JavaScript SDK CommonJS build no longer sets `moduleResolution` node10, which TypeScript 7 removed; the built output is unchanged.
+ - JavaScript SDK CI and release jobs install with `--engine-strict` wherever they run the tests, so an unsupported Node fails at install.
+ - The JavaScript SDK smoke check sends requests through both built clients, so the Node 18 CI lane covers the request path.
+ - Retire the whatsapp-web.js download-mimetype install patch; inbound media downloads now pass the mimetype themselves.
+ - A whatsapp-web.js inbound media download the page answers with nothing logs a warning, and one WhatsApp Web rejects is logged with the rejection's name, message and WhatsApp Web build instead of the minified `t: t`.
+ - A status post the engine refuses is logged with its session and type, as a failed chat send already is.
+ - Storage import abort messages name the `STORAGE_IMPORT_MAX_BYTES` or `STORAGE_IMPORT_MAX_ENTRIES` setting that stopped them.
+ - CI and the weekly security scan run `npm audit` over the JavaScript SDK, and Dependabot watches its lockfile.
+ - The Baileys linked-device name defaults to `Ubuntu` instead of `OpenWA`, because some accounts reject a non-standard name on phone-number pairing (#1857, thanks @yoosufhaffejee; reported in #1471 and #1666, thanks @ImPabl0 and @Muhammad-Suban).
+ - The `/events` WebSocket echoes a `requestId` only when it is a string of at most 128 characters; any other value is dropped from the reply.
+ - A `/events` WebSocket `unsubscribe` whose `sessionId` is neither `*` nor a session id of at most 128 letters, digits and hyphens answers `INVALID_SESSION`, as `subscribe` does.
+ - The Baileys engine refuses SVG input to its image decoder, so a sticker, profile picture or group picture sent as an SVG answers `400` and an outbound image's thumbnail skips it; raster images convert as before.
+ - The ffmpeg runs of the gateway itself (media conversion and the voice note waveform) start with only `PATH`, `LD_LIBRARY_PATH`, `DYLD_LIBRARY_PATH`, `HOME`, `TMPDIR`, `TEMP`, `TMP`, `LANG`, `LC_ALL` and `SystemRoot` from the gateway's environment, so no secret reaches them or a wrapper script behind `FFMPEG_PATH`.
+ - The release workflow keeps its staging image when a gate fails on a good build, so a re-run of the failed jobs finds it; an abandoned release leaves one stray tag.
+ - The PHP SDK release runs its tests in a job without the mirror token, and a second job tags the mirror with git hooks disabled; the mirror workflow pushes with hooks disabled too.
+ - The JavaScript SDK release builds, tests and packs the tarball in a job without the publish credential, and a second job publishes that tarball; the Java SDK release runs its tests in a job without the Maven Central token and the signing key.
+ - The release workflow reads the version it extracts the release notes for from the environment instead of interpolating it into the script.
+ - Dependabot watches the Python, Java, PHP and Go SDK manifests.
### Fixed
diff --cc docs/03-system-architecture.md
index 45290ec50,e43ad560a..bed2f0baa
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@@ -917,16 -917,27 +917,28 @@@ export enum EngineStatus
export interface EngineEventCallbacks {
onQRCode?: (qr: string) => void;
onReady?: (phone: string, pushName: string) => void;
- onMessage?: (message: IncomingMessage) => void;
- onMessageCreate?: (message: IncomingMessage) => void; // outgoing (incl. linked-phone sends)
- onMessageAck?: (messageId: string, status: DeliveryStatus) => void;
+ admitInbound?: (arrival: {
+ id: string;
+ chatId: string;
+ needsRoom: boolean;
+ status: boolean;
+ fromMe?: boolean;
+ author?: string;
+ }) => InboundTicket | undefined; // PostgreSQL: reserves room for a download before the emit, and holds a change to the chat, direction and author it names
+ onMessage?: (message: IncomingMessage, ticket?: InboundTicket) => void | InboundReceipt; // the receipt reports { conflict: true } when the id already held another message; Baileys drops its copy
+ // A change aimed at that id that reads as foreign to the engine's copy waits for the receipt: up to 3 media download
+ // timeouts for a message still being processed, then 5 minutes for the session, at most 64 changes at once. A change
+ // that cannot wait, or is still waiting when the time runs out, is dropped.
+ onMessageCreate?: (message: IncomingMessage, ticket?: InboundTicket) => void; // outgoing (incl. linked-phone sends)
+ onMessageAck?: (messageId: string, status: DeliveryStatus, chatId?: string) => void;
+ onMessageReceipt?: (event: MessageReceiptEvent) => void; // per-recipient group/status receipts (Baileys only)
- onMessageRevoked?: (message: RevokedMessage) => void;
+ onMessageRevoked?: (message: RevokedMessage, actor?: { fromMe: boolean }) => void;
onMessageReaction?: (event: ReactionEvent) => void;
onMessageEdited?: (message: EditedMessage) => void;
+ onEventResponse?: (event: EventResponseEvent) => void; // an RSVP to a WhatsApp event; Baileys only
onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update / group.join_request
onCall?: (event: IncomingCallEvent) => void; // incoming call ringing; Baileys can rejectCall() while it rings
- onHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatch
+ onHistoryMessages?: (messages: IncomingMessage[]) => void | Promise<IncomingMessage[] | void>; // bulk initial sync; persist, don't dispatch
onDisconnected?: (reason: string) => void; // recoverable -> reconnect
onReconnecting?: (attempt: number, nextDelayMs: number) => void; // engines that retry internally (Baileys)
onStateChanged?: (state: EngineStatus) => void;
diff --cc docs/06-api-specification.md
index 28e7c4869,7251fc7f5..d0f8823c8
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@@ -4591,7 -4603,7 +4603,7 @@@ Webhooks are configured per session an
Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are never returned by any webhook route (the response DTO has no `@Expose` for them, so `fromEntity` drops them). `GET /api/infra/export-data` also omits both from its `webhooks` rows, so a backup no longer carries webhook credentials — a restored webhook comes back unsigned (`secret` null, `headers` `{}`) until you set them again. The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.
- The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.receipt`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `group.join_request`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Five are **Baileys only**, because whatsapp-web.js produces no callback behind them: `message.receipt` (whatsapp-web.js has no per-recipient receipt event), `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js has no call-outcome callback, so these three are accepted on subscribe and then simply never fire). `message.receipt` is also the one event a `*` subscription does **not** receive: it fires once per recipient, so it must be named explicitly. `call.received` is dispatched by both engines but is not reliable on whatsapp-web.js: it fired there in a live test on 2026-09-17 and did not in one on 2026-08-10. See the per-event catalog below for engine scope.
-The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `event.response`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `group.join_request`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Five are **Baileys only**, because whatsapp-web.js produces no callback behind them: `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself), `event.response` (accepted on subscribe and never fired) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js has no call-outcome callback, so these three are accepted on subscribe and then simply never fire). `call.received` is dispatched by both engines but is not reliable on whatsapp-web.js: it fired there in a live test on 2026-09-17 and did not in one on 2026-08-10. See the per-event catalog below for engine scope.
++The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.receipt`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `event.response`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `group.join_request`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Six are **Baileys only**, because whatsapp-web.js produces no callback behind them: `message.receipt` (whatsapp-web.js has no per-recipient receipt event), `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself), `event.response` (accepted on subscribe and never fired) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js has no call-outcome callback, so these three are accepted on subscribe and then simply never fire). `message.receipt` is the one event a `*` subscription does not receive: it fires once per recipient, so it must be named explicitly. `call.received` is dispatched by both engines but is not reliable on whatsapp-web.js: it fired there in a live test on 2026-09-17 and did not in one on 2026-08-10. See the per-event catalog below for engine scope.
#### GET /api/sessions/:sessionId/webhooks
@@@ -7140,7 -7161,8 +7162,8 @@@ A subscribe request whose `events` arra
### Wildcards and scoping
- - **`sessionId: "*"`** subscribes to every session; **`events: ["*"]`** subscribes to every subscribable event except `message.receipt`, whose per-recipient volume makes it opt-in by name. They combine (e.g. `"*"` + `["*"]` = every event of every session).
+ - **Chat-restricted keys receive only events for `allowedChats`.** Message, presence and `event.response` events require `data.chatId`; group events require `data.groupId`. Persisted phone/LID aliases are matched at delivery time, including mappings learned after subscribing. An event without a resolvable chat is omitted. Account events, calls, statuses, QR codes, and `group.join_request` (it names people outside the allowed chats, as the membership-request routes do) are omitted even with `events: ["*"]`; a request containing only account events answers `FORBIDDEN_EVENTS`. These filters apply across Redis replicas. A changed chat authorization disconnects the socket on its next subscribe.
-- **`sessionId: "*"`** subscribes to every session; **`events: ["*"]`** subscribes to every subscribable event. They combine (e.g. `"*"` + `["*"]` = every event of every session).
++- **`sessionId: "*"`** subscribes to every session; **`events: ["*"]`** subscribes to every subscribable event except `message.receipt`, whose per-recipient volume makes it opt-in by name. They combine (e.g. `"*"` + `["*"]` = every wildcard-covered event of every session).
- The API key is **re-validated on every `subscribe`** (not just at connect), so a key revoked or expired mid-connection is caught — the server replies `UNAUTHORIZED` and disconnects.
- **Per-key session scope is enforced** against the fresh key: a key restricted via `allowedSessions` may NOT subscribe to `"*"` and may NOT subscribe to a session outside its allowlist — either is rejected with `FORBIDDEN_SESSION`. An unrestricted key (no `allowedSessions`) may subscribe to anything, including `"*"`.
- **Live sockets are re-validated against the database once a minute**, with no client activity required. A socket carries the key as it stood when it connected, and rooms joined earlier are never revisited, so that snapshot is what the sweep compares against the current row, along with any later `subscribe` whose key no longer matched it (what that `subscribe` granted outlives the change, so putting the row back does not spare the socket). It closes the key's sockets with an `UNAUTHORIZED` frame naming the cause: `API key has been deleted`, `API key has been revoked`, `API key has expired`, or `API key authorization changed; please reconnect` when `role`, `allowedIps`, `allowedSessions`, `allowedChats` or `expiresAt` moved. A change made through this API still evicts synchronously in the same request; the sweep is what catches an expiry, a change written straight to this node's main database, or one committed in the instant a socket was connecting. API keys are per node (see [13 - Horizontal Scaling](./13-horizontal-scaling.md)), so a change made on another node never reaches this node's sockets; repeat it on every node. A rename, and the usage counters the gateway itself writes, evict nobody. Treat these frames as "reconnect and resubscribe", not as fatal.
@@@ -7192,34 -7214,36 +7215,37 @@@ Every registered webhook receives an HT
### Event catalog
-These are the events OpenWA actually emits. A webhook is registered with an `events` list; an event is delivered to a webhook when its `events` array includes the event name or `"*"`.
+These are the events OpenWA actually emits. A webhook is registered with an `events` list; an event is delivered to a webhook when its `events` array includes the event name or `"*"` (`"*"` excludes `message.receipt`, which is delivered only when named).
- | Event | When it fires | `data` payload sketch |
- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
- | `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `fromMe`, `chatId`, `media{mimetype,filename?,data?,omitted?,sizeBytes?}` (media messages only), `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one; **Baileys only**) |
- | `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` |
- | `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it |
- | `message.receipt` | One recipient receives, reads or plays a group or status message the account sent (**Baileys only**; not included in `*`) | `{ id, messageId, chatId, participant, status, timestamp }` — one event per recipient and status; `status` is `delivered`/`read`/`played`, `timestamp` is epoch **seconds**. Receipts from the account's own linked devices are not reported. On Baileys 7.0.0-rc14 a played voice note reports `read`. Nothing is stored and `message.ack` is not advanced by it |
- | `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |
- | `message.revoked` | A message is deleted/recalled | `{ id, revokedId?, chatId, from, to, type: "revoked", body: "", timestamp }` — **reconcile on `revokedId`** (the original deleted message's id), falling back to `id`. On whatsapp-web.js `id` is the _revocation notification_ (a distinct message that won't match a stored id) and `revokedId` may be absent when the original isn't cached locally; on Baileys the two coincide |
- | `message.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions? }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot, omitted when the gateway holds no stored copy of the message to compute it from (an ephemeral message, or one predating the session going live); treat it as unknown rather than empty and keep the map you already hold. `reaction` is empty when removed |
- | `message.edited` | A message body or media caption is edited | `{ messageId, chatId, body, senderId, from, to, fromMe, isGroup, type, hasMedia, author?, mentionedIds?, timestamp }` — `messageId` is the original message id, `body` is the latest text/caption, and `timestamp` is the edit occurrence time in epoch **seconds** (not the original creation time) |
- | `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` — `qr` is a **PNG data URL** (`data:image/png;base64,…`), the same rendered value `GET /api/sessions/{sessionId}/qr` returns as `qrCode`, not the raw `2@…` linking ref. Render it directly in an `<img src>`; the raw ref never leaves the engine adapter |
- | `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
- | `session.disconnected` | The session disconnects on the engine or WhatsApp side (drop, conflict, or a phone-initiated unlink). Not fired for API-initiated stop/logout/delete — those are acknowledged by the API response and the `session.status` transition | `{ sessionId, reason }` |
- | `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |
- | `presence.update` | A subscribed chat's presence changed — someone came online, started typing, or stopped. Only actual CHANGES are dispatched: WhatsApp repeats itself freely, and every repeat would otherwise be a delivery | `{ sessionId, chatId, participants: [{ id, state, lastSeen? }], groupOnlineCount? }` — `state` is `available`/`unavailable`/`composing`/`recording`/`paused`; `lastSeen` is epoch **seconds** and absent when the contact hides it. Requires `POST .../presence/subscribe` first, and Baileys — whatsapp-web.js cannot observe presence |
- | `session.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values |
- | `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` |
- | `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }`. `actorId` is the admin/inviter when known. **Baileys**: a session added to or joining a group reports only its own id in `participantIds` (members added with it are not listed) |
- | `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` |
- | `group.update` | Group metadata changes (subject, description, announce/locked settings) | `{ groupId, actorId?, participantIds, changes?, timestamp }` — `changes` carries only the fields that changed: `subject?`, `description?`, `announce?`, `locked?` |
- | `group.join_request` | Someone asked to join a group this session administers (join-approval mode on) | `{ groupId, actorId?, participantIds, timestamp }` — `participantIds` are the users asking to join; `actorId` is who created the request when the engine reports one (differs from the requester on a non-admin add). Act on it via `GET/POST .../groups/:groupId/membership-requests[...]` **Baileys caveat**: the library (7.0.0-rc14) emits this only for non-admin-add requests — an invite-link self-request may produce no event there (upstream TODO); the membership-requests list endpoint still reports it. |
- | `call.received` | An incoming voice/video call starts ringing. Dispatched by both engines, but **not reliable on whatsapp-web.js**: it fired in a live test on 2026-09-17 and did not in one on 2026-08-10 | `{ callId, from, isVideo, isGroup, timestamp }` — `callId` is the id to pass to `POST /sessions/:sessionId/calls/:callId/reject` (Baileys only). `from` may be an `@lid` privacy id on either engine; resolve it with `GET /api/sessions/:sessionId/contacts/:contactId/phone` |
- | `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended, whether answered, declined, or never picked up. **Baileys only**: whatsapp-web.js emits no call-outcome event | `{ sessionId, callId, from, outcome, isVideo, isGroup, timestamp }`. `callId` matches the `call.received` that preceded it, so the pair can be correlated. The engines report _what_ happened, never _who_ did it: an accept can come from any linked device. An outcome is only sent for a call this session saw ring, and offline-replayed signalling for calls that ended while disconnected is dropped. WhatsApp's `terminate` is deliberately unmapped: it covers both a caller hanging up before answer and either side ending an answered call, with nothing to tell them apart |
- | `status.received` | A contact posts a status/story (opt-in — see below) | `{ sessionId, statusId, contact: { id, name?, pushName? }, type, caption?, hasMedia, mediaOmitted, omitReason?, postedAt, expiresAt }` — `statusId` is the store's `id` (usable with the status endpoints below); `postedAt`/`expiresAt` are epoch **milliseconds** (unlike the epoch-seconds convention for message timestamps), matching the `GET /status` store's own `Date`-backed fields |
-
- > **`status.received` is opt-in and carries no media blob.** Unlike every other event above, `status.received` is only delivered to a webhook whose `events` list explicitly includes `"status.received"` (or `"*"`) — registering for other events does not implicitly subscribe you to it. The payload never embeds media bytes: when `hasMedia` is `true`, fetch the file separately via `GET /api/sessions/:sessionId/status/:statusId/media`. Your own posted statuses never trigger this event — only inbound stories from contacts (an own-send echo is dropped before ingest).
+ | Event | When it fires | `data` payload sketch |
+ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+ | `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `fromMe`, `chatId`, `media{mimetype,filename?,data?,omitted?,sizeBytes?}` (media messages only), `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, and `poll{name,options,allowMultipleAnswers}` on a poll creation message; on Baileys also `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one) |
+ | `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` |
-| `message.ack` | A delivery/read receipt updates an outbound message. On Baileys only 1:1 receipts arrive: it reports group and status receipts per participant, which are not consumed, so an own group or status message stays at `sent`, see below | `{ id, messageId, status, ack, chatId? }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it; `chatId` is the conversation the acked message belongs to, present whenever the engine's update names the chat (both engines do on the live path) |
++| `message.ack` | A delivery/read receipt updates an outbound message. On Baileys only 1:1 receipts advance it; opt-in `message.receipt` reports group and status receipts per participant and leaves the message at `sent`, see below | `{ id, messageId, status, ack, chatId? }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it; `chatId` is the conversation the acked message belongs to, present whenever the engine's update names the chat (both engines do on the live path) |
++| `message.receipt` | One recipient receives, reads or plays a group or status message the account sent (**Baileys only**; not included in `*`) | `{ id, messageId, chatId, participant, status, timestamp }` ; one event per recipient and status; `status` is `delivered`/`read`/`played`, `timestamp` is epoch **seconds**. Receipts from the account's own linked devices are not reported. On Baileys 7.0.0-rc14 a played voice note reports `read`. Nothing is stored and `message.ack` is not advanced by it |
+ | `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1, chatId? }`; `chatId` follows the same rules as `message.ack` |
+ | `message.revoked` | A message is deleted/recalled | `{ id, revokedId?, chatId, from, to, type: "revoked", body: "", timestamp }` — **reconcile on `revokedId`** (the original deleted message's id), falling back to `id`. On whatsapp-web.js `id` is the _revocation notification_ (a distinct message that won't match a stored id) and `revokedId` may be absent when the original isn't cached locally; on Baileys the two coincide |
+ | `message.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions? }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot, omitted when the gateway holds no stored copy of the message to compute it from (an ephemeral message, or one predating the session going live); treat it as unknown rather than empty and keep the map you already hold. `reaction` is empty when removed |
+ | `message.edited` | A message body or media caption is edited | `{ messageId, chatId, body, senderId, from, to, fromMe, isGroup, type, hasMedia, author?, mentionedIds?, timestamp }` — `messageId` is the original message id, `body` is the latest text/caption, and `timestamp` is the edit occurrence time in epoch **seconds** (not the original creation time) |
+ | `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` — `qr` is a **PNG data URL** (`data:image/png;base64,…`), the same rendered value `GET /api/sessions/{sessionId}/qr` returns as `qrCode`, not the raw `2@…` linking ref. Render it directly in an `<img src>`; the raw ref never leaves the engine adapter |
+ | `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
+ | `session.disconnected` | The session disconnects on the engine or WhatsApp side (drop, conflict, or a phone-initiated unlink). Not fired for API-initiated stop/logout/delete — those are acknowledged by the API response and the `session.status` transition | `{ sessionId, reason }` |
+ | `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |
+ | `presence.update` | A subscribed chat's presence changed — someone came online, started typing, or stopped. Only actual CHANGES are dispatched: WhatsApp repeats itself freely, and every repeat would otherwise be a delivery | `{ sessionId, chatId, participants: [{ id, state, lastSeen? }], groupOnlineCount? }` — `state` is `available`/`unavailable`/`composing`/`recording`/`paused`; `lastSeen` is epoch **seconds** and absent when the contact hides it. Requires `POST .../presence/subscribe` first, and Baileys — whatsapp-web.js cannot observe presence |
+ | `event.response` | A guest answered a WhatsApp event invitation (going, not going, maybe). **Baileys only**; see the payload note below | `{ sessionId, eventMessageId, chatId, responderId, contact?, fromMe, response, extraGuestCount?, eventName?, responseMessageId, timestamp }`. `response` is `going`/`not_going`/`maybe`/`unknown`; `timestamp` is epoch **seconds** on the guest's clock. Order a guest's answers by `timestamp`, not by delivery |
+ | `session.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values |
+ | `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` |
+ | `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }`. `actorId` is the admin/inviter when known. **Baileys**: a session added to or joining a group reports only its own id in `participantIds` (members added with it are not listed) |
+ | `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` |
+ | `group.update` | Group metadata changes (subject, description, announce/locked settings) | `{ groupId, actorId?, participantIds, changes?, timestamp }` — `changes` carries only the fields that changed: `subject?`, `description?`, `announce?`, `locked?` |
+ | `group.join_request` | Someone asked to join a group this session administers (join-approval mode on) | `{ groupId, actorId?, participantIds, timestamp }` — `participantIds` are the users asking to join; `actorId` is who created the request when the engine reports one (differs from the requester on a non-admin add). Act on it via `GET/POST .../groups/:groupId/membership-requests[...]` **Baileys caveat**: the library (7.0.0-rc14) emits this only for non-admin-add requests — an invite-link self-request may produce no event there (upstream TODO); the membership-requests list endpoint still reports it. |
+ | `call.received` | An incoming voice/video call starts ringing. Dispatched by both engines, but **not reliable on whatsapp-web.js**: it fired in a live test on 2026-09-17 and did not in one on 2026-08-10 | `{ callId, from, isVideo, isGroup, timestamp }` — `callId` is the id to pass to `POST /sessions/:sessionId/calls/:callId/reject` (Baileys only). `from` may be an `@lid` privacy id on either engine; resolve it with `GET /api/sessions/:sessionId/contacts/:contactId/phone` |
+ | `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended, whether answered, declined, or never picked up. **Baileys only**: whatsapp-web.js emits no call-outcome event | `{ sessionId, callId, from, outcome, isVideo, isGroup, timestamp }`. `callId` matches the `call.received` that preceded it, so the pair can be correlated. The engines report _what_ happened, never _who_ did it: an accept can come from any linked device. An outcome is only sent for a call this session saw ring, and offline-replayed signalling for calls that ended while disconnected is dropped. WhatsApp's `terminate` is deliberately unmapped: it covers both a caller hanging up before answer and either side ending an answered call, with nothing to tell them apart |
+ | `status.received` | A contact posts a status/story (opt-in — see below) | `{ sessionId, statusId, contact: { id, name?, pushName? }, type, caption?, hasMedia, mediaOmitted, omitReason?, postedAt, expiresAt }` — `statusId` is the store's `id` (usable with the status endpoints below); `postedAt`/`expiresAt` are epoch **milliseconds** (unlike the epoch-seconds convention for message timestamps), matching the `GET /status` store's own `Date`-backed fields |
+
+ > **`message.ack` on Baileys.** An own group or status message stays at `sent` unless the server rejects it, which still arrives as `failed`. The event is not limited to outbound messages: when the account's own phone reads a 1:1 chat, the messages received there are acked as `read` too, with no `fromMe` in the payload, and their stored copy moves to `read`.
+
-> **`status.received` is opt-in and carries no media blob.** Unlike every other event above, `status.received` is only delivered to a webhook whose `events` list explicitly includes `"status.received"` (or `"*"`) — registering for other events does not implicitly subscribe you to it. The payload never embeds media bytes: when `hasMedia` is `true`, fetch the file separately via `GET /api/sessions/:sessionId/status/:statusId/media`. Your own posted statuses never trigger this event — only inbound stories from contacts (an own-send echo is dropped before ingest).
++> **`status.received` is opt-in and carries no media blob.** `status.received` is only delivered to a webhook whose `events` list explicitly includes `"status.received"` (or `"*"`) — registering for other events does not implicitly subscribe you to it. The payload never embeds media bytes: when `hasMedia` is `true`, fetch the file separately via `GET /api/sessions/:sessionId/status/:statusId/media`. Your own posted statuses never trigger this event — only inbound stories from contacts (an own-send echo is dropped before ingest).
> **`STORE_EPHEMERAL_MESSAGES=false` affects `message.received`.** When `STORE_EPHEMERAL_MESSAGES` is set to `false`, incoming disappearing messages (those with `ephemeralDuration > 0`) are **not** persisted nor dispatched — no DB insert, no webhook delivery, and no websocket event. Downstream consumers and the dashboard both stop seeing them. Default is `true` (backward compatible — store and dispatch everything).
diff --cc sdk/python/openwa/types.py
index 4dd87e2be,74864095b..fc3c5a0b3
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@@ -65,20 -65,20 +65,20 @@@ MessageType = Literal
"unknown",
]
WebhookEvent = Literal[
- "message.received", "message.sent", "message.ack", "message.failed", "message.revoked",
+ "message.received", "message.sent", "message.ack", "message.receipt", "message.failed", "message.revoked",
"message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",
"session.disconnected", "session.reconnect_loop", "session.restriction", "presence.update",
- "group.join", "group.leave", "group.update", "group.join_request",
+ "event.response", "group.join", "group.leave", "group.update", "group.join_request",
"call.received", "status.received",
"call.accepted", "call.rejected", "call.missed",
"*",
]
# The events a delivery can carry: WebhookEvent without the "*" subscription wildcard.
WebhookDeliveryEvent = Literal[
- "message.received", "message.sent", "message.ack", "message.failed", "message.revoked",
+ "message.received", "message.sent", "message.ack", "message.receipt", "message.failed", "message.revoked",
"message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",
"session.disconnected", "session.reconnect_loop", "session.restriction", "presence.update",
- "group.join", "group.leave", "group.update", "group.join_request",
+ "event.response", "group.join", "group.leave", "group.update", "group.join_request",
"call.received", "status.received",
"call.accepted", "call.rejected", "call.missed",
]
diff --cc src/engine/adapters/baileys-events.spec.ts
index c1a4bc96f,e872d9205..5c91f46b6
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@@ -3,7 -4,7 +4,7 @@@ import { createLogger } from '../../com
import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
import { inboundMediaConcurrency } from './inbound-media-cap';
import type { WAMessage, WASocket } from '@whiskeysockets/baileys';
- import type { MessageReceiptEvent } from '../interfaces/whatsapp-engine.interface';
-import type { Contact, EventResponseEvent } from '../interfaces/whatsapp-engine.interface';
++import type { Contact, EventResponseEvent, MessageReceiptEvent } from '../interfaces/whatsapp-engine.interface';
/**
* `downloadMediaMessage` is a jest mock, not a silent no-op: the real-download branch
@@@ -118,8 -120,9 +120,10 @@@ function makeHost(overrides: Partial<Ba
getOnMessageEdited: () => undefined,
getOnMessageReaction: () => undefined,
getOnMessageAck: () => undefined,
+ getOnMessageReceipt: () => undefined,
getOnGroupEvent: () => undefined,
+ getOnEventResponse: () => undefined,
+ findContact: () => null,
getOnCall: () => undefined,
getOnPresenceUpdate: () => undefined,
getOnCallOutcome: () => undefined,
@@@ -633,80 -636,896 +637,974 @@@ describe('BaileysEvents record of messa
});
});
+describe('BaileysEvents.handleMessageReceiptUpdate', () => {
+ const group = '[email protected]';
+ const member = '[email protected]';
+
+ function setup(overrides: Partial<BaileysEventsHost> = {}) {
+ const onMessageReceipt = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnMessageReceipt: () => onMessageReceipt, ...overrides }));
+ return { events, onMessageReceipt };
+ }
+
+ it('reports one event per recipient receipt of a message the account sent', () => {
+ const { events, onMessageReceipt } = setup();
+ events.handleMessageReceiptUpdate([
+ {
+ key: { id: 'OUT1', remoteJid: group, fromMe: true },
+ receipt: { userJid: member, receiptTimestamp: 1700000000 },
+ },
+ { key: { id: 'OUT1', remoteJid: group, fromMe: true }, receipt: { userJid: member, readTimestamp: 1700000060 } },
+ ]);
+ expect(onMessageReceipt.mock.calls).toEqual([
+ [{ messageId: 'OUT1', chatId: group, participant: member, status: 'delivered', timestamp: 1700000000 }],
+ [{ messageId: 'OUT1', chatId: group, participant: member, status: 'read', timestamp: 1700000060 }],
+ ]);
+ });
+
+ it('splits a buffered entry that carries several timestamps into one event per status', () => {
+ const { events, onMessageReceipt } = setup();
+ events.handleMessageReceiptUpdate([
+ {
+ key: { id: 'OUT1', remoteJid: group, fromMe: true },
+ receipt: { userJid: member, receiptTimestamp: 1, readTimestamp: 2, playedTimestamp: 3 },
+ },
+ ]);
+ const calls = onMessageReceipt.mock.calls as Array<[MessageReceiptEvent]>;
+ expect(calls.map(([e]) => [e.status, e.timestamp])).toEqual([
+ ['delivered', 1],
+ ['read', 2],
+ ['played', 3],
+ ]);
+ });
+
+ it("drops receipts from the account's own devices, in either dialect", () => {
+ const { events, onMessageReceipt } = setup({
+ getSocketOrNull: () =>
+ ({ user: { id: '6280000000000:[email protected]', lid: '99999@lid' } }) as unknown as WASocket,
+ });
+ events.handleMessageReceiptUpdate([
+ {
+ key: { id: 'OUT1', remoteJid: group, fromMe: true },
+ receipt: { userJid: '[email protected]', readTimestamp: 1 },
+ },
+ { key: { id: 'OUT1', remoteJid: group, fromMe: true }, receipt: { userJid: '99999@lid', readTimestamp: 1 } },
+ ]);
+ expect(onMessageReceipt).not.toHaveBeenCalled();
+ });
+
+ it('ignores receipts for messages the account did not send, and malformed entries', () => {
+ const { events, onMessageReceipt } = setup();
+ events.handleMessageReceiptUpdate([
+ { key: { id: 'IN1', remoteJid: group, fromMe: false }, receipt: { userJid: member, readTimestamp: 1 } },
+ { key: { remoteJid: group, fromMe: true }, receipt: { userJid: member, readTimestamp: 1 } },
+ { key: { id: 'OUT1', remoteJid: group, fromMe: true }, receipt: { readTimestamp: 1 } },
+ { key: { id: 'OUT1', remoteJid: group, fromMe: true }, receipt: { userJid: member } },
+ ]);
+ expect(onMessageReceipt).not.toHaveBeenCalled();
+ });
+
+ it('neutralises the chat and participant ids', () => {
+ const { events, onMessageReceipt } = setup({ toNeutralJid: (jid: string) => `n:${jid}` });
+ events.handleMessageReceiptUpdate([
+ { key: { id: 'OUT1', remoteJid: group, fromMe: true }, receipt: { userJid: '55555@lid', readTimestamp: 1 } },
+ ]);
+ expect(onMessageReceipt).toHaveBeenCalledWith(
+ expect.objectContaining({ chatId: `n:${group}`, participant: 'n:55555@lid' }),
+ );
+ });
+});
++
+ describe('BaileysEvents record of conflicting copies removed', () => {
+ it('forgets the id removed longest ago once it holds its limit', async () => {
+ const limit = BaileysEvents.DELETED_FOR_EVERYONE_LIMIT;
+ const settled = Promise.resolve({ conflict: true });
+ const events = new BaileysEvents(makeHost({ getOnMessage: () => () => ({ settled }) }));
+ const deliver = async (...ids: string[]): Promise<void> => {
+ events.handleMessagesUpsert({
+ type: 'notify',
+ messages: ids.map(id => ({
+ key: { id, remoteJid: '[email protected]', fromMe: false },
+ messageTimestamp: 1_700_000_000,
+ message: { conversation: 'hi' },
+ })),
+ });
+ for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve));
+ };
+ const removals = (events as unknown as { copyRemovals: Map<string, number> }).copyRemovals;
+
+ await deliver(...Array.from({ length: limit }, (_, i) => `M${i}`));
+ expect(removals.size).toBe(limit);
+ // M0 is removed again, which makes it the newest, and one more id pushes the oldest out.
+ await deliver('M0');
+ await deliver('EXTRA');
+
+ expect(removals.size).toBe(limit);
+ expect(removals.get('M0')).toBe(2);
+ expect(removals.has('M1')).toBe(false);
+ expect(removals.get('EXTRA')).toBe(1);
+ });
+ });
+
+ describe('BaileysEvents live keys of a 1:1 chat', () => {
+ // Baileys runs every live key through cleanMessage, which leaves '' where a 1:1 key has no participant.
+ const partner = '[email protected]';
+ const self = '[email protected]';
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ it.each([
+ ['the chat partner', false, partner],
+ ['the account', true, self],
+ ])('names %s as the reactor of a reaction whose participant is empty', async (_who, fromMe, expected) => {
+ const onMessageReaction = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnMessageReaction: () => onMessageReaction }));
+
+ events.handleMessagesUpsert({
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'R1', remoteJid: partner, fromMe, participant: '' },
+ messageTimestamp: 1_700_000_000,
+ message: { reactionMessage: { key: { id: 'M1', remoteJid: partner }, text: '👍' } },
+ },
+ ],
+ });
+ for (let i = 0; i < 5; i++) await flush();
+
+ expect(onMessageReaction).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'M1', senderId: expected }));
+ });
+
+ it('flags a sender known only by lid when the participant is empty', async () => {
+ const events = new BaileysEvents(makeHost());
+
+ const incoming = await events.mapMessage(
+ {
+ key: { id: 'L1', remoteJid: '111222333@lid', fromMe: false, participant: '' },
+ messageTimestamp: 1_700_000_000,
+ message: { conversation: 'hi' },
+ },
+ 'conversation',
+ );
+
+ expect(incoming.isLidSender).toBe(true);
+ });
+
+ it.each([
+ ['the guest', false, partner],
+ ['the account', true, self],
+ ])('reports an answer from %s whose RSVP key has an empty participant', async (_who, fromMe, expected) => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse }));
+
+ events.handleMessagesUpdate([
+ {
+ key: { id: 'EVT9', remoteJid: self },
+ update: {
+ eventResponses: [
+ {
+ eventResponseMessageKey: { id: 'RSVP9', remoteJid: partner, fromMe, participant: '' },
+ senderTimestampMs: 1786000000123,
+ response: { response: 1 },
+ },
+ ],
+ },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ responderId: expected, fromMe }));
+ });
+ });
+
+ describe('BaileysEvents event RSVPs (event.response)', () => {
+ const group = '[email protected]';
+ const eventKey = { id: 'EVT1', remoteJid: group };
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ function rsvp(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ eventResponseMessageKey: {
+ id: 'RSVP1',
+ remoteJid: group,
+ participant: '[email protected]',
+ fromMe: false,
+ },
+ senderTimestampMs: 1786000000123,
+ response: { response: 1, timestampMs: 1786000000123, extraGuestCount: 2 },
+ ...overrides,
+ };
+ }
+
+ it('reports a decrypted RSVP with the event name read from the stored creation message', async () => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(
+ makeHost({
+ getOnEventResponse: () => onEventResponse,
+ getStoredMessage: () =>
+ Promise.resolve({ key: eventKey, message: { eventMessage: { name: 'Game night' } } } as unknown as WAMessage),
+ }),
+ );
+
+ events.handleMessagesUpdate([{ key: eventKey, update: { eventResponses: [rsvp()] } }] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledTimes(1);
+ expect(onEventResponse).toHaveBeenCalledWith({
+ eventMessageId: 'EVT1',
+ chatId: group,
+ responderId: '[email protected]',
+ fromMe: false,
+ response: 'going',
+ extraGuestCount: 2,
+ eventName: 'Game night',
+ responseMessageId: 'RSVP1',
+ timestamp: 1786000000,
+ });
+ });
+
+ it.each([
+ [2, 'not_going'],
+ [3, 'maybe'],
+ [0, 'unknown'],
+ [undefined, 'unknown'],
+ ])('maps response type %p to %p', async (type, expected) => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse }));
+
+ events.handleMessagesUpdate([
+ { key: eventKey, update: { eventResponses: [rsvp({ response: { response: type } })] } },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ response: expected }));
+ expect((onEventResponse.mock.calls as unknown[][])[0][0]).not.toHaveProperty('extraGuestCount');
+ });
+
+ it("attributes the account's own 1:1 answer to the account", async () => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse }));
+ const chat = '[email protected]';
+
+ events.handleMessagesUpdate([
+ {
+ key: { id: 'EVT2', remoteJid: chat },
+ update: { eventResponses: [rsvp({ eventResponseMessageKey: { id: 'RSVP2', remoteJid: chat, fromMe: true } })] },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(
+ expect.objectContaining({ chatId: chat, responderId: '[email protected]', fromMe: true }),
+ );
+ });
+
+ it("takes a guest's 1:1 answer to the account's own event from the RSVP, not the guest's view of the event", async () => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse }));
+ const guest = '[email protected]';
+
+ // Baileys passes the creation key on as the guest sent it: its remoteJid is this account.
+ events.handleMessagesUpdate([
+ {
+ key: { id: 'EVT3', remoteJid: '[email protected]', fromMe: false },
+ update: {
+ eventResponses: [rsvp({ eventResponseMessageKey: { id: 'RSVP3', remoteJid: guest, fromMe: false } })],
+ },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(
+ expect.objectContaining({ eventMessageId: 'EVT3', chatId: guest, responderId: guest, fromMe: false }),
+ );
+ });
+
+ it("names the responder from the session's contact store", async () => {
+ const onEventResponse = jest.fn();
+ const findContact = jest.fn((id: string) =>
+ id === '[email protected]' ? ({ id, name: 'Ana Pérez', pushName: 'Ana' } as Contact) : null,
+ );
+ const events = new BaileysEvents(makeHost({ getOnEventResponse: () => onEventResponse, findContact }));
+
+ events.handleMessagesUpdate([
+ { key: eventKey, update: { eventResponses: [rsvp()] } },
+ {
+ key: eventKey,
+ update: {
+ eventResponses: [
+ rsvp({ eventResponseMessageKey: { id: 'RSVP4', remoteJid: group, participant: '[email protected]' } }),
+ ],
+ },
+ },
+ ] as never);
+ await flush();
+
+ const byId = (id: string) =>
+ (onEventResponse.mock.calls as EventResponseEvent[][]).map(([e]) => e).find(e => e.responseMessageId === id);
+ expect(byId('RSVP1')?.contact).toEqual({ name: 'Ana Pérez', pushName: 'Ana' });
+ expect(byId('RSVP4')).not.toHaveProperty('contact');
+ });
+
+ it('still reports the RSVP, without a name, when the store cannot be read', async () => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(
+ makeHost({
+ getOnEventResponse: () => onEventResponse,
+ getStoredMessage: () => Promise.reject(new Error('database is locked')),
+ }),
+ );
+
+ events.handleMessagesUpdate([{ key: eventKey, update: { eventResponses: [rsvp()] } }] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledTimes(1);
+ expect((onEventResponse.mock.calls as unknown[][])[0][0]).not.toHaveProperty('eventName');
+ });
+
+ it('keeps reporting acks next to RSVPs, and ignores an RSVP without its own key', async () => {
+ const onEventResponse = jest.fn();
+ const onMessageAck = jest.fn();
+ const events = new BaileysEvents(
+ makeHost({ getOnEventResponse: () => onEventResponse, getOnMessageAck: () => onMessageAck }),
+ );
+
+ events.handleMessagesUpdate([
+ { key: eventKey, update: { status: 3, eventResponses: [rsvp({ eventResponseMessageKey: null })] } },
+ ] as never);
+ await flush();
+
+ expect(onMessageAck).toHaveBeenCalledTimes(1);
+ expect(onEventResponse).not.toHaveBeenCalled();
+ });
+
+ describe('which chat an RSVP may answer for', () => {
+ const otherGroup = '[email protected]';
+ const storedIn =
+ (remoteJid: string, extra: Record<string, unknown> = {}) =>
+ () =>
+ Promise.resolve({
+ key: { id: 'EVT1', remoteJid, fromMe: false, ...extra },
+ message: { eventMessage: { name: 'Game night' } },
+ } as unknown as WAMessage);
+
+ it("drops an RSVP sent in another chat than its event's, which Baileys decrypts without comparing chats", async () => {
+ const onEventResponse = jest.fn();
+ const logger = createLogger('BaileysEventsSpec');
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ const events = new BaileysEvents(
+ makeHost({ getOnEventResponse: () => onEventResponse, getStoredMessage: storedIn(otherGroup), logger }),
+ );
+
+ // The event lives in otherGroup; the default RSVP envelope arrived in `group`.
+ events.handleMessagesUpdate([
+ { key: { id: 'EVT1', remoteJid: otherGroup }, update: { eventResponses: [rsvp()] } },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).not.toHaveBeenCalled();
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an RSVP whose stored event sits in the chat the answer arrived in', async () => {
+ const onEventResponse = jest.fn();
+ const events = new BaileysEvents(
+ makeHost({ getOnEventResponse: () => onEventResponse, getStoredMessage: storedIn(group) }),
+ );
+
+ events.handleMessagesUpdate([{ key: eventKey, update: { eventResponses: [rsvp()] } }] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ chatId: group, eventName: 'Game night' }));
+ });
+
+ it("reports a guest's 1:1 answer to the account's own event, kept in the guest's chat", async () => {
+ const onEventResponse = jest.fn();
+ const guest = '[email protected]';
+ const events = new BaileysEvents(
+ makeHost({ getOnEventResponse: () => onEventResponse, getStoredMessage: storedIn(guest, { fromMe: true }) }),
+ );
+
+ events.handleMessagesUpdate([
+ {
+ key: { id: 'EVT1', remoteJid: '[email protected]', fromMe: false },
+ update: {
+ eventResponses: [rsvp({ eventResponseMessageKey: { id: 'RSVP6', remoteJid: guest, fromMe: false } })],
+ },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ chatId: guest, responderId: guest }));
+ });
+
+ it("compares a lid chat with its phone number once the key's pair is known", async () => {
+ const onEventResponse = jest.fn();
+ const lid = '99887766@lid';
+ const phone = '[email protected]';
+ let paired = false;
+ const events = new BaileysEvents(
+ makeHost({
+ getOnEventResponse: () => onEventResponse,
+ getStoredMessage: storedIn(phone, { fromMe: true }),
+ recordKeyLidMappings: () => {
+ paired = true;
+ },
+ toNeutralJid: jid => (paired && jid === lid ? phone : jid),
+ }),
+ );
+
+ events.handleMessagesUpdate([
+ {
+ key: { id: 'EVT1', remoteJid: '[email protected]', fromMe: false },
+ update: {
+ eventResponses: [
+ rsvp({ eventResponseMessageKey: { id: 'RSVP7', remoteJid: lid, remoteJidAlt: phone, fromMe: false } }),
+ ],
+ },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ chatId: phone, responderId: phone }));
+ });
+ });
+
+ it("learns the RSVP key's lid and phone pair before naming the responder", async () => {
+ const onEventResponse = jest.fn();
+ const lid = '99887766@lid';
+ const phone = '[email protected]';
+ let paired = false;
+ const events = new BaileysEvents(
+ makeHost({
+ getOnEventResponse: () => onEventResponse,
+ recordKeyLidMappings: () => {
+ paired = true;
+ },
+ toNeutralJid: jid => (paired && jid === lid ? phone : jid),
+ }),
+ );
+
+ events.handleMessagesUpdate([
+ {
+ key: eventKey,
+ update: {
+ eventResponses: [
+ rsvp({
+ eventResponseMessageKey: { id: 'RSVP8', remoteJid: group, participant: lid, participantAlt: phone },
+ }),
+ ],
+ },
+ },
+ ] as never);
+ await flush();
+
+ expect(onEventResponse).toHaveBeenCalledWith(expect.objectContaining({ responderId: phone }));
+ });
+ });
+
+ /**
+ * WhatsApp sends a contact's edit, and a reaction in some chats, encrypted under the secret of the message
+ * it changes. These tests seal their payloads with the library's own key construction (see
+ * baileys-secret-payload.spec.ts) and let the stub's protobuf decode read JSON, which is the only part
+ * the real library supplies.
+ */
+ describe('BaileysEvents encrypted edits and reactions', () => {
+ const group = '[email protected]';
+ const author = '39900313301142@lid';
+ const reactor = '195700218425410@lid';
+ const secret = Buffer.alloc(32, 0x42);
+ const flush = async (): Promise<void> => {
+ for (let i = 0; i < 6; i++) await new Promise(resolve => setImmediate(resolve));
+ };
+
+ const protoStub = {
+ Message: {
+ SecretEncryptedMessage: { SecretEncType: { UNKNOWN: 0, EVENT_EDIT: 1, MESSAGE_EDIT: 2 } },
+ ProtocolMessage: { Type: { REVOKE: 0, MESSAGE_EDIT: 14 } },
+ decode: (bytes: Uint8Array): unknown => JSON.parse(Buffer.from(bytes).toString()),
+ ReactionMessage: { decode: (bytes: Uint8Array): unknown => JSON.parse(Buffer.from(bytes).toString()) },
+ },
+ };
+ const lib = { ...libStub, proto: protoStub } as unknown as Awaited<ReturnType<BaileysEventsHost['loadLib']>>;
+
+ function seal(
+ label: 'Message Edit' | 'Enc Reaction',
+ ids: { target: string; author: string; modifier: string },
+ plain: object,
+ withSecret: Buffer = secret,
+ ): { encPayload: Buffer; encIv: Buffer } {
+ const prk = createHmac('sha256', Buffer.alloc(32)).update(withSecret).digest();
+ const info = Buffer.from(`${ids.target}${ids.author}${ids.modifier}${label}`);
+ const key = createHmac('sha256', prk)
+ .update(Buffer.concat([info, Buffer.from([1])]))
+ .digest();
+ const iv = Buffer.alloc(12, 5);
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
+ const body = Buffer.concat([
+ cipher.update(Buffer.from(JSON.stringify(plain))),
+ cipher.final(),
+ cipher.getAuthTag(),
+ ]);
+ return { encPayload: body, encIv: iv };
+ }
+
+ const original = (overrides: Record<string, unknown> = {}): WAMessage =>
+ ({
+ key: { id: 'ORIG1', remoteJid: group, participant: author, fromMe: false },
+ messageTimestamp: 1_786_000_000,
+ message: { conversation: 'old text', messageContextInfo: { messageSecret: secret.toString('base64') } },
+ ...overrides,
+ }) as unknown as WAMessage;
+
+ const editPlain = {
+ protocolMessage: {
+ type: 14,
+ key: { id: 'ORIG1' },
+ editedMessage: { conversation: 'new text' },
+ timestampMs: 1786000000123,
+ },
+ };
+
+ function editEnvelope(
+ overrides: {
+ participant?: string;
+ fromMe?: boolean;
+ sealed?: object;
+ type?: unknown;
+ target?: string;
+ remoteJid?: string;
+ } = {},
+ ): WAMessage {
+ const participant = overrides.participant ?? author;
+ const sealed =
+ overrides.sealed ?? seal('Message Edit', { target: 'ORIG1', author, modifier: participant }, editPlain);
+ return {
+ key: { id: 'ENV1', remoteJid: overrides.remoteJid ?? group, participant, fromMe: overrides.fromMe ?? false },
+ messageTimestamp: 1_786_000_100,
+ message: {
+ secretEncryptedMessage: {
+ targetMessageKey: { id: overrides.target ?? 'ORIG1', remoteJid: group, fromMe: true },
+ ...sealed,
+ secretEncType: overrides.type ?? 2,
+ },
+ },
+ } as unknown as WAMessage;
+ }
+
+ function reactionEnvelope(text: string, overrides: { remoteJid?: string; sealed?: object } = {}): WAMessage {
+ const sealed =
+ overrides.sealed ??
+ seal('Enc Reaction', { target: 'ORIG1', author, modifier: reactor }, { text, senderTimestampMs: 1786000000999 });
+ return {
+ key: { id: 'REACT1', remoteJid: overrides.remoteJid ?? group, participant: reactor, fromMe: false },
+ messageTimestamp: 1_786_000_200,
+ message: {
+ encReactionMessage: { targetMessageKey: { id: 'ORIG1', remoteJid: group, fromMe: false }, ...sealed },
+ },
+ };
+ }
+
+ function setup(extra: Partial<BaileysEventsHost> = {}, stored: WAMessage | null = original()) {
+ const onMessageEdited = jest.fn();
+ const onMessageReaction = jest.fn();
+ const onMessage = jest.fn();
+ const recordMessageEdit = jest.fn();
+ const events = new BaileysEvents(
+ makeHost({
+ loadLib: () => Promise.resolve(lib),
+ getStoredMessage: (id: string) => Promise.resolve(id === 'ORIG1' ? stored : null),
+ getOnMessageEdited: () => onMessageEdited,
+ getOnMessageReaction: () => onMessageReaction,
+ getOnMessage: () => onMessage,
+ recordMessageEdit,
+ ...extra,
+ }),
+ );
+ return { events, onMessageEdited, onMessageReaction, onMessage, recordMessageEdit };
+ }
+
+ it("applies a contact's encrypted edit of a stored message, as the plain protocol message would be", async () => {
+ const { events, onMessageEdited, onMessage, recordMessageEdit } = setup();
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledTimes(1);
+ expect(onMessageEdited).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'ORIG1', body: 'new text', chatId: group, senderId: author }),
+ );
+ expect(recordMessageEdit).toHaveBeenCalledWith(group, 'ORIG1', 'new text');
+ expect(onMessage).not.toHaveBeenCalled();
+ });
+
+ it('reads the edit of a 1:1 message, whose key names the partner by chat and leaves the participant empty', async () => {
+ const chat = '262813461250071@lid';
+ const stored = original({ key: { id: 'ORIG1', remoteJid: chat, participant: '', fromMe: false } });
+ const { events, onMessageEdited } = setup({}, stored);
+ const sealed = seal('Message Edit', { target: 'ORIG1', author: chat, modifier: chat }, editPlain);
+ const envelope = editEnvelope({ sealed, remoteJid: chat, participant: '' });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [envelope] });
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));
+ });
+
+ it("reads an edit the account made from its phone, under the account's own id", async () => {
+ const self = '[email protected]';
+ const stored = original({ key: { id: 'ORIG1', remoteJid: group, fromMe: true } });
+ const { events, onMessageEdited } = setup(
+ {
+ getSocketOrNull: () => ({ user: { id: '6280000000000:[email protected]', lid: '5550001:12@lid' } }) as WASocket,
+ },
+ stored,
+ );
+ const sealed = seal('Message Edit', { target: 'ORIG1', author: self, modifier: self }, editPlain);
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope({ sealed, fromMe: true })] });
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', fromMe: true }));
+ });
+
+ it('applies an edit the account made from its phone as a plain protocol message, under its own id', async () => {
+ const stored = original({ key: { id: 'ORIG1', remoteJid: group, fromMe: true } });
+ const { events, onMessageEdited, recordMessageEdit } = setup({}, stored);
+ const plain = {
+ key: { id: 'ENV2', remoteJid: group, fromMe: true },
+ messageTimestamp: 1_786_000_100,
+ message: { protocolMessage: editPlain.protocolMessage },
+ } as unknown as WAMessage;
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [plain] });
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'ORIG1', body: 'new text', fromMe: true }),
+ );
+ expect(recordMessageEdit).toHaveBeenCalledWith(group, 'ORIG1', 'new text');
+ });
+
+ it('reads an edit of a message that is still being processed, with the secret that copy carries', async () => {
+ // The original's repeat-delivery check never settles until released, which keeps it in flight; the
+ // edit's own read of the store answers nothing.
+ let release: (stored: WAMessage | null) => void = () => undefined;
+ let reads = 0;
+ const getStoredMessage = (id: string): Promise<WAMessage | null> => {
+ if (id !== 'ORIG1') return Promise.resolve(null);
+ reads += 1;
+ return reads === 1 ? new Promise(resolve => (release = resolve)) : Promise.resolve(null);
+ };
+ const { events, onMessageEdited } = setup({ getStoredMessage });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));
+ release(null);
+ await flush();
+ });
+
+ it('reads the edit of an original that finishes while the edit is still reading the store', async () => {
+ // The edit's read of the store is issued while the original is in flight, and answers (null: the row
+ // was written after the read began) only once the original has finished and left the in-flight map.
+ const reads: Array<(stored: WAMessage | null) => void> = [];
+ // Only these two reads are held; any later read of the id (the guard that follows) answers at once.
+ const getStoredMessage = (id: string): Promise<WAMessage | null> =>
+ id === 'ORIG1' && reads.length < 2 ? new Promise(resolve => reads.push(resolve)) : Promise.resolve(null);
+ const { events, onMessageEdited } = setup({ getStoredMessage });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+ expect(reads).toHaveLength(2);
+
+ reads[0](null); // the original's own repeat-delivery check answers: it is stored and done
+ await flush();
+ reads[1](null); // now the edit's read answers, finding no row and no in-flight entry
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));
+ });
+
+ it("drops another member's encrypted edit of an original that finishes while the guard reads the store", async () => {
+ // Held reads of the target, in order: the original's own repeat check, the reveal's read, the guard's.
+ const reads: Array<(stored: WAMessage | null) => void> = [];
+ const getStoredMessage = (id: string): Promise<WAMessage | null> =>
+ id === 'ORIG1' && reads.length < 3 ? new Promise(resolve => reads.push(resolve)) : Promise.resolve(null);
+ const { events, onMessageEdited, recordMessageEdit } = setup({ getStoredMessage });
+ // Another member of the group, who holds the message's secret as a recipient of it, seals an edit.
+ const forged = editEnvelope({
+ participant: reactor,
+ sealed: seal('Message Edit', { target: 'ORIG1', author, modifier: reactor }, editPlain),
+ });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [forged] });
+ await flush();
+ expect(reads).toHaveLength(2);
+
+ reads[1](null); // the reveal reads nothing and decrypts from the copy in flight
+ await flush();
+ expect(reads).toHaveLength(3); // the guard's read is out now
+ reads[0](null); // the original finishes and leaves the in-flight map while it is
+ await flush();
+ reads[2](null);
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ expect(recordMessageEdit).not.toHaveBeenCalled();
+ });
+
+ it('holds a plain edit from another member to the same rule when the original finishes during the read', async () => {
+ const reads: Array<(stored: WAMessage | null) => void> = [];
+ const getStoredMessage = (id: string): Promise<WAMessage | null> =>
+ id === 'ORIG1' && reads.length < 2 ? new Promise(resolve => reads.push(resolve)) : Promise.resolve(null);
+ const { events, onMessageEdited } = setup({ getStoredMessage });
+ const plain = {
+ key: { id: 'ENV2', remoteJid: group, participant: reactor, fromMe: false },
+ messageTimestamp: 1_786_000_100,
+ message: { protocolMessage: editPlain.protocolMessage },
+ } as unknown as WAMessage;
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [plain] });
+ await flush();
+ expect(reads).toHaveLength(2); // the original's check and the guard's read
+ reads[0](null);
+ await flush();
+ reads[1](null);
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ });
+
+ it("still applies the author's own encrypted edit in the same interleaving", async () => {
+ const reads: Array<(stored: WAMessage | null) => void> = [];
+ const getStoredMessage = (id: string): Promise<WAMessage | null> =>
+ id === 'ORIG1' && reads.length < 3 ? new Promise(resolve => reads.push(resolve)) : Promise.resolve(null);
+ const { events, onMessageEdited } = setup({ getStoredMessage });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+ reads[1](null);
+ await flush();
+ reads[0](null);
+ await flush();
+ reads[2](null);
+ await flush();
+
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));
+ });
+
+ describe("another member's encrypted edit of an original still being processed", () => {
+ // The original's own repeat check is the first read of the store. The store keeps what is put into it, so
+ // a read made after the original was processed finds its copy.
+ const withHeldReads = (held: number[], answered: Promise<{ conflict?: boolean } | undefined>) => {
+ const opens = new Map<number, () => void>();
+ const gates = new Map<number, Promise<void>>();
+ for (const index of held) gates.set(index, new Promise<void>(resolve => opens.set(index, resolve)));
+ let copy: WAMessage | null = null;
+ let reads = 0;
+ const setups = setup({
+ getStoredMessage: async (id: string) => {
+ if (id !== 'ORIG1') return null;
+ const seen = copy;
+ await gates.get(++reads);
+ return seen;
+ },
+ putStoredMessage: (msg: WAMessage) => {
+ copy = msg;
+ return Promise.resolve();
+ },
+ removeStoredMessage: () => {
+ copy = null;
+ return Promise.resolve();
+ },
+ getOnMessage: () => jest.fn(() => ({ settled: answered })),
+ });
+ return { ...setups, open: (index: number) => opens.get(index)!() };
+ };
+ const forged = (): WAMessage =>
+ editEnvelope({
+ participant: reactor,
+ sealed: seal('Message Edit', { target: 'ORIG1', author, modifier: reactor }, editPlain),
+ });
+
+ it('is held until the original is stored, and stays held while the original has no answer', async () => {
+ const { events, onMessageEdited, recordMessageEdit, open } = withHeldReads([1], new Promise(() => undefined));
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [forged()] });
+ await flush();
+ expect(onMessageEdited).not.toHaveBeenCalled();
+
+ open(1);
+ await flush();
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ expect(recordMessageEdit).not.toHaveBeenCalled();
+ });
+
+ it('is applied once the answer says the original was another message and its copy is gone', async () => {
+ let answer!: (outcome: { conflict: boolean }) => void;
+ const answered = new Promise<{ conflict: boolean }>(resolve => (answer = resolve));
+ const { events, onMessageEdited, open } = withHeldReads([1], answered);
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [forged()] });
+ await flush();
+ open(1);
+ await flush();
+ expect(onMessageEdited).not.toHaveBeenCalled();
+
+ answer({ conflict: true });
+ await flush();
+ expect(onMessageEdited).toHaveBeenCalledWith(expect.objectContaining({ messageId: 'ORIG1', body: 'new text' }));
+ });
+
+ it('is dropped once the original is stored and answered as the message', async () => {
+ // Reads, in order: the original's repeat check, the reveal's, the guard's, and the guard's second.
+ const answered = Promise.resolve({ conflict: false });
+ const { events, onMessageEdited, recordMessageEdit, open } = withHeldReads([1, 4], answered);
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [original()] });
+ await flush();
+ events.handleMessagesUpsert({ type: 'notify', messages: [forged()] });
+ await flush();
+ open(1);
+ await flush();
+ open(4);
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ expect(recordMessageEdit).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('leaves an encrypted edit unapplied when', () => {
+ it.each([
+ ['another member sealed it for the message', () => editEnvelope({ participant: reactor })],
+ [
+ 'its payload was sealed under another secret',
+ () =>
+ editEnvelope({
+ sealed: seal('Message Edit', { target: 'ORIG1', author, modifier: author }, editPlain, Buffer.alloc(32, 1)),
+ }),
+ ],
+ ['it is an edit of an event', () => editEnvelope({ type: 1 })],
+ [
+ 'it names a message that is not stored',
+ () =>
+ editEnvelope({
+ target: 'GONE',
+ sealed: seal('Message Edit', { target: 'GONE', author, modifier: author }, editPlain),
+ }),
+ ],
+ [
+ 'what it decrypts to names another message than the one it targets',
+ () =>
+ editEnvelope({
+ sealed: seal(
+ 'Message Edit',
+ { target: 'ORIG1', author, modifier: author },
+ {
+ protocolMessage: { ...editPlain.protocolMessage, key: { id: 'SOMETHING_ELSE' } },
+ },
+ ),
+ }),
+ ],
+ [
+ 'what it decrypts to is not an edit',
+ () =>
+ editEnvelope({
+ sealed: seal(
+ 'Message Edit',
+ { target: 'ORIG1', author, modifier: author },
+ {
+ protocolMessage: { ...editPlain.protocolMessage, type: 0 },
+ },
+ ),
+ }),
+ ],
+ ['it targets a message of another chat', () => editEnvelope({ remoteJid: '[email protected]' })],
+ ])('%s', async (_name, build) => {
+ const { events, onMessageEdited, onMessage, recordMessageEdit } = setup();
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [build()] });
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ expect(recordMessageEdit).not.toHaveBeenCalled();
+ expect(onMessage).not.toHaveBeenCalled();
+ });
+
+ it('the message store cannot be read', async () => {
+ const { events, onMessageEdited } = setup({ getStoredMessage: () => Promise.reject(new Error('store down')) });
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ });
+
+ it('the target carries no secret', async () => {
+ const { events, onMessageEdited } = setup({}, original({ message: { conversation: 'old text' } }));
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [editEnvelope()] });
+ await flush();
+
+ expect(onMessageEdited).not.toHaveBeenCalled();
+ });
+ });
+
+ it('reports a reaction a member sent encrypted, and its removal', async () => {
+ const { events, onMessageReaction } = setup();
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('👍')] });
+ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('')] });
+ await flush();
+
+ expect(onMessageReaction).toHaveBeenCalledTimes(2);
+ expect(onMessageReaction).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ messageId: 'ORIG1', chatId: group, reaction: '👍', senderId: reactor }),
+ );
+ expect(onMessageReaction).toHaveBeenNthCalledWith(2, expect.objectContaining({ reaction: '', senderId: reactor }));
+ });
+
+ it('drops an encrypted reaction that names a message of another chat, as a plain one is', async () => {
+ const { events, onMessageReaction } = setup();
+
+ events.handleMessagesUpsert({
+ type: 'notify',
+ messages: [reactionEnvelope('👍', { remoteJid: '[email protected]' })],
+ });
+ await flush();
+
+ expect(onMessageReaction).not.toHaveBeenCalled();
+ });
+
+ it('drops an encrypted reaction sealed under another secret', async () => {
+ const { events, onMessageReaction } = setup();
+ const sealed = seal(
+ 'Enc Reaction',
+ { target: 'ORIG1', author, modifier: reactor },
+ { text: '👍' },
+ Buffer.alloc(32, 9),
+ );
+
+ events.handleMessagesUpsert({ type: 'notify', messages: [reactionEnvelope('👍', { sealed })] });
+ await flush();
+
+ expect(onMessageReaction).not.toHaveBeenCalled();
+ });
+ });
diff --cc src/engine/adapters/baileys-events.ts
index 9d4763c06,4e4605cc3..a4b0f7a28
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@@ -203,10 -242,12 +244,14 @@@ export interface BaileysEventsHost
getOnMessageReaction(): EngineEventCallbacks['onMessageReaction'];
/** The currently-registered onMessageAck callback, if any (assigned at initialize()). */
getOnMessageAck(): EngineEventCallbacks['onMessageAck'];
+ /** The currently-registered onMessageReceipt callback, if any (assigned at initialize()). */
+ getOnMessageReceipt(): EngineEventCallbacks['onMessageReceipt'];
/** The currently-registered onGroupEvent callback, if any (assigned at initialize()). */
getOnGroupEvent(): EngineEventCallbacks['onGroupEvent'];
+ /** The currently-registered onEventResponse callback, if any (assigned at initialize()). */
+ getOnEventResponse(): EngineEventCallbacks['onEventResponse'];
+ /** A contact from the session's own store, by any id dialect; no network read. */
+ findContact(contactId: string): Contact | null;
/** The currently-registered onCall callback, if any (assigned at initialize()). */
getOnCall(): EngineEventCallbacks['onCall'];
/** The currently-registered onPresenceUpdate callback, if any (assigned at initialize()). */
@@@ -782,78 -1300,81 +1304,153 @@@ export class BaileysEvents
}
}
+ /**
+ * Baileys `message-receipt.update`: per-participant receipts, which Baileys raises only for group
+ * and status messages (1:1 receipts arrive as `messages.update` instead). Only receipts for
+ * messages this account sent are reported, and receipts from the account's own linked devices are
+ * dropped. The event buffer can merge several receipts of one participant into one entry, so each
+ * timestamp the entry carries becomes its own event. rc14 files a `played` receipt under
+ * `readTimestamp`, so on that version a voice note that was played reports `read`.
+ */
+ handleMessageReceiptUpdate(
+ updates: Array<{
+ key?: { id?: string | null; remoteJid?: string | null; fromMe?: boolean | null };
+ receipt?: {
+ userJid?: string | null;
+ receiptTimestamp?: number | { toNumber(): number } | null;
+ readTimestamp?: number | { toNumber(): number } | null;
+ playedTimestamp?: number | { toNumber(): number } | null;
+ };
+ }>,
+ ): void {
+ const onReceipt = this.host.getOnMessageReceipt();
+ if (!onReceipt) {
+ return;
+ }
+ const isSelf = this.selfMatcher();
+ for (const { key, receipt } of Array.isArray(updates) ? updates : []) {
+ if (!key?.id || !key.remoteJid || key.fromMe !== true || !receipt?.userJid || isSelf(receipt.userJid)) {
+ continue;
+ }
+ const stamps: Array<[MessageReceiptStatus, typeof receipt.receiptTimestamp]> = [
+ ['delivered', receipt.receiptTimestamp],
+ ['read', receipt.readTimestamp],
+ ['played', receipt.playedTimestamp],
+ ];
+ for (const [status, ts] of stamps) {
+ if (ts == null) continue;
+ const event: MessageReceiptEvent = {
+ messageId: key.id,
+ chatId: this.host.toNeutralJid(key.remoteJid),
+ participant: this.host.toNeutralJid(receipt.userJid),
+ status,
+ timestamp: toUnixSeconds(ts),
+ };
+ onReceipt(event);
+ }
+ }
+ }
+
+ /**
+ * Matches any jid of this account, in either dialect and from any of its devices (user parts are
+ * compared). Answers false for everything while the account's own id is unknown.
+ */
+ private selfMatcher(): (jid: string | null | undefined) => boolean {
+ const selfJid = this.host.normalizedSelfJid();
+ if (!selfJid) {
+ return () => false;
+ }
+ const phone = userPart(selfJid);
+ const lid = this.host.getSocketOrNull()?.user?.lid;
+ const lidUser = lid ? userPart(lid) : undefined;
+ return (jid: string | null | undefined): boolean => {
+ if (!jid) return false;
+ const { kind, userPart: user } = parseWaId(jid);
+ if (kind === 'user') return user === phone;
+ if (kind !== 'lid') return false;
+ if (lidUser !== undefined) return user === lidUser;
+ // Creds carrying no `user.lid` leave nothing to compare a lid-addressed jid against, and every
+ // such comparison would answer false. Fall back to the session's own lid to phone mapping,
+ // which the store learns from the same traffic.
+ return userPart(this.host.toNeutralJid(jid)) === phone;
+ };
+ }
+
+ /**
+ * An RSVP to a WhatsApp event. Baileys decrypts it itself while processing the inbound
+ * `encEventResponseMessage` (whose upsert the live path drops as non-content): it reads the event
+ * creation message's `messageSecret` through the socket's getMessage, which this adapter backs
+ * with the message store, and re-emits the plaintext as a `messages.update` of the CREATION
+ * message's key. An RSVP to an event the store does not hold cannot be decrypted and never
+ * arrives here. Decryption authenticates the responder, since the key is derived from their jid.
+ */
+ private async emitEventResponse(eventKey: BaileysMessageUpdate['key'], rsvp: BaileysEventResponse): Promise<void> {
+ const callback = this.host.getOnEventResponse();
+ const envelope = rsvp.eventResponseMessageKey;
+ if (!callback || !eventKey?.id || !eventKey.remoteJid || !envelope?.id) return;
+ // Learned before any id below is canonicalized, as an inbound message does, so a guest answering
+ // for the first time is not reported by lid once and by phone number afterwards.
+ this.host.recordKeyLidMappings(envelope);
+ // Baileys decrypts an RSVP against whichever stored event its creation key names and compares no
+ // chats, so a member of two groups can answer in one an event posted in the other. The answer is
+ // reported for the chat it arrived in, so one sent outside its event's chat is dropped, as an edit,
+ // revoke or reaction aimed at a message of another chat is. Fails open like those: a store that
+ // cannot be read, or ids that cannot be compared, report the RSVP as before.
+ const stored = await this.readStoredMessage(eventKey.id, 'reading the event an RSVP answers');
+ if (
+ stored &&
+ differentWaIds(
+ [stored.key.remoteJid, stored.key.remoteJidAlt],
+ [envelope.remoteJid, envelope.remoteJidAlt],
+ jid => this.host.toNeutralJid(jid),
+ )
+ ) {
+ this.host.logger.warn('Dropping an event response sent in a chat other than its event', {
+ msgId: eventKey.id,
+ responseMessageId: envelope.id,
+ remoteJid: envelope.remoteJid,
+ });
+ return;
+ }
+ const fromMe = envelope.fromMe === true;
+ // The creation key is the guest's view of the event (in a 1:1 chat its remoteJid is this
+ // account), so the chat comes from the RSVP's own key, which Baileys has put on our side.
+ const chatJid = envelope.remoteJid ?? eventKey.remoteJid;
+ // Same rule as a reaction: a 1:1 key names the chat partner, so the account's own answer is
+ // attributed to the account; group keys carry the responder as `participant`.
+ const responder = keyParticipant(envelope) ?? (fromMe ? this.host.normalizedSelfJid() : chatJid);
+ if (!responder) return;
+ const event: EventResponseEvent = {
+ eventMessageId: eventKey.id,
+ chatId: this.host.toNeutralJid(chatJid),
+ responderId: this.host.toNeutralJid(responder),
+ fromMe,
+ response: mapBaileysEventResponseType(rsvp.response?.response),
+ responseMessageId: envelope.id,
+ timestamp: this.toEditUnixSeconds(
+ rsvp.senderTimestampMs ?? rsvp.response?.timestampMs,
+ Math.floor(Date.now() / 1000),
+ ),
+ };
+ const guests = rsvp.response?.extraGuestCount;
+ if (typeof guests === 'number' && Number.isFinite(guests)) event.extraGuestCount = guests;
+ // Named from the session's own contact store, like the sender of message.received, so an
+ // attendance list can be built from the RSVPs alone without a network read per answer.
+ const known = this.host.findContact(responder);
+ if (known?.name || known?.pushName) {
+ event.contact = {
+ ...(known.name ? { name: known.name } : {}),
+ ...(known.pushName ? { pushName: known.pushName } : {}),
+ };
+ }
+ if (stored?.message) {
+ const b = await this.host.loadLib();
+ const name = b.normalizeMessageContent(stored.message)?.eventMessage?.name;
+ if (name) event.eventName = name;
+ }
+ callback(event);
+ }
+
/**
* Baileys `group-participants.update`: a membership change. Only add/remove map to the neutral
* join/leave kinds — promote/demote (and 'modify', a phone-number-change rewrite) change no
diff --cc src/engine/adapters/baileys.adapter.spec.ts
index a8572ffd5,b1287b82f..a2c7ad6f6
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@@ -2761,28 -2959,21 +2959,40 @@@ describe('BaileysAdapter inbound fan-ou
const adapter = newAdapter();
await adapter.initialize({ onMessageAck });
fakeSock.fire('messages.update', [{ key: { id: 'OUT1' }, update: { status: 3 } }]);
- expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered');
+ expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered', undefined);
+ });
+
+ it('carries the update key chat on onMessageAck, canonicalized', async () => {
+ const onMessageAck = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessageAck });
+ fakeSock.fire('messages.update', [
+ { key: { id: 'OUT2', remoteJid: '[email protected]' }, update: { status: 2 } },
+ { key: { id: 'OUT3', remoteJid: '[email protected]' }, update: { status: 3 } },
+ ]);
+ expect(onMessageAck).toHaveBeenCalledWith('OUT2', 'sent', '[email protected]');
+ expect(onMessageAck).toHaveBeenCalledWith('OUT3', 'delivered', '[email protected]');
});
+ it('emits onMessageReceipt from message-receipt.update for a group message the account sent', async () => {
+ const onMessageReceipt = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessageReceipt });
+ fakeSock.fire('message-receipt.update', [
+ {
+ key: { id: 'OUT1', remoteJid: '[email protected]', fromMe: true },
+ receipt: { userJid: '[email protected]', readTimestamp: 1700000000 },
+ },
+ ]);
+ expect(onMessageReceipt).toHaveBeenCalledWith({
+ messageId: 'OUT1',
+ chatId: '[email protected]',
+ participant: '[email protected]',
+ status: 'read',
+ timestamp: 1700000000,
+ });
+ });
+
it('inbound image: downloads media and exposes base64 + caption as body', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as {
diff --cc src/engine/adapters/baileys.adapter.ts
index 06071b9a8,5d9ddc091..0bfe39f8f
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@@ -157,8 -162,8 +162,9 @@@ export class BaileysAdapter implements
getOnMessageEdited: () => this.callbacks.onMessageEdited,
getOnMessageReaction: () => this.callbacks.onMessageReaction,
getOnMessageAck: () => this.callbacks.onMessageAck,
+ getOnMessageReceipt: () => this.callbacks.onMessageReceipt,
getOnGroupEvent: () => this.callbacks.onGroupEvent,
+ getOnEventResponse: () => this.callbacks.onEventResponse,
getOnCall: () => this.callbacks.onCall,
getOnPresenceUpdate: () => this.callbacks.onPresenceUpdate,
getOnCallOutcome: () => this.callbacks.onCallOutcome,
diff --cc src/engine/interfaces/whatsapp-engine.interface.ts
index fd2e89f86,1e745b16e..d150b2764
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@@ -796,25 -828,52 +828,71 @@@ export interface CallOutcomeEvent
timestamp: number;
}
+/** What one recipient did with an outgoing message. `played` applies to voice notes and view-once media. */
+export type MessageReceiptStatus = 'delivered' | 'read' | 'played';
+
+/**
+ * One recipient's receipt for a message the account sent (group and status messages, where WhatsApp
+ * reports each participant separately). Receipts from the account's own linked devices are dropped
+ * by the adapter, so `participant` is always someone else.
+ */
+export interface MessageReceiptEvent {
+ messageId: string;
+ /** Neutral id of the chat the message was sent to (the group, or `status@broadcast`). */
+ chatId: string;
+ /** Neutral id of the recipient the receipt came from. */
+ participant: string;
+ status: MessageReceiptStatus;
+ /** Unix seconds the recipient reached this status (engine timestamp). */
+ timestamp: number;
+}
+
+ /**
+ * A message's place in its session from the moment it arrives until its row is written (see
+ * `EngineEventCallbacks.admitInbound`). The engine hands it back with the message it emits.
+ */
+ export interface InboundTicket {
+ /**
+ * Room for one downloaded payload: true once granted, false when the message asked for none, or
+ * when no room came free in time (the media then goes out with the omitted marker, undownloaded).
+ * Call it right before the download, never earlier: the grant is held until the row is written.
+ */
+ reserve: () => boolean | Promise<boolean>;
+ /** Keep the room until `p` settles too: work on the payload that may outlive the emit. */
+ holdUntil: (p: Promise<unknown>) => void;
+ /** The message will not be emitted: release its turn and its room. A no-op after the emit. */
+ drop: () => void;
+ /**
+ * Whether the session recorded a delete for everyone of this message while holding it, so emitting
+ * it stores the row cleared and announces nothing. False for a revoke the session never saw.
+ */
+ readonly revoked: boolean;
+ }
+
+ /**
+ * What the session made of a message handed to `EngineEventCallbacks.onMessage`, for an engine that
+ * keeps its own copy of messages keyed by id. An engine that keeps none ignores it.
+ */
+ export interface InboundOutcome {
+ /**
+ * The session already holds a different message under this id (another chat, another side of the
+ * conversation, or another author), so the delivery was dropped as a duplicate. The engine's copy
+ * under that id is this delivery's, not the message the session holds, and must not stand in for it.
+ * Left out for a delivery that landed and for one the session cannot prove is another message.
+ */
+ conflict?: boolean;
+ }
+
+ /**
+ * The session's answer to `onMessage`, for an engine that wants to know what became of the message.
+ * Wrapped rather than a bare promise: most engines ignore it, and a promise nobody awaits reads as a
+ * mistake wherever a callback is called.
+ */
+ export interface InboundReceipt {
+ /** Settles once the message's row is settled, with what became of it; never rejects. */
+ settled: Promise<InboundOutcome | undefined>;
+ }
+
export interface EngineEventCallbacks {
onQRCode?: (qr: string) => void;
onReady?: (phone: string, pushName: string) => void;
@@@ -827,16 -912,23 +931,28 @@@
/**
* Fired when the delivery status of an outgoing message advances. The adapter maps its native
* delivery signal to the neutral `DeliveryStatus`, so consumers never see engine-specific codes.
+ * `chatId` is the conversation the acked message belongs to, canonicalized the same way the
+ * inbound mappers canonicalize `IncomingMessage.chatId`; undefined when the engine's update
+ * carries no chat, and the emitted payload then omits the field rather than guess.
*/
- onMessageAck?: (messageId: string, status: DeliveryStatus) => void;
+ onMessageAck?: (messageId: string, status: DeliveryStatus, chatId?: string) => void;
+ /**
+ * Fired once per recipient as each one receives, reads or plays a message the account sent to a
+ * group or status. Baileys only: whatsapp-web.js has no per-participant receipt event.
+ */
+ onMessageReceipt?: (event: MessageReceiptEvent) => void;
- onMessageRevoked?: (message: RevokedMessage) => void;
+ /**
+ * `actor.fromMe` says whether the account itself made the revoke (from its phone). Only an engine that
+ * receives the raw protocol message can say; whatsapp-web.js leaves it out.
+ */
+ onMessageRevoked?: (message: RevokedMessage, actor?: { fromMe: boolean }) => void;
onMessageReaction?: (event: ReactionEvent) => void;
onMessageEdited?: (message: EditedMessage) => void;
+ /**
+ * Fired for each RSVP to a WhatsApp event (consumers emit `event.response`). Baileys only: it
+ * decrypts the RSVP itself from the stored event creation message. whatsapp-web.js never fires it.
+ */
+ onEventResponse?: (event: EventResponseEvent) => void;
/**
* Fired on group membership changes (join/leave), group metadata updates
* (subject/description/announce/locked), and pending join requests. The `kind` selects the
diff --cc src/modules/events/events.gateway.chat-scope.spec.ts
index 000000000,494a535c4..f3401ec5d
mode 000000,100644..100644
--- a/src/modules/events/events.gateway.chat-scope.spec.ts
+++ b/src/modules/events/events.gateway.chat-scope.spec.ts
@@@ -1,0 -1,410 +1,436 @@@
+ import type { ConfigService } from '@nestjs/config';
+ import type { Server, Socket } from 'socket.io';
+ import { EventsGateway } from './events.gateway';
+ import { ChatScopeService } from '../auth/chat-scope.service';
+ import type { AuthService } from '../auth/auth.service';
+ import type { AuditService } from '../audit/audit.service';
+ import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';
+ import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+
+ const PHONE = '[email protected]';
+ const OTHER = '[email protected]';
+ const key = (id: string, allowedChats: string[] | null, allowedSessions: string[] | null = ['s1']): ApiKey =>
+ ({ id, name: id, role: ApiKeyRole.VIEWER, allowedSessions, allowedChats }) as ApiKey;
+
+ function socket(id: string) {
+ const rooms = new Set([id]);
+ const client = {
+ id,
+ rooms,
+ data: {},
+ disconnected: false,
+ handshake: { auth: { apiKey: id }, headers: {}, address: '127.0.0.1' },
+ emit: jest.fn(),
+ join: jest.fn((room: string) => {
+ rooms.add(room);
+ }),
+ leave: jest.fn((room: string) => {
+ rooms.delete(room);
+ }),
+ disconnect: jest.fn(() => {
+ client.disconnected = true;
+ rooms.clear();
+ }),
+ };
+ return client;
+ }
+
+ describe('chat-scoped WebSocket rooms', () => {
+ let gateway: EventsGateway;
+ let current: Record<string, ApiKey>;
+ let clients: ReturnType<typeof socket>[];
+ let lidPhone: string | null;
+ let mappingFails: boolean;
+ let resolveIds: jest.SpyInstance;
+ const subscribe = (client: ReturnType<typeof socket>, events = ['*'], sessionId = 's1') =>
+ gateway.handleMessage(client as unknown as Socket, { type: 'subscribe', sessionId, events });
+ const events = (client: ReturnType<typeof socket>) =>
+ client.emit.mock.calls
+ .map(
+ ([, frame]) =>
+ frame as { type: string; payload: { event: string; sessionId: string; data: Record<string, unknown> } },
+ )
+ .filter(frame => frame.type === 'event');
+ const flush = () => new Promise<void>(resolve => setImmediate(resolve));
+ const connect = async (
+ id: string,
+ chats: string[] | null,
+ sessions: string[] | null = ['s1'],
+ sessionId = 's1',
+ subscribed = ['*'],
+ ) => {
+ current[id] = key(id, chats, sessions);
+ const client = socket(id);
+ clients.push(client);
+ await gateway.handleConnection(client as unknown as Socket);
+ await subscribe(client, subscribed, sessionId);
+ return client;
+ };
+
+ beforeEach(() => {
+ current = {};
+ clients = [];
+ lidPhone = null;
+ mappingFails = false;
+ const scope = new ChatScopeService({
+ phonesForLidsPersisted: jest.fn((lids: string[]) => {
+ if (mappingFails) return Promise.reject(new Error('Mapping lookup unavailable'));
+ return Promise.resolve(lids.includes('123456') ? { '123456': lidPhone } : {});
+ }),
+ lidsForPhonesPersisted: jest.fn().mockResolvedValue({}),
+ } as unknown as LidMappingStoreService);
+ resolveIds = jest.spyOn(scope, 'idsForFilter');
+ gateway = new EventsGateway(
+ { validateApiKey: jest.fn((id: string) => Promise.resolve(current[id])) } as unknown as AuthService,
+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,
+ { get: jest.fn((_name: string, fallback: unknown) => fallback) } as unknown as ConfigService,
+ scope,
+ );
+ // Room unions model the adapter's recipient deduplication, including remote recipients.
+ gateway.server = {
+ to: (room: string | string[]) => {
+ const target = new Set(Array.isArray(room) ? room : [room]);
+ const excluded = new Set<string>();
+ const broadcast = {
+ to: (next: string) => {
+ target.add(next);
+ return broadcast;
+ },
+ except: (next: string) => {
+ excluded.add(next);
+ return broadcast;
+ },
+ emit: (name: string, frame: unknown) => {
+ for (const client of clients) {
+ if ([...target].some(r => client.rooms.has(r)) && ![...excluded].some(r => client.rooms.has(r))) {
+ client.emit(name, frame);
+ }
+ }
+ },
+ };
+ return broadcast;
+ },
+ } as unknown as Server;
+ });
+
+ it('keeps restricted subscriptions out of the global stream and deduplicates overlapping rooms', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ const outside = await connect('outside', [OTHER]);
+ const unrestricted = await connect('unrestricted', null);
+ await subscribe(allowed, ['message.received', '*']);
+ expect(allowed.disconnected).toBe(false);
+ const held = [...allowed.rooms].filter(room => room.startsWith('session:'));
+ expect(held.length).toBeGreaterThan(0);
+ expect(held.every(room => room.includes(':chat:'))).toBe(true);
+ gateway.emitMessage('s1', { chatId: PHONE, body: 'allowed' });
+ await flush();
+ expect(events(allowed)).toHaveLength(1);
+ expect(events(outside)).toHaveLength(0);
+ expect(events(unrestricted)).toHaveLength(1);
+ });
+
+ it('keeps group join requests away from a restricted key, since they name people outside its chats', async () => {
+ const group = '[email protected]';
+ const restricted = await connect('restricted', [group]);
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitGroupJoinRequest('s1', { groupId: group, participantIds: ['[email protected]'] });
+ gateway.emitGroupUpdate('s1', { groupId: group, subject: 'Renamed' });
+ await flush();
+ // The REST membership-request routes refuse these keys for the same reason: a requester is, by
+ // definition, not in the allowed chats, and listing the queue names them.
+ expect(events(restricted).map(frame => frame.payload.event)).toEqual(['group.update']);
+ expect(events(unrestricted).map(frame => frame.payload.event)).toEqual(['group.join_request', 'group.update']);
+ expect(await subscribe(restricted, ['group.join_request'])).toMatchObject({
+ type: 'error',
+ code: 'FORBIDDEN_EVENTS',
+ });
+ });
+
+ it('delivers an event response only to keys whose chats include the chat it names', async () => {
+ const group = '[email protected]';
+ const inside = await connect('inside', [group]);
+ const outside = await connect('outside', ['[email protected]']);
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitEventResponse('s1', { chatId: group, eventMessageId: 'EVT1', response: 'going' });
+ gateway.emitEventResponse('s1', { eventMessageId: 'EVT2', response: 'going' });
+ await flush();
+ expect(events(inside).map(frame => frame.payload.data)).toEqual([
+ expect.objectContaining({ eventMessageId: 'EVT1' }),
+ ]);
+ expect(events(outside)).toHaveLength(0);
+ // An unrestricted key hears every one, a payload with no chat included.
+ expect(events(unrestricted)).toHaveLength(2);
+ });
+
++ it('delivers receipts only to named subscriptions within the allowed session and chat', async () => {
++ const group = '[email protected]';
++ const named = await connect('named', [group], ['s1'], 's1', ['message.receipt']);
++ const allSessions = await connect('all-sessions', [group], null, '*', ['message.receipt']);
++ const outside = await connect('outside', ['[email protected]'], ['s1'], 's1', ['message.receipt']);
++ const wildcard = await connect('wildcard', [group]);
++ const receipt = {
++ id: 'OUT1',
++ messageId: 'OUT1',
++ chatId: group,
++ participant: PHONE,
++ status: 'read' as const,
++ timestamp: 1700000000,
++ };
++
++ gateway.emitMessageReceipt('s1', receipt);
++ gateway.emitMessageReceipt('s2', receipt);
++ gateway.emitMessageReceipt('s1', { ...receipt, chatId: 'status@broadcast' });
++ await flush();
++
++ expect(events(named).map(frame => frame.payload.sessionId)).toEqual(['s1']);
++ expect(events(allSessions).map(frame => frame.payload.sessionId)).toEqual(['s1', 's2']);
++ expect(events(outside)).toHaveLength(0);
++ expect(events(wildcard)).toHaveLength(0);
++ });
++
+ it('refuses a subscribe that can never fit before it builds a single room name', async () => {
+ const chats = Array.from({ length: 450 }, (_, index) => `62811${String(index).padStart(7, '0')}@c.us`);
+ const restricted = await connect('restricted', chats);
+ // The room set is only consulted once the names exist, so a read after the refusal means the
+ // refused frame was still paid for in full (tens of milliseconds at a few thousand allowlist entries).
+ let reads = 0;
+ const joined = restricted.rooms;
+ Object.defineProperty(restricted, 'rooms', {
+ get: () => {
+ reads += 1;
+ return joined;
+ },
+ });
+ const chatEvents = [
+ 'message.received',
+ 'message.sent',
+ 'message.ack',
+ 'message.revoked',
+ 'message.reaction',
+ 'message.edited',
+ 'group.join',
+ 'group.leave',
+ 'group.update',
+ 'presence.update',
+ ];
+ const refused = await subscribe(restricted, chatEvents);
+ expect(refused).toMatchObject({ type: 'error', code: 'TOO_MANY_SUBSCRIPTIONS' });
+ expect(reads).toBe(0);
+ // The socket holds nothing, so unsubscribing cannot make this fit: the reply names what each event
+ // costs this key and the way out.
+ const { message } = refused as { message: string };
+ expect(message).toContain('every event 900 subscriptions');
+ expect(message).toContain('name fewer events or use "*"');
+ expect(message).not.toContain('unsubscribe');
+ });
+
+ it('does not suggest "*" to a key whose allowlist alone is over the cap', async () => {
+ // A list stored before allowedChats was bounded: its address forms exceed what one socket may hold,
+ // so even one event never fits and only a shorter list helps.
+ const chats = Array.from({ length: 2100 }, (_, index) => `62811${String(index).padStart(7, '0')}@c.us`);
+ const restricted = await connect('restricted', chats);
+ const refused = await subscribe(restricted, ['*']);
+ expect(refused).toMatchObject({ type: 'error', code: 'TOO_MANY_SUBSCRIPTIONS' });
+ const { message } = refused as { message: string };
+ expect(message).toContain('every event 4200 subscriptions');
+ expect(message).toContain('shorten the allowlist');
+ expect(message).not.toContain('use "*"');
+ expect(message).not.toContain('unsubscribe');
+ });
+
+ it('tells a subscriber that is over the cap because of what it already holds to unsubscribe first', async () => {
+ const chats = Array.from({ length: 450 }, (_, index) => `62811${String(index).padStart(7, '0')}@c.us`);
+ const restricted = await connect('restricted', chats);
+ // The wildcard subscription holds 900 rooms; four more events add 3600, each frame within the cap alone.
+ const fourEvents = ['message.received', 'message.sent', 'message.ack', 'message.revoked'];
+ const refused = await subscribe(restricted, fourEvents, 's1');
+ expect(refused).toMatchObject({ type: 'error', code: 'TOO_MANY_SUBSCRIPTIONS' });
+ expect((refused as { message: string }).message).toContain('unsubscribe first');
+ });
+
+ it('performs no chat lookups for a local stream without restricted subscribers', async () => {
+ const previous = process.env.REDIS_ENABLED;
+ process.env.REDIS_ENABLED = 'false';
+ try {
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ await flush();
+ expect(events(unrestricted)).toHaveLength(1);
+ expect(resolveIds).not.toHaveBeenCalled();
+ } finally {
+ if (previous === undefined) delete process.env.REDIS_ENABLED;
+ else process.env.REDIS_ENABLED = previous;
+ }
+ });
+
+ it('publishes the chat rooms when Redis fans out, though this node tracks no restricted socket', async () => {
+ const previous = process.env.REDIS_ENABLED;
+ process.env.REDIS_ENABLED = 'true';
+ try {
+ // A restricted socket on another replica: the adapter reaches it through its rooms, but this node
+ // never tracks it. Dropping the tracking keeps the rooms the subscribe granted.
+ const remote = await connect('remote', [PHONE]);
+ gateway.handleDisconnect(remote as unknown as Socket);
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ await flush();
+ expect(resolveIds).toHaveBeenCalledWith({ allowedChats: [PHONE] });
+ expect(events(remote)).toHaveLength(1);
+ expect(events(unrestricted)).toHaveLength(1);
+ } finally {
+ if (previous === undefined) delete process.env.REDIS_ENABLED;
+ else process.env.REDIS_ENABLED = previous;
+ }
+ });
+
+ it('resolves a phone/LID mapping learned after subscription', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(allowed)).toHaveLength(0);
+ lidPhone = '628111000111';
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(allowed)).toHaveLength(1);
+ });
+
+ it('keeps equal phone and LID digits separate without a persisted mapping', async () => {
+ const phone = await connect('phone', ['[email protected]']);
+ const lid = await connect('lid', ['123456@lid']);
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(phone)).toHaveLength(0);
+ expect(events(lid)).toHaveLength(1);
+ gateway.emitMessage('s1', { chatId: '[email protected]' });
+ await flush();
+ expect(events(phone)).toHaveLength(1);
+ expect(events(lid)).toHaveLength(1);
+ });
+
+ it('fails closed on a mapping lookup failure while retaining unrestricted delivery', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ const unrestricted = await connect('unrestricted', null);
+ mappingFails = true;
+ gateway.emitMessage('s1', { chatId: PHONE });
+ await flush();
+ expect(events(allowed)).toHaveLength(0);
+ expect(events(unrestricted)).toHaveLength(1);
+ });
+
+ it.each([false, true])('preserves session event order across slow lookups (failed edit: %s)', async failed => {
+ const allowed = await connect('allowed', [PHONE], null, '*');
+ const unrestricted = await connect('unrestricted', null, null, '*');
+ let finishFirst!: (ids: string[]) => void;
+ resolveIds
+ .mockImplementationOnce(() => new Promise<string[]>(resolve => (finishFirst = resolve)))
+ .mockImplementationOnce(() =>
+ failed ? Promise.reject(new Error('Mapping lookup unavailable')) : Promise.resolve([PHONE]),
+ );
+
+ gateway.emitMessage('s1', { chatId: PHONE, id: 'm1', body: 'original' });
+ gateway.emitMessageEdited('s1', { chatId: '123456@lid', messageId: 'm1', body: 'edited' });
+ gateway.emitMessageReaction('s1', { chatId: PHONE, messageId: 'm1', reaction: 'ok' });
+ gateway.emitMessage('s2', { chatId: PHONE, id: 'm2' });
+ await flush();
+ expect(events(allowed).map(frame => frame.payload.sessionId)).toEqual(['s2']);
+ expect(events(unrestricted).map(frame => frame.payload.event)).toEqual([
+ 'message.received',
+ 'message.edited',
+ 'message.reaction',
+ 'message.received',
+ ]);
+
+ finishFirst([PHONE]);
+ await flush();
+ expect(
+ events(allowed)
+ .filter(frame => frame.payload.sessionId === 's1')
+ .map(frame => frame.payload.event),
+ ).toEqual(
+ failed ? ['message.received', 'message.reaction'] : ['message.received', 'message.edited', 'message.reaction'],
+ );
+
+ lidPhone = '628111000111';
+ gateway.emitMessage('s1', { chatId: '123456@lid', id: 'm3' });
+ await flush();
+ expect(events(allowed).at(-1)?.payload.data.id).toBe('m3');
+ });
+
+ it('deduplicates chat rooms across wildcard and specific sessions', async () => {
+ const allowed = await connect('allowed', [PHONE], null, '*');
+ await subscribe(allowed, ['*', 'message.received']);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ gateway.emitMessage('s2', { chatId: PHONE });
+ await flush();
+ expect(events(allowed)).toHaveLength(2);
+ });
+
+ // connect() subscribes with '*', which the wildcard rooms serve. Subscribing to one named event instead
+ // leaves only the room named for that event to match, on the named session and on the wildcard session.
+ it.each<[string, string, string[]]>([
+ ['a named session', 's1', ['s1:message.received']],
+ ['the wildcard session', '*', ['s1:message.received', 's2:message.received']],
+ ])('delivers a chat event to a restricted subscriber of one named event on %s', async (_label, sessionId, sent) => {
+ const allowed = await connect('allowed', [PHONE], null, sessionId, ['message.received']);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ gateway.emitMessage('s2', { chatId: PHONE });
+ gateway.emitMessageEdited('s1', { chatId: PHONE, messageId: 'm1', body: 'edited' });
+ await flush();
+ const received = events(allowed).map(frame => `${frame.payload.sessionId}:${frame.payload.event}`);
+ expect(received.sort()).toEqual(sent);
+ });
+
+ it('grants no stream rooms to an allowlist with no chattable identities', async () => {
+ const client = await connect('invalid', ['status@broadcast', '']);
+ expect(await subscribe(client)).toMatchObject({ code: 'FORBIDDEN_EVENTS' });
+ expect([...client.rooms].filter(room => room.startsWith('session:'))).toEqual([]);
+ });
+
+ it('omits account-wide events and receipts without a chat while admitting group events', async () => {
+ const allowed = await connect('allowed', ['[email protected]']);
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitQRCode('s1', 'private-qr');
+ gateway.emitSessionStatus('s1', 'ready');
+ gateway.emitCallReceived('s1', { from: PHONE });
+ gateway.emitStatusReceived('s1', { chatId: '[email protected]' });
+ gateway.emitMessageAck('s1', { id: 'm1', messageId: 'm1', status: 'delivered', ack: 2 });
+ gateway.emitGroupJoin('s1', { groupId: '[email protected]', participantIds: [PHONE] });
+ await flush();
+ expect(events(allowed).map(frame => frame.payload.event)).toEqual(['group.join']);
+ expect(events(unrestricted)).toHaveLength(5);
+ });
+
+ it('rejects explicit account events and retains the session fence', async () => {
+ const client = await connect('allowed', [PHONE]);
+ const session = await subscribe(client, ['*'], '*');
+ expect(session).toMatchObject({ code: 'FORBIDDEN_SESSION' });
+ const account = await subscribe(client, ['session.qr']);
+ expect(account).toMatchObject({ code: 'FORBIDDEN_EVENTS' });
+ });
+
+ it('disconnects a changed chat authorization before granting more rooms', async () => {
+ const client = await connect('allowed', [PHONE]);
+ current.allowed = key('allowed', [OTHER]);
+ expect(await subscribe(client)).toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(client.disconnected).toBe(true);
+ });
+
+ it('removes chat rooms on unsubscribe and counts them against the subscription cap', async () => {
+ const client = await connect('allowed', [PHONE]);
+ await gateway.handleMessage(client as unknown as Socket, { type: 'unsubscribe', sessionId: 's1' });
+ expect([...client.rooms].filter(room => room.startsWith('session:'))).toEqual([]);
+ const many = await connect(
+ 'many',
+ Array.from({ length: 400 }, (_, i) => `${628100000000 + i}@c.us`),
+ );
+ const response = await subscribe(many, [
+ 'message.received',
+ 'message.sent',
+ 'message.ack',
+ 'message.revoked',
+ 'message.reaction',
+ 'message.edited',
+ ]);
+ expect(response).toMatchObject({ code: 'TOO_MANY_SUBSCRIPTIONS' });
+ });
+ });
diff --cc src/modules/events/events.gateway.ts
index 1f862f1e8,34e64894d..ffb8c3122
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@@ -59,9 -61,42 +61,44 @@@ import type
WSPongResponse,
} from './dto/ws-messages.dto';
import { SUBSCRIBABLE_EVENTS, buildRoomName } from './dto/ws-messages.dto';
-import type { DeliveryStatus } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { DeliveryStatus, MessageReceiptStatus } from '../../engine/interfaces/whatsapp-engine.interface';
+import { WILDCARD_EXCLUDED_EVENTS } from '../../common/utils/wildcard-events';
+ // The events a chat-restricted key may receive, each delivered only for a chat inside its allowlist.
+ // group.join_request is not one of them: it names the people asking to join, who are outside the
+ // allowed chats by definition, and the REST membership-request routes refuse these keys for that reason.
+ const CHAT_EVENTS = new Set([
+ 'message.received',
+ 'message.sent',
+ 'message.ack',
++ 'message.receipt',
+ 'message.revoked',
+ 'message.reaction',
+ 'message.edited',
+ 'group.join',
+ 'group.leave',
+ 'group.update',
+ 'presence.update',
+ 'event.response',
+ ]);
+
+ /**
+ * The frame with a `requestId` that is not a short string dropped. A reply that carried client JSON back
+ * made the transport serialize whatever structure the client nested in it, which is not the client's to
+ * choose; the handlers below then never see anything but a string or nothing.
+ */
+ function withSafeRequestId(message: WSClientMessage | null | undefined): WSClientMessage | null | undefined {
+ if (typeof message !== 'object' || message === null || Array.isArray(message)) return message;
+ const { requestId } = message as { requestId?: unknown };
+ if (requestId === undefined) return message;
+ if (typeof requestId === 'string' && requestId.length <= MAX_REQUEST_ID_LENGTH) return message;
+ return { ...message, requestId: undefined };
+ }
+
+ function chatRoom(sessionId: string, event: string, chatId: string): string {
+ return `${buildRoomName(sessionId, event)}:chat:${encodeURIComponent(chatId)}`;
+ }
+
/**
* Whether an API key may subscribe to a session's WebSocket event rooms.
* An unrestricted key (no `allowedSessions`) may subscribe to anything, including
@@@ -758,13 -811,53 +813,54 @@@ export class EventsGateway implements O
// them receives the event exactly once (Socket.IO dedups recipients per
// broadcast). Four separate .emit() calls would deliver one copy per room.
// `except` is resolved by the adapter, so the exclusion also holds across nodes with Redis.
- const broadcast = this.server
- .to(buildRoomName(sessionId, event))
- .to(buildRoomName(sessionId, '*'))
- .to(buildRoomName('*', event))
- .to(buildRoomName('*', '*'));
+ // An event in WILDCARD_EXCLUDED_EVENTS skips the two event-'*' rooms: only sockets that named it
+ // (for one session or for all) receive it.
+ const named = this.server.to(buildRoomName(sessionId, event)).to(buildRoomName('*', event));
+ const broadcast = WILDCARD_EXCLUDED_EVENTS.includes(event)
+ ? named
+ : named.to(buildRoomName(sessionId, '*')).to(buildRoomName('*', '*'));
(exceptRoom ? broadcast.except(exceptRoom) : broadcast).emit('message', eventMessage);
+ if (!CHAT_EVENTS.has(event) || data === null || typeof data !== 'object') return;
+ const value = data as Record<string, unknown>;
+ const chatId = event.startsWith('group.') ? value.groupId : value.chatId;
+ if (typeof chatId !== 'string' || !chatId.trim()) return;
+ if (
+ !isWsRedisEnabled() &&
+ !Array.from(this.socketsByKeyId.values()).some(sockets =>
+ Array.from(sockets).some(client => this.chatScope.isRestricted((client.data as { apiKey?: ApiKey }).apiKey)),
+ )
+ ) {
+ return;
+ }
+ // Expand the emitted identity using current persisted mappings, so new LID mappings work
+ // without rejoining rooms. Literal allowlist rooms also enforce the fence across Redis nodes.
+ // Resolve identities concurrently, but retain event order within each session, including
+ // after a failed lookup. Other sessions and unrestricted broadcasts remain independent.
+ const delivery = Promise.allSettled([
+ this.chatDeliveries.get(sessionId),
+ this.chatScope.idsForFilter({ allowedChats: [chatId] }),
+ ])
+ .then(([, resolved]) => {
+ if (resolved.status === 'rejected') throw resolved.reason;
+ const ids = resolved.value;
+ if (!ids?.length) return;
- const rooms = ids.flatMap(id => [
- chatRoom(sessionId, event, id),
- chatRoom(sessionId, '*', id),
- chatRoom('*', event, id),
- chatRoom('*', '*', id),
- ]);
++ const rooms = ids.flatMap(id => {
++ const namedRooms = [chatRoom(sessionId, event, id), chatRoom('*', event, id)];
++ return WILDCARD_EXCLUDED_EVENTS.includes(event)
++ ? namedRooms
++ : [...namedRooms, chatRoom(sessionId, '*', id), chatRoom('*', '*', id)];
++ });
+ this.server.to(rooms).emit('message', eventMessage);
+ })
+ .catch(error =>
+ this.logger.warn('Could not resolve chat identity for WebSocket delivery', {
+ error: error instanceof Error ? error.message : String(error),
+ }),
+ )
+ .finally(() => {
+ if (this.chatDeliveries.get(sessionId) === delivery) this.chatDeliveries.delete(sessionId);
+ });
+ this.chatDeliveries.set(sessionId, delivery);
}
/**
diff --cc src/modules/session/message-projector.service.ts
index c3f7dcae1,cdbb38aa6..d0e945b27
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@@ -22,8 -23,10 +23,11 @@@ import type { StatusUpdate } from '../s
import {
IWhatsAppEngine,
DeliveryStatus,
+ MessageReceiptEvent,
IncomingMessage,
+ InboundOutcome,
+ InboundReceipt,
+ InboundTicket,
ReactionEvent,
EditedMessage,
RevokedMessage,
diff --cc src/modules/session/session-engine-event-wiring.ts
index b52ab85ed,2d87c5a61..7157eb10b
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@@ -241,10 -245,10 +245,11 @@@ export class SessionEngineEventWiring
.persistHistoryMessages(id, engine, messages)
.catch(err => this.logger.error(`Failed to persist history messages for ${id}`, String(err)));
},
- onMessageCreate: (message): void => host.messages.handleOwnSendEcho(id, engine, message),
- onMessageAck: (messageId, status): void => host.messages.handleMessageAck(id, engine, messageId, status),
+ onMessageCreate: (message, ticket): void => host.messages.handleOwnSendEcho(id, engine, message, ticket),
+ onMessageAck: (messageId, status, chatId): void =>
+ host.messages.handleMessageAck(id, engine, messageId, status, chatId),
+ onMessageReceipt: (event): void => host.messages.handleMessageReceipt(id, engine, event),
- onMessageRevoked: (message): void => host.messages.handleMessageRevoked(id, engine, message),
+ onMessageRevoked: (message, actor): void => host.messages.handleMessageRevoked(id, engine, message, actor),
onMessageReaction: (event): void => {
if (!host.isLiveEngine(id, engine)) return;
if (!event.messageId) {
diff --cc src/modules/session/session.service.spec.ts
index 5b00c0e26,221bca6e9..23454974b
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@@ -5764,35 -6098,65 +6099,94 @@@ describe('SessionService', () =>
expect(socketPayload.ack).toBeDefined();
});
+ it('forwards a per-recipient receipt as message.receipt, identically over the socket and the webhook', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ expect(typeof callbacks.onMessageReceipt).toBe('function');
+
+ callbacks.onMessageReceipt!({
+ messageId: 'wa-out-1',
+ chatId: '[email protected]',
+ participant: '[email protected]',
+ status: 'read',
+ timestamp: 1700000000,
+ });
+ await flush();
+
+ const receiptCalls = (eventsGateway.emitMessageReceipt as jest.Mock).mock.calls as unknown[][];
+ const socketPayload = receiptCalls[0][1] as Record<string, unknown>;
+ const webhookPayload = dispatchedEvents('message.receipt')[0][2] as Record<string, unknown>;
+ expect(socketPayload).toEqual(webhookPayload);
+ expect(socketPayload).toEqual({
+ id: 'wa-out-1',
+ messageId: 'wa-out-1',
+ chatId: '[email protected]',
+ participant: '[email protected]',
+ status: 'read',
+ timestamp: 1700000000,
+ });
+ // A receipt is not the message's own tick: it never advances the stored status or fires message.ack.
+ expect(dispatchedEvents('message.ack')).toHaveLength(0);
+ });
+
+ // A webhook chatId condition matches an ack or failure only when the payload names the chat.
+ it('carries the chat an engine update names on the ack and failure events', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+
+ callbacks.onMessageAck!('wa-out-1', 'failed', '[email protected]');
+ await flush();
+
+ expect(eventsGateway.emitMessageAck).toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ expect.objectContaining({ messageId: 'wa-out-1', chatId: '[email protected]' }),
+ );
+ expect(dispatchedEvents('message.ack')[0][2]).toMatchObject({ chatId: '[email protected]' });
+ expect(dispatchedEvents('message.failed')[0][2]).toMatchObject({ chatId: '[email protected]' });
+ });
+
+ // On PostgreSQL the engine hands each emit the ticket it was admitted with. Without it the
+ // message takes the ticketless path: the chat order gate and the media memory bound stop applying.
+ describe('hands the admission ticket of an emit to the projector', () => {
+ const ticket: InboundTicket = {
+ reserve: () => true,
+ holdUntil: () => undefined,
+ drop: () => undefined,
+ revoked: false,
+ };
+
+ it('for an inbound message', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const projector = (lifecycle as unknown as { messages: MessageProjector }).messages;
+ const handle = jest.spyOn(projector, 'handleInboundMessage').mockImplementation(() => undefined);
+ const inbound = makeMessage({ fromMe: false });
+
+ callbacks.onMessage!(inbound, ticket);
+
+ expect(handle).toHaveBeenCalledWith('sess-uuid-1', mockEngine, inbound, ticket);
+ });
+
+ it('for an own-send echo', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const projector = (lifecycle as unknown as { messages: MessageProjector }).messages;
+ const handle = jest.spyOn(projector, 'handleOwnSendEcho').mockImplementation(() => undefined);
+ const echo = makeMessage({ fromMe: true });
+
+ callbacks.onMessageCreate!(echo, ticket);
+
+ expect(handle).toHaveBeenCalledWith('sess-uuid-1', mockEngine, echo, ticket);
+ });
+ });
+
+ // The Baileys history capture clears the previews of messages already revoked in the database
+ // from what this returns.
+ it('hands the revocations the projector stored for a history batch back to the engine', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const projector = (lifecycle as unknown as { messages: MessageProjector }).messages;
+ const revoked = [makeMessage({ id: 'h1', type: 'revoked', body: '' })];
+ jest.spyOn(projector, 'persistHistoryMessages').mockResolvedValue(revoked);
+
+ expect(await callbacks.onHistoryMessages!([makeMessage({ id: 'h1' })])).toBe(revoked);
+ });
+
it("reflects delivery on the stored message: 'delivered' updates status to DELIVERED (#220)", async () => {
const callbacks = await startAndCaptureCallbacks();
diff --cc src/modules/webhook/utils/deliver-once.ts
index 601fa843a,072338516..0619abdec
--- a/src/modules/webhook/utils/deliver-once.ts
+++ b/src/modules/webhook/utils/deliver-once.ts
@@@ -34,11 -33,18 +34,18 @@@ export function sanitizeCustomHeaders(c
* moment (a queued job, a direct retry, an outbox replay) runs this against a fresh row, so a removed,
* disabled or unsubscribed webhook stops receiving the event.
*/
- export function isDeliverableWebhook<T extends { active: boolean; events: string[] }>(
+ export function isDeliverableWebhook<T extends { active: boolean; events: string[]; sessionId?: string }>(
row: T | null | undefined,
event: string,
+ sessionId?: string,
): row is T {
- return !!row && row.active && Array.isArray(row.events) && subscriptionCoversEvent(row.events, event);
+ return (
+ !!row &&
+ (sessionId === undefined || row.sessionId === sessionId) &&
+ row.active &&
+ Array.isArray(row.events) &&
- (row.events.includes(event) || row.events.includes('*'))
++ subscriptionCoversEvent(row.events, event)
+ );
}
/** HMAC-SHA256 over the exact pre-serialized body, prefixed for receiver-side verification. */
diff --cc src/modules/webhook/webhook-delivery.service.ts
index 242985d2a,aef78d23e..4eaf19dad
--- a/src/modules/webhook/webhook-delivery.service.ts
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@@ -67,22 -68,18 +69,25 @@@ const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTE
/**
* How long shutdown waits for in-flight direct deliveries (and their dead-letter bookkeeping) to
- * finish before abandoning them. Default 5s; override with WEBHOOK_SHUTDOWN_DRAIN_MS.
+ * finish before abandoning them, and for an outbox replay in flight. Default 5s; override with
+ * WEBHOOK_SHUTDOWN_DRAIN_MS. Defined in shutdown-budget.ts, which sizes the kill deadline from it.
*/
- const DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS = 5000;
+ export { DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS };
+/**
+ * How long a session's answer to "which opt-in events does an active webhook name" is reused. Writes
+ * through WebhookService drop the answer at once on this node; a write on another instance (Redis
+ * deployment), or one that bypasses WebhookService, is picked up when it expires.
+ */
+const OPT_IN_SUBSCRIPTIONS_TTL_MS = 5000;
+
/**
* The result of one delivery attempt. Reported, not thrown: every delivery failure below is already
- * handled in place, so a try/catch cannot tell a delivered event from a dead-lettered one. The one
- * exception that escapes is 'ConcurrencyLimiter closed' from a retry backoff woken after shutdown;
- * only runLimited can see it, and it records the shutdown and keeps the outbox row pending.
+ * handled in place, so a try/catch cannot tell a delivered event from a dead-lettered one. Two
+ * exceptions escape, both from shutdown, and both keep the outbox row pending: 'ConcurrencyLimiter
+ * closed' from a retry backoff woken after it, which only runLimited sees and records, and the
+ * AbortError of a replay whose signal stopped its retries or its queue fallback, which reaches
+ * WebhookReconcilerService through redeliver.
* 'cancelled' is terminal like 'delivered' and must never be replayed: either a plugin suppressed the
* dispatch (nothing left the process), or a direct retry found the webhook removed, disabled or
* unsubscribed (an earlier attempt may already have been POSTed).