Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat: live group/call events, message edit, group join & settings, own profile, call reject (#842)
Yudhi Armyndharis426603e59cc0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49f782ce5..26f8c3e81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Outbound message edit.** `POST /api/sessions/:sessionId/messages/edit` edits the text of a+ message sent by the account, on both engines (whatsapp-web.js `Message.edit`, Baileys+ `sendMessage` with an `edit` key). Attempting to edit another sender's message fails with `403`,+ an unknown message/chat with `404`, and the stored record's body is updated through the same+ serialized mutation queue as inbound edit events. `message.edited` continues to cover inbound edits.+- **Live group events.** `group.join`, `group.leave`, and `group.update` are now actually+ dispatched — to webhooks (HMAC-signed, with stable idempotency keys) and to Socket.IO+ subscribers — on both engines. They were previously accepted in subscriptions but never emitted+ ("reserved"). whatsapp-web.js maps `group_join`/`group_leave`/`group_update` notifications;+ Baileys maps `group-participants.update` (add/remove) and `groups.update` (subject, description,+ announce/locked changes). On Baileys, full-metadata snapshots (emitted by the library on+ reconnect and on `GET /groups`) are filtered out so they never surface as fabricated updates;+ genuine changes replayed from an offline window are dispatched with the receipt time as their+ `timestamp` (the engine does not forward the original occurrence time).+- **Join groups & group settings.** `POST /api/sessions/:sessionId/groups/join` joins a group via+ invite code (an invalid/expired code returns a typed `400`). `GET`/`PUT+ /api/sessions/:sessionId/groups/:groupId/settings` read and update the admin-only flags+ (`announce`, `locked`) and the disappearing-message timer (`ephemeralSeconds`, Baileys only — it+ returns a documented `501` on whatsapp-web.js, which has no such API). A settings patch applies+ the timer first, so a `501` can never silently follow an already-applied flag change, and+ explicit `null` fields are rejected with `400`.+- **Own-profile management.** `PUT /api/sessions/:sessionId/profile/name`, `/status`, and+ `/picture` set the linked account's display name, about text, and profile picture on both engines.+- **Incoming-call handling.** A new `call.received` webhook + Socket.IO event fires when an+ incoming call starts ringing (both engines; stale offers replayed from an offline window and the+ account's own outgoing calls are not emitted). `POST /api/sessions/:sessionId/calls/:callId/reject`+ rejects a ringing call, and the per-session `config.autoRejectCalls: true` flag (settable at+ session creation) rejects every incoming call automatically — the event is still dispatched+ first. Unknown or expired call ids return `404`.+- **Docs: official plugin catalog is now discoverable.** The README feature table points to the+ first-party Integration Fabric plugins (Chatwoot, Typebot, …) in the+ [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) repo, and+ `docs/23-community-integrations.md` clarifies that it lists community projects only.+### Fixed- Running more than one session no longer corrupts the Chromium launch flags of every@@ -22,6 +58,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0session's healthy browser. The adapter now copies the array before appending, so theshared configuration is never mutated. Fixed in #840 — thanks @szmazhr.+- The dashboard webhook editor now offers `session.reconnect_loop` (accepted by the backend since+ #800 but never listed in the UI), and the Java/Python SDK event types now include it as well.- Typing a session name in the dashboard's **Create New Session** dialog no longerstalls after the first character. The shared `Modal` component ran its initial-focusstep inside a `useEffect` whose dependency array included `onClose`, and callers passdiff --git a/README.md b/README.mdindex 7f6dfafcc..0bfab4125 100644--- a/README.md+++ b/README.md@@ -40,6 +40,7 @@ Built on a **pluggable architecture**, OpenWA lets you select database engines (| 🖥️ **Full Dashboard** | Modern React UI for session, webhook, and API key management || 🔹 **Multi-Session Ready** | Run multiple WhatsApp sessions concurrently on one instance || 🐳 **Docker Native** | Production-ready with zero configuration |+| 🧩 **Official Plugins** | Chatwoot, Typebot & more as sandboxed plugins on the Integration Fabric — [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) || 🔗 **n8n Integration** | Community nodes for workflow automation || 🧩 **Community Adapters** | Third-party integrations (e.g. ioBroker) — see [docs](./docs/23-community-integrations.md) |@@ -108,7 +109,7 @@ For any deployment where ethical, legal, or regulatory compliance matters (healt| Text Messages | ✅ | Send/receive text messages || Media Messages | ✅ | Images, videos, documents, audio || Message Reactions | ✅ | React to messages with emoji |-| Message Editing | ✅ | Live `message.edited` events on both engines |+| Message Editing | ✅ | Send edits + live `message.edited` events on both engines || Bulk Messaging | ✅ | Send to multiple recipients || Message Status | ✅ | Track delivery and read receipts |@@ -116,7 +117,9 @@ For any deployment where ethical, legal, or regulatory compliance matters (healt| Feature | Status | Description || ------------------- | ------ | ---------------------------------- |-| Groups API | ✅ | Create, manage, and message groups |+| Groups API | ✅ | Create, manage, join (invite code), and configure groups |+| Profile Management | ✅ | Set own display name, about text, and profile picture |+| Call Handling | ✅ | `call.received` events, reject calls, per-session auto-reject || Channels/Newsletter | ✅ | WhatsApp Channels support || Labels Management | ✅ | Organize chats with labels || Proxy Support | ✅ | Per-session proxy configuration |diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex 3242a862f..2166da6c0 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -100,9 +100,11 @@ const availableEventNames = ['session.qr','session.authenticated','session.disconnected',+ 'session.reconnect_loop','group.join','group.leave','group.update',+ 'call.received','*',] as const;diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex d3242f670..ade8146bb 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -364,7 +364,8 @@ CREATE TABLE webhooks ("session.reconnect_loop","group.join","group.leave",- "group.update"+ "group.update",+ "call.received"]```diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 12e97c5ca..2064074e1 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1336,6 +1336,40 @@ After the engine delete, the stored message body is cleared and its `type` set t**Errors:** `400` session not active / message not found / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error+#### POST /api/sessions/:sessionId/messages/edit++Edit the text of a message sent by this account; also updates the stored record's body.++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |++**Request body** — `EditMessageDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| chatId | string | Yes | non-empty | Chat containing the message |+| messageId | string | Yes | non-empty | Message to edit (the send response's `messageId`) |+| body | string | Yes | non-empty, ≤ 4096 chars | New text content |++```json+{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "body": "Corrected text" }+```++**Response** `200`++The edited message keeps its original id.++```json+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1760000000 }+```++**Errors:** `400` session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` message not found · `500` engine error (e.g. editing another account's message, which WhatsApp forbids)+#### POST /api/sessions/:sessionId/messages/send-bulkSend messages to multiple recipients as an async batch — returns immediately and processes in the background.@@ -2022,6 +2056,92 @@ Revoke the current invite code and generate a new one.**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role+#### POST /api/sessions/:sessionId/groups/join++Join a group via an invite code (the part after `https://chat.whatsapp.com/`).++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |++**Request body** — `JoinGroupDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| inviteCode | string | Yes | non-empty | Group invite code |++```json+{ "inviteCode": "XyZ987654321" }+```++**Response** `200`++```json+{ "success": true, "groupId": "[email protected]" }+```++**Errors:** `400` session is not started / invalid invite code · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role++#### GET /api/sessions/:sessionId/groups/:groupId/settings++Read the group's admin-only settings and disappearing-message timer.++**Auth:** API key++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |+| groupId | string | Group ID |++**Response** `200`++`announce` = only admins can send messages; `locked` = only admins can edit group info. `ephemeralSeconds` is present only when the engine reports a disappearing-message timer.++```json+{ "announce": false, "locked": false, "ephemeralSeconds": 604800 }+```++**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `404` group not found++#### PUT /api/sessions/:sessionId/groups/:groupId/settings++Update group settings. Each present field maps to one engine call; absent fields stay untouched. The caller must be a group admin for the change to take effect.++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |+| groupId | string | Group ID |++**Request body** — `GroupSettingsDto` (at least one field required)++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| announce | boolean | No | boolean | Only admins can send messages |+| locked | boolean | No | boolean | Only admins can edit group info |+| ephemeralSeconds | integer | No | ≥ 0 | Disappearing-message timer in seconds (`0` disables). **Baileys only** — whatsapp-web.js returns `501` |++```json+{ "announce": true, "ephemeralSeconds": 86400 }+```++**Response** `200`++```json+{ "success": true, "message": "Group settings updated" }+```++**Errors:** `400` session is not started / empty patch / unknown body field · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `501` `ephemeralSeconds` on the whatsapp-web.js engine (library limitation)+### 6.4.5 Message TemplatesReusable message templates scoped to a session, with `{{variable}}` placeholders rendered at send time. All routes are nested under `/api/sessions/:sessionId/templates` and require an **OPERATOR** key. The `sessionId` is stored on the template but is **not** validated against an existing session in these handlers.@@ -2932,7 +3052,7 @@ Webhooks are configured per session and managed under `/api/sessions/:sessionId/Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). 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.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `group.join`, `group.leave`, `group.update`. The `group.*` events are **reserved** — accepted and validated but never dispatched (no engine emit source).+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`, `group.join`, `group.leave`, `group.update`, `call.received`. All of them are actively dispatched by the engines.#### GET /api/sessions/:sessionId/webhooks@@ -4512,6 +4632,83 @@ contract surface for a future plugin provider whose `search()` throws `ServiceUn> overridden via the query — there is no `sessionIds` query parameter, and `SearchService` overwrites> any session scope at the provider boundary.+### 6.4.13 Profile (own account)++Manage the linked account's own profile. All routes are nested under `/api/sessions/:sessionId/profile` and require an **OPERATOR** key.++#### PUT /api/sessions/:sessionId/profile/name++Set the account display name (max 25 chars).++**Auth:** API key (OPERATOR)++```json+{ "name": "ACME Support" }+```++**Response** `200` — `{ "success": true, "message": "Profile name updated" }`++**Errors:** `400` session is not started / invalid name · `401` · `403` · `500` engine refused the change++#### PUT /api/sessions/:sessionId/profile/status++Set the account about/status text (max 139 chars; empty string clears it).++**Auth:** API key (OPERATOR)++```json+{ "status": "We reply within one business day" }+```++**Response** `200` — `{ "success": true, "message": "Profile status updated" }`++**Errors:** `400` session is not started / status too long · `401` · `403`++#### PUT /api/sessions/:sessionId/profile/picture++Set the account profile picture from a URL or base64 image (same media DTO conventions as message sends, §6.3).++**Auth:** API key (OPERATOR)++```json+{ "url": "https://example.com/avatar.png" }+```++or++```json+{ "base64": "iVBORw0KGgo...", "mimetype": "image/png" }+```++**Response** `200` — `{ "success": true, "message": "Profile picture updated" }`++**Errors:** `400` neither `url` nor `base64` provided / base64 without `mimetype` · `401` · `403` · `500` engine refused the change++### 6.4.14 Calls++Incoming-call management. A `call.received` webhook/socket event (§6.6) announces an incoming ringing call and carries the `callId` used below.++#### POST /api/sessions/:sessionId/calls/:callId/reject++Reject a currently ringing incoming call. Only a live call can be rejected — the id is valid while the call rings (a short server-side cache); afterwards it expires.++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |+| callId | string | Call ID from the `call.received` event |++**Request body** — none.++**Response** `200` — `{ "success": true }`++**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `404` call not found or no longer ringing++> **Auto-reject per session.** Set `"config": { "autoRejectCalls": true }` when creating a session to have the server reject every incoming call automatically — the `call.received` event is still dispatched first, so automations keep full visibility.+## 6.5 Real-time API (WebSocket)Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.@@ -4603,11 +4800,15 @@ session.statussession.qrsession.authenticatedsession.disconnected+group.join+group.leave+group.update+call.received```A subscribe request whose `events` array contains no recognized name (after filtering) is rejected with `INVALID_EVENTS`. Unknown names mixed with valid ones are silently dropped; the `subscribed` reply echoes only the accepted events.-> **`group.*` events are NOT subscribable on the socket.** They have no engine emit source and are never delivered over Socket.IO (they remain reserved only on the webhook side).+> `message.failed` and `session.reconnect_loop` are webhook-only — they are not subscribable on the socket.### Wildcards and scoping@@ -4677,10 +4878,16 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `session.disconnected` | The session disconnects | `{ 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 }` || `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `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 |+| `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?` |+| `call.received` | An incoming voice/video call starts ringing | `{ callId, from, isVideo, isGroup, timestamp }` — `callId` is the id to pass to `POST /sessions/:sessionId/calls/:callId/reject` |> **`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).-> **Reserved but not emitted.** `group.join`, `group.leave`, and `group.update` are accepted in a webhook's `events` list (and have reserved idempotency-key formats), but **no code path currently emits them** — registering for them is harmless but they will never be delivered. Likewise there is **no** `contact.update` or `presence.update` event.+> There is **no** `contact.update` or `presence.update` event, and no `call.accepted` / `call.terminated` lifecycle event yet — only `call.received` is emitted.++> **Group-event timing caveat (Baileys).** Membership/metadata changes that occurred while a Baileys session was offline are replayed by WhatsApp on reconnect and are dispatched like live events — but the engine does not forward their original occurrence time, so they carry the **receipt time** as `timestamp`. Treat `group.*` payloads as change notifications rather than a precise clock; stale offline *calls* are never emitted this way (they are filtered by the `offline` flag).### Delivery semantics — at-least-once@@ -4736,6 +4943,9 @@ Every delivery includes:- `session.status`: `sess_{sessionId}_{status}_{occurredAt}`- `session.authenticated`: `auth_{sessionId}_{hash(data)}_{occurredAt}`- `session.disconnected`: `disc_{sessionId}_{hash(reason)}_{occurredAt}`+- `group.join` / `group.leave`: `grp_{groupId}_{hash(participantIds)}_{join|leave}_{occurredAt}`+- `group.update`: `grp_{groupId}_update_{hash(changes)}_{occurredAt}`+- `call.received`: `call_{sessionId}_{callId}` (a call id is unique per call, so no `occurredAt` salt)Recurring lifecycle events (and `message.reaction` / `message.edited`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji, or editing the same message multiple times — so they are salted with an `occurredAt` timestamp captured **once per dispatch and reused across that dispatch's retries**. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex ee7b6384f..4a0e4df59 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -998,10 +998,13 @@ available_events:- session.disconnected # Session disconnected- session.reconnect_loop # Every 5th consecutive reconnect attempt (payload: sessionId, attempts, nextDelayMs)- # Groups (reserved but NOT currently emitted — accepted in events list, never delivered)- - group.join # reserved, not emitted- - group.leave # reserved, not emitted- - group.update # reserved, not emitted+ # Groups+ - group.join # Participant(s) added/joined+ - group.leave # Participant(s) left/removed+ - group.update # Group subject/description/announce/locked changed++ # Calls+ - call.received # Incoming call ringing (payload: callId, from, isVideo, isGroup, timestamp)```**Q: Webhook payload format?**diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.mdindex 718d5e00f..b80c1815f 100644--- a/docs/22-n8n-integration.md+++ b/docs/22-n8n-integration.md@@ -87,10 +87,10 @@ Start workflows when WhatsApp events occur.| `session.authenticated` | Session logged in (phone available) | Startup notifications || `session.disconnected` | Session lost connection | Alert monitoring || `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting |--> **Reserved:** `group.join`, `group.leave`, and `group.update` are accepted by the-> subscription API but are not emitted yet — don't depend on them until a release notes-> them as live.+| `group.join` | Participant(s) joined a group | Welcome messages |+| `group.leave` | Participant(s) left a group | Churn tracking |+| `group.update` | Group subject/description/settings changed | Group administration |+| `call.received` | Incoming call started ringing | Auto-reject + auto-reply bots |#### How It Worksdiff --git a/docs/23-community-integrations.md b/docs/23-community-integrations.mdindex b718fbbfb..9a6f03146 100644--- a/docs/23-community-integrations.md+++ b/docs/23-community-integrations.md@@ -2,6 +2,10 @@Third-party integrations and adapters built by the community on top of OpenWA's REST API.+> **Looking for Chatwoot, Typebot, and other first-party integrations?** Those ship as official+> sandboxed plugins on the Integration Fabric — see the [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins)+> catalog. This page lists only community-built projects.+> ⚠️ **These projects are community-maintained and are not affiliated with or endorsed by OpenWA.**> They may lag behind OpenWA API changes. Verify compatibility and review the source before using> them in production.diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex fd607f377..5a91ceea2 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -127,8 +127,9 @@ declares a `tier` (`read` | `write`) and, for writes, a required role.| **Webhook** | list, get (read-only) | — |**Deliberately excluded from the surface** (not exposed as tools): session lifecycle-(create/delete/start/stop/force-kill), chat delete, bulk send, message delete, group-leave/remove/promote/demote/invite-revoke, all API-key management, all plugin management,+(create/delete/start/stop/force-kill), chat delete, bulk send, message delete, message edit, group+leave/remove/promote/demote/invite-revoke/join, group settings writes, all own-profile writes+(name/status/picture), call reject, all API-key management, all plugin management,infrastructure import/export/restart, settings writes, and webhook create/update/delete.These are destructive, privileged, or have no agent use case.diff --git a/docs/engine-capability-matrix.md b/docs/engine-capability-matrix.mdindex 19f416b7f..ca67b31bb 100644--- a/docs/engine-capability-matrix.md+++ b/docs/engine-capability-matrix.md@@ -22,7 +22,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins## Unwired-capability inventory-14 of the 71 interface methods are `not-available` on at least one adapter (19 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.+15 of the 80 interface methods are `not-available` on at least one adapter (20 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.### Channels / Newsletter@@ -137,16 +137,17 @@ These are honestly out of reach of a clean adapter wiring because the installed- `getContactStatus` / `getContactStatuses` — `fetchStatus` returns the *about* text, not 24h stories; stories only surface as `status@broadcast` messages. Needs an OpenWA-side story accumulator.- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).-**wwjs (5 cells):**+**wwjs (6 cells):**- `getCatalog` / `getProducts` / `getProduct` — no catalog API at all (`index.d.ts` 0 hits; `Product` is inbound-only).- `sendProduct` — no outbound product content type.- `sendCatalog` — no outbound catalog content type.+- `setGroupEphemeral` — no disappearing-timer setter in whatsapp-web.js 1.34.7 (`ephemeralDuration` exists only as a createGroup option). Baileys: `groupToggleEphemeral`.---## Snapshot summary-- **71** interface methods, **142** adapter-cells (71 × 2 engines).-- **123** supported cells; **19** not-available cells across **14** methods.-- Of the 19 not-available cells: **5 adapter-gaps** (fixable) + **14 library-limitations** + **0 uncertain**.+- **80** interface methods, **160** adapter-cells (80 × 2 engines).+- **140** supported cells; **20** not-available cells across **15** methods.+- Of the 20 not-available cells: **5 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.- **3 phantom-support rows** (wwjs `getCatalog`/`getProducts`/`getProduct` — they stub without throwing, so the drift gate's throw-heuristic cannot see them; the matrix is the source of truth for these).diff --git a/openapi.json b/openapi.jsonindex aaa13fe21..db7c3a45f 100644--- a/openapi.json+++ b/openapi.json@@ -2016,6 +2016,54 @@]}},+ "/api/sessions/{sessionId}/messages/edit": {+ "post": {+ "operationId": "MessageController_edit",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EditMessageDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Message edited",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessageResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session not active or invalid request"+ },+ "404": {+ "description": "Message not found"+ }+ },+ "summary": "Edit the text of a message sent by this account",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/send-bulk": {"post": {"operationId": "MessageController_sendBulk",@@ -2991,6 +3039,126 @@]}},+ "/api/sessions/{sessionId}/groups/join": {+ "post": {+ "operationId": "GroupController_join",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/JoinGroupDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Joined the group"+ }+ },+ "summary": "Join a group via invite code",+ "tags": [+ "groups"+ ]+ }+ },+ "/api/sessions/{sessionId}/groups/{groupId}/settings": {+ "get": {+ "operationId": "GroupController_getSettings",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "required": true,+ "in": "path",+ "description": "Group ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Group settings"+ },+ "404": {+ "description": "Group not found"+ }+ },+ "summary": "Get group settings (announce / locked / ephemeral timer)",+ "tags": [+ "groups"+ ]+ },+ "put": {+ "operationId": "GroupController_updateSettings",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "required": true,+ "in": "path",+ "description": "Group ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GroupSettingsDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Group settings updated"+ },+ "400": {+ "description": "No setting provided"+ },+ "501": {+ "description": "The active engine does not support a requested setting"+ }+ },+ "summary": "Update group settings (announce / locked / ephemeral timer)",+ "tags": [+ "groups"+ ]+ }+ },"/api/sessions/{sessionId}/groups": {"post": {"operationId": "GroupController_create",@@ -3390,6 +3558,154 @@]}},+ "/api/sessions/{sessionId}/profile/name": {+ "put": {+ "operationId": "ProfileController_setName",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetProfileNameDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Profile name updated"+ }+ },+ "summary": "Set the account display name",+ "tags": [+ "profile"+ ]+ }+ },+ "/api/sessions/{sessionId}/profile/status": {+ "put": {+ "operationId": "ProfileController_setStatus",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetProfileStatusDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Profile status updated"+ }+ },+ "summary": "Set the account about/status text",+ "tags": [+ "profile"+ ]+ }+ },+ "/api/sessions/{sessionId}/profile/picture": {+ "put": {+ "operationId": "ProfileController_setPicture",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetProfilePictureDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Profile picture updated"+ },+ "400": {+ "description": "Neither url nor base64 provided, or base64 without mimetype"+ }+ },+ "summary": "Set the account profile picture (URL or base64 image)",+ "tags": [+ "profile"+ ]+ }+ },+ "/api/sessions/{sessionId}/calls/{callId}/reject": {+ "post": {+ "operationId": "CallController_reject",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "callId",+ "required": true,+ "in": "path",+ "description": "Call ID from the call.received event",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Call rejected"+ },+ "400": {+ "description": "Session is not started"+ },+ "404": {+ "description": "Call not found or no longer ringing"+ }+ },+ "summary": "Reject a ringing incoming call",+ "tags": [+ "calls"+ ]+ }+ },"/api/sessions/{sessionId}/labels": {"get": {"operationId": "LabelController_findAll",@@ -5691,7 +6007,7 @@},"config": {"type": "object",- "description": "Session configuration options",+ "description": "Session configuration options. Set autoRejectCalls (boolean, default false) to automatically reject incoming calls — the call.received event is still emitted.","example": {"autoReconnect": true}@@ -5930,6 +6246,7 @@"group.join","group.leave","group.update",+ "call.received","*"]}@@ -6074,6 +6391,7 @@"group.join","group.leave","group.update",+ "call.received","*"]}@@ -6462,6 +6780,27 @@"messageId"]},+ "EditMessageDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ },+ "body": {+ "type": "string",+ "description": "New text body for the message",+ "maxLength": 4096+ }+ },+ "required": [+ "chatId",+ "messageId",+ "body"+ ]+ },"BulkMediaDto": {"type": "object","properties": {@@ -6907,6 +7246,37 @@}}},+ "JoinGroupDto": {+ "type": "object",+ "properties": {+ "inviteCode": {+ "type": "string",+ "description": "Group invite code (the token from a https://chat.whatsapp.com/<code> link)",+ "maxLength": 128+ }+ },+ "required": [+ "inviteCode"+ ]+ },+ "GroupSettingsDto": {+ "type": "object",+ "properties": {+ "announce": {+ "type": "boolean",+ "description": "Only admins can send messages (announce group)"+ },+ "locked": {+ "type": "boolean",+ "description": "Only admins can edit group info (locked group)"+ },+ "ephemeralSeconds": {+ "type": "number",+ "description": "Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d)",+ "minimum": 0+ }+ }+ },"CreateGroupDto": {"type": "object","properties": {@@ -6969,6 +7339,51 @@"description"]},+ "SetProfileNameDto": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "New display name (WhatsApp limit: 25 characters)",+ "maxLength": 25+ }+ },+ "required": [+ "name"+ ]+ },+ "SetProfileStatusDto": {+ "type": "object",+ "properties": {+ "status": {+ "type": "string",+ "description": "New about/status text (may be empty to clear it; WhatsApp limit: 139 characters)",+ "maxLength": 139+ }+ },+ "required": [+ "status"+ ]+ },+ "SetProfilePictureDto": {+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "description": "Image URL (http/https)",+ "example": "https://example.com/avatar.jpg"+ },+ "base64": {+ "type": "string",+ "description": "Base64 encoded image data"+ },+ "mimetype": {+ "type": "string",+ "description": "Image MIME type (required when using base64)",+ "example": "image/jpeg"+ }+ }+ },"SendTextStatusDto": {"type": "object","properties": {diff --git a/sdk/README.md b/sdk/README.mdindex 009b3345d..a897ca24f 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -25,9 +25,9 @@ All five SDKs expose the same fluent resource surface:| Resource | Methods || ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `sessions` | list, get, create, delete, start, stop, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, history, reactions, sendBulk, batchStatus, cancelBatch |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, editMessage, history, reactions, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, phone, block, unblock |-| `groups` | list, get, create, add/remove/promote/demoteParticipants, setSubject, setDescription, leave, inviteCode, revokeInviteCode |+| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode || `webhooks` | list, get, create, update, delete, test || `chats` | list, markRead, markUnread, delete, sendState || `labels` | list, get, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |@@ -36,6 +36,8 @@ All five SDKs expose the same fluent resource surface:| `status` | list, fromContact, sendText, sendImage, sendVideo, delete _(Stories)_ || `search` | search _(Operator)_ || `templates`| list, get, create, update, delete |+| `profile` | setProfileName, setProfileStatus, setProfilePicture _(OPERATOR)_ |+| `calls` | rejectCall _(OPERATOR)_ || `health` | check, live, ready |> ⚠️ Endpoints requiring an `OPERATOR`-level API key are noted in the inlinediff --git a/sdk/go/README.md b/sdk/go/README.mdindex 932291dba..7b245b7c9 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -53,7 +53,7 @@ func main() {`client.Sessions`, `client.Messages`, `client.Contacts`, `client.Groups`,`client.Webhooks`, `client.Chats`, `client.Status`, `client.Labels`,`client.Channels`, `client.Catalog`, `client.Templates`, `client.Health`,- `client.Search`, `client.Auth`.+ `client.Search`, `client.Auth`, `client.Profile`, `client.Calls`.- **Context-first** — every network method takes `ctx context.Context` as itsfirst argument; the context bounds the request (and any retries).- **Functional options + DI** — inject dependencies instead of relying ondiff --git a/sdk/go/calls.go b/sdk/go/calls.gonew file mode 100644index 000000000..16625f91f--- /dev/null+++ b/sdk/go/calls.go@@ -0,0 +1,24 @@+package openwa++import "context"++// CallsService acts on incoming voice/video calls.+// Backed by src/modules/call/call.controller.ts.+type CallsService struct{ client *Client }++func (s *CallsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/calls"+}++// RejectCall rejects a ringing incoming call; callID comes from the+// call.received event (CallReceivedPayload.CallID). A call can only be+// rejected while it is still ringing — otherwise the server responds 404.+// Requires an OPERATOR-level key.+func (s *CallsService) RejectCall(ctx context.Context, sessionID, callID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(callID)+"/reject", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/client.go b/sdk/go/client.goindex 62ffb285d..f6ef1e5fb 100644--- a/sdk/go/client.go+++ b/sdk/go/client.go@@ -67,6 +67,8 @@ type Client struct {Health *HealthServiceSearch *SearchServiceAuth *AuthService+ Profile *ProfileService+ Calls *CallsService}var localhostHosts = map[string]bool{"localhost": true, "127.0.0.1": true, "::1": true}@@ -146,6 +148,8 @@ func New(baseURL, apiKey string, opts ...Option) (*Client, error) {c.Health = &HealthService{client: c}c.Search = &SearchService{client: c}c.Auth = &AuthService{client: c}+ c.Profile = &ProfileService{client: c}+ c.Calls = &CallsService{client: c}return c, nil}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex c1ee0e0da..ecf0bfb0c 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -738,3 +738,311 @@ func TestChannelMessagesDecodeEngineShape(t *testing.T) {t.Errorf("MediaURL: %q", msg.MediaURL)}}++func TestEditMessage(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"messageId":"m1","timestamp":1700000001}`}+ c := newTestClient(t, rt)++ res, err := c.Messages.EditMessage(context.Background(), "s1", EditMessageRequest{+ ChatID: "[email protected]",+ MessageID: "m1",+ Body: "edited",+ })+ if err != nil {+ t.Fatalf("EditMessage: %v", err)+ }+ if res.MessageID != "m1" || res.Timestamp != 1700000001 {+ t.Fatalf("unexpected response: %+v", res)+ }++ wantPath := "/api/sessions/s1/messages/edit"+ if got := rt.lastReq.URL.Path; got != wantPath {+ t.Fatalf("path = %q, want %q", got, wantPath)+ }+ if rt.lastReq.Method != "POST" {+ t.Fatalf("method = %q, want POST", rt.lastReq.Method)+ }++ var sent EditMessageRequest+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent.ChatID != "[email protected]" || sent.MessageID != "m1" || sent.Body != "edited" {+ t.Fatalf("sent body = %+v", sent)+ }+}++func TestEditMessageNotFound(t *testing.T) {+ rt := &recordTransport{+ status: 404,+ body: `{"statusCode":404,"message":"Message not found","error":"Not Found"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Messages.EditMessage(context.Background(), "s1", EditMessageRequest{+ ChatID: "x", MessageID: "nope", Body: "y",+ })+ if !errors.Is(err, ErrNotFound) {+ t.Fatalf("errors.Is ErrNotFound = false for %v", err)+ }+}++func TestJoinGroup(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true,"groupId":"[email protected]"}`}+ c := newTestClient(t, rt)++ res, err := c.Groups.JoinGroup(context.Background(), "s1", JoinGroupRequest{InviteCode: "abc123"})+ if err != nil {+ t.Fatalf("JoinGroup: %v", err)+ }+ if !res.Success || res.GroupID != "[email protected]" {+ t.Fatalf("unexpected response: %+v", res)+ }++ var sent JoinGroupRequest+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent.InviteCode != "abc123" {+ t.Fatalf("sent body = %+v", sent)+ }+}++func TestGetGroupSettings(t *testing.T) {+ // ephemeralSeconds is absent when the engine does not report it — it must+ // decode as nil, not as a zero-valued present field.+ rt := &recordTransport{status: 200, body: `{"announce":true,"locked":false}`}+ c := newTestClient(t, rt)++ got, err := c.Groups.GetGroupSettings(context.Background(), "s1", "g1")+ if err != nil {+ t.Fatalf("GetGroupSettings: %v", err)+ }+ if got.Announce == nil || !*got.Announce {+ t.Errorf("Announce: %+v", got.Announce)+ }+ if got.Locked == nil || *got.Locked {+ t.Errorf("Locked: %+v", got.Locked)+ }+ if got.EphemeralSeconds != nil {+ t.Errorf("EphemeralSeconds should be nil when absent, got %+v", *got.EphemeralSeconds)+ }+}++// An update must only touch the settings that were set — unset pointer fields+// are omitted from the body so the server leaves them alone.+func TestUpdateGroupSettingsOmitsUnsetFields(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true,"message":"Group settings updated"}`}+ c := newTestClient(t, rt)++ res, err := c.Groups.UpdateGroupSettings(context.Background(), "s1", "g1", GroupSettings{Announce: Ptr(true)})+ if err != nil {+ t.Fatalf("UpdateGroupSettings: %v", err)+ }+ if !res.Success || res.Message != "Group settings updated" {+ t.Fatalf("unexpected response: %+v", res)+ }+ if rt.lastReq.Method != "PUT" {+ t.Fatalf("method = %q, want PUT", rt.lastReq.Method)+ }++ var sent map[string]any+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent["announce"] != true {+ t.Fatalf("announce = %v", sent["announce"])+ }+ if _, ok := sent["locked"]; ok {+ t.Fatal("unset locked should be omitted from body")+ }+ if _, ok := sent["ephemeralSeconds"]; ok {+ t.Fatal("unset ephemeralSeconds should be omitted from body")+ }+}++// Setting ephemeralSeconds on the whatsapp-web.js engine surfaces as 501.+func TestUpdateGroupSettingsNotImplemented(t *testing.T) {+ rt := &recordTransport{+ status: 501,+ body: `{"statusCode":501,"message":"Engine does not support ephemeral messages","error":"Not Implemented"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Groups.UpdateGroupSettings(context.Background(), "s1", "g1", GroupSettings{EphemeralSeconds: Ptr(86400)})+ if !errors.Is(err, ErrNotImplemented) {+ t.Fatalf("errors.Is ErrNotImplemented = false for %v", err)+ }+}++func TestSetProfileName(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true,"message":"Profile name updated"}`}+ c := newTestClient(t, rt)++ res, err := c.Profile.SetProfileName(context.Background(), "s1", SetProfileNameRequest{Name: "Acme"})+ if err != nil {+ t.Fatalf("SetProfileName: %v", err)+ }+ if !res.Success {+ t.Fatalf("unexpected response: %+v", res)+ }++ wantPath := "/api/sessions/s1/profile/name"+ if got := rt.lastReq.URL.Path; got != wantPath {+ t.Fatalf("path = %q, want %q", got, wantPath)+ }+ var sent SetProfileNameRequest+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent.Name != "Acme" {+ t.Fatalf("sent body = %+v", sent)+ }+}++// An empty status clears the about text — the field must still be sent.+func TestSetProfileStatusEmptyClears(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true,"message":"Profile status updated"}`}+ c := newTestClient(t, rt)++ if _, err := c.Profile.SetProfileStatus(context.Background(), "s1", SetProfileStatusRequest{Status: ""}); err != nil {+ t.Fatalf("SetProfileStatus: %v", err)+ }+ if !strings.Contains(string(rt.lastRaw), `"status":""`) {+ t.Fatalf("empty status must be sent, body = %s", rt.lastRaw)+ }+}++// The picture body is either {url} or {base64, mimetype} — never a mix, and+// empty alternates are omitted.+func TestSetProfilePictureBody(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true,"message":"Profile picture updated"}`}+ c := newTestClient(t, rt)++ if _, err := c.Profile.SetProfilePicture(context.Background(), "s1", SetProfilePictureRequest{+ Base64: "aW1hZ2U=",+ Mimetype: "image/jpeg",+ }); err != nil {+ t.Fatalf("SetProfilePicture: %v", err)+ }++ var sent map[string]any+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent["base64"] != "aW1hZ2U=" || sent["mimetype"] != "image/jpeg" {+ t.Fatalf("sent body = %v", sent)+ }+ if _, ok := sent["url"]; ok {+ t.Fatal("empty url should be omitted from body")+ }+}++func TestRejectCall(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"success":true}`}+ c := newTestClient(t, rt)++ res, err := c.Calls.RejectCall(context.Background(), "s1", "call-1")+ if err != nil {+ t.Fatalf("RejectCall: %v", err)+ }+ if !res.Success {+ t.Fatalf("unexpected response: %+v", res)+ }++ wantPath := "/api/sessions/s1/calls/call-1/reject"+ if got := rt.lastReq.URL.Path; got != wantPath {+ t.Fatalf("path = %q, want %q", got, wantPath)+ }+ if rt.lastReq.Method != "POST" {+ t.Fatalf("method = %q, want POST", rt.lastReq.Method)+ }+}++// A call that is no longer ringing surfaces as 404.+func TestRejectCallNotRinging(t *testing.T) {+ rt := &recordTransport{+ status: 404,+ body: `{"statusCode":404,"message":"Call not found or no longer ringing","error":"Not Found"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Calls.RejectCall(context.Background(), "s1", "call-1")+ if !errors.Is(err, ErrNotFound) {+ t.Fatalf("errors.Is ErrNotFound = false for %v", err)+ }+}++// The Event* constants are the wire values of the server's WEBHOOK_EVENTS+// catalog — a typo here silently subscribes to nothing.+func TestWebhookEventWireValues(t *testing.T) {+ want := map[WebhookEvent]string{+ EventMessageReceived: "message.received",+ EventMessageSent: "message.sent",+ EventMessageAck: "message.ack",+ EventMessageFailed: "message.failed",+ EventMessageRevoked: "message.revoked",+ EventMessageReaction: "message.reaction",+ EventMessageEdited: "message.edited",+ EventSessionStatus: "session.status",+ EventSessionQR: "session.qr",+ EventSessionAuthenticated: "session.authenticated",+ EventSessionDisconnected: "session.disconnected",+ EventSessionReconnectLoop: "session.reconnect_loop",+ EventGroupJoin: "group.join",+ EventGroupLeave: "group.leave",+ EventGroupUpdate: "group.update",+ EventCallReceived: "call.received",+ EventAll: "*",+ }+ for got, w := range want {+ if got != w {+ t.Errorf("event constant = %q, want %q", got, w)+ }+ }+}++// The group event payload decodes join/leave (participants, no changes) and+// update (changes delta, empty participants) shapes alike.+func TestGroupEventPayloadDecodes(t *testing.T) {+ join := `{"groupId":"[email protected]","actorId":"[email protected]","participantIds":["[email protected]"],"timestamp":1700000000}`+ var j GroupEventPayload+ if err := json.Unmarshal([]byte(join), &j); err != nil {+ t.Fatalf("join payload: %v", err)+ }+ if j.GroupID != "[email protected]" || j.ActorID == nil || *j.ActorID != "[email protected]" {+ t.Fatalf("join decode: %+v", j)+ }+ if len(j.ParticipantIDs) != 1 || j.ParticipantIDs[0] != "[email protected]" {+ t.Fatalf("join participants: %+v", j.ParticipantIDs)+ }+ if j.Changes != nil {+ t.Fatalf("join should carry no changes, got %+v", j.Changes)+ }++ update := `{"groupId":"[email protected]","participantIds":[],"changes":{"subject":"New","locked":true},"timestamp":1700000001}`+ var u GroupEventPayload+ if err := json.Unmarshal([]byte(update), &u); err != nil {+ t.Fatalf("update payload: %v", err)+ }+ if u.Changes == nil || u.Changes.Subject == nil || *u.Changes.Subject != "New" {+ t.Fatalf("update changes: %+v", u.Changes)+ }+ if u.Changes.Locked == nil || !*u.Changes.Locked {+ t.Fatalf("update locked: %+v", u.Changes.Locked)+ }+ if u.Changes.Announce != nil || u.Changes.Description != nil {+ t.Fatalf("unchanged settings must stay nil: %+v", u.Changes)+ }+}++func TestCallReceivedPayloadDecodes(t *testing.T) {+ body := `{"callId":"call-1","from":"[email protected]","isVideo":true,"isGroup":false,"timestamp":1700000000}`+ var p CallReceivedPayload+ if err := json.Unmarshal([]byte(body), &p); err != nil {+ t.Fatalf("call payload: %v", err)+ }+ if p.CallID != "call-1" || p.From != "[email protected]" || !p.IsVideo || p.IsGroup || p.Timestamp != 1700000000 {+ t.Fatalf("call decode: %+v", p)+ }+}diff --git a/sdk/go/example_test.go b/sdk/go/example_test.goindex e5761720d..c60283474 100644--- a/sdk/go/example_test.go+++ b/sdk/go/example_test.go@@ -60,3 +60,23 @@ func ExampleWithRetry() {)_ = client}++func ExampleClient_webhookEvents() {+ client, _ := openwa.New("http://localhost:2785", "owa_k1_…")++ // Subscribe to the group and call events with the Event* constants — they+ // are the exact wire values, so a typo is a compile error, not a silent+ // no-delivery.+ _, err := client.Webhooks.Create(context.Background(), "my-session", openwa.CreateWebhookRequest{+ URL: "https://example.com/hook",+ Events: []string{+ openwa.EventGroupJoin,+ openwa.EventGroupLeave,+ openwa.EventGroupUpdate,+ openwa.EventCallReceived,+ },+ })+ if err != nil {+ log.Fatal(err)+ }+}diff --git a/sdk/go/groups.go b/sdk/go/groups.goindex d804ef5d6..a12f4423a 100644--- a/sdk/go/groups.go+++ b/sdk/go/groups.go@@ -37,6 +37,40 @@ func (s *GroupsService) Create(ctx context.Context, sessionID string, body Creatreturn &out, nil}+// JoinGroup joins a group via an invite code. Requires an OPERATOR-level key.+func (s *GroupsService) JoinGroup(ctx context.Context, sessionID string, body JoinGroupRequest) (*JoinGroupResponse, error) {+ var out JoinGroupResponse+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/join", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// GetGroupSettings returns the group's announce / locked / ephemeral-timer+// settings.+func (s *GroupsService) GetGroupSettings(ctx context.Context, sessionID, groupID string) (*GroupSettings, error) {+ var out GroupSettings+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(groupID)+"/settings", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// UpdateGroupSettings patches the group settings; at least one field must be+// set (the server rejects an empty patch with a 400). Setting+// EphemeralSeconds returns 501 on the whatsapp-web.js engine. Requires an+// OPERATOR-level key.+func (s *GroupsService) UpdateGroupSettings(ctx context.Context, sessionID, groupID string, body GroupSettings) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(groupID)+"/settings", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}+// AddParticipants adds members to a group.func (s *GroupsService) AddParticipants(ctx context.Context, sessionID, groupID string, participants []string) (*SuccessResult, error) {return s.participants(ctx, "POST", sessionID, groupID, "/participants", participants)diff --git a/sdk/go/messages.go b/sdk/go/messages.goindex 04eabee0f..24f9bfa78 100644--- a/sdk/go/messages.go+++ b/sdk/go/messages.go@@ -105,6 +105,17 @@ func (s *MessagesService) Delete(ctx context.Context, sessionID string, body Delreturn &out, nil}+// EditMessage edits the text of a message sent by this account. Requires an+// OPERATOR-level key. The server responds 404 when the message is not found.+func (s *MessagesService) EditMessage(ctx context.Context, sessionID string, body EditMessageRequest) (*MessageResponse, error) {+ var out MessageResponse+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/edit", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}+// History reads live chat history from WhatsApp.func (s *MessagesService) History(ctx context.Context, sessionID, chatID string, query *MessageHistoryQuery) ([]ChatHistoryMessage, error) {var out []ChatHistoryMessagediff --git a/sdk/go/profile.go b/sdk/go/profile.gonew file mode 100644index 000000000..7344a2927--- /dev/null+++ b/sdk/go/profile.go@@ -0,0 +1,44 @@+package openwa++import "context"++// ProfileService manages the connected account's own profile.+// Backed by src/modules/profile/profile.controller.ts. All methods require an+// OPERATOR-level key.+type ProfileService struct{ client *Client }++func (s *ProfileService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/profile"+}++// SetProfileName sets the account display name.+func (s *ProfileService) SetProfileName(ctx context.Context, sessionID string, body SetProfileNameRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/name", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SetProfileStatus sets the account about/status text; an empty Status clears+// it.+func (s *ProfileService) SetProfileStatus(ctx context.Context, sessionID string, body SetProfileStatusRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/status", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SetProfilePicture sets the account profile picture from a public URL or+// inline base64 (provide exactly one).+func (s *ProfileService) SetProfilePicture(ctx context.Context, sessionID string, body SetProfilePictureRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/picture", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goindex a5f857c46..9e2a3aa3b 100644--- a/sdk/go/routing_test.go+++ b/sdk/go/routing_test.go@@ -42,6 +42,7 @@ func TestRouting(t *testing.T) {{"Messages.Forward", func(c *Client) { c.Messages.Forward(ctx, "s1", ForwardMessageRequest{}) }, "POST", "/api/sessions/s1/messages/forward"},{"Messages.React", func(c *Client) { c.Messages.React(ctx, "s1", ReactMessageRequest{}) }, "POST", "/api/sessions/s1/messages/react"},{"Messages.Delete", func(c *Client) { c.Messages.Delete(ctx, "s1", DeleteMessageRequest{}) }, "POST", "/api/sessions/s1/messages/delete"},+ {"Messages.EditMessage", func(c *Client) { c.Messages.EditMessage(ctx, "s1", EditMessageRequest{}) }, "POST", "/api/sessions/s1/messages/edit"},{"Messages.History", func(c *Client) { c.Messages.History(ctx, "s1", "c1", nil) }, "GET", "/api/sessions/s1/messages/c1/history"},{"Messages.Reactions", func(c *Client) { c.Messages.Reactions(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/reactions"},{"Messages.SendBulk", func(c *Client) { c.Messages.SendBulk(ctx, "s1", SendBulkRequest{}) }, "POST", "/api/sessions/s1/messages/send-bulk"},@@ -59,6 +60,7 @@ func TestRouting(t *testing.T) {{"Groups.List", func(c *Client) { c.Groups.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/groups"},{"Groups.Get", func(c *Client) { c.Groups.Get(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1"},{"Groups.Create", func(c *Client) { c.Groups.Create(ctx, "s1", CreateGroupRequest{}) }, "POST", "/api/sessions/s1/groups"},+ {"Groups.JoinGroup", func(c *Client) { c.Groups.JoinGroup(ctx, "s1", JoinGroupRequest{}) }, "POST", "/api/sessions/s1/groups/join"},{"Groups.AddParticipants", func(c *Client) { c.Groups.AddParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants"},{"Groups.RemoveParticipants", func(c *Client) { c.Groups.RemoveParticipants(ctx, "s1", "g1", nil) }, "DELETE", "/api/sessions/s1/groups/g1/participants"},{"Groups.PromoteParticipants", func(c *Client) { c.Groups.PromoteParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants/promote"},@@ -68,6 +70,8 @@ func TestRouting(t *testing.T) {{"Groups.Leave", func(c *Client) { c.Groups.Leave(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/leave"},{"Groups.InviteCode", func(c *Client) { c.Groups.InviteCode(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1/invite-code"},{"Groups.RevokeInviteCode", func(c *Client) { c.Groups.RevokeInviteCode(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/invite-code/revoke"},+ {"Groups.GetGroupSettings", func(c *Client) { c.Groups.GetGroupSettings(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1/settings"},+ {"Groups.UpdateGroupSettings", func(c *Client) { c.Groups.UpdateGroupSettings(ctx, "s1", "g1", GroupSettings{}) }, "PUT", "/api/sessions/s1/groups/g1/settings"},{"Webhooks.List", func(c *Client) { c.Webhooks.List(ctx, "s1") }, "GET", "/api/sessions/s1/webhooks"},{"Webhooks.Get", func(c *Client) { c.Webhooks.Get(ctx, "s1", "w1") }, "GET", "/api/sessions/s1/webhooks/w1"},@@ -119,6 +123,12 @@ func TestRouting(t *testing.T) {{"Search.Search", func(c *Client) { c.Search.Search(ctx, SearchQuery{Q: "hi"}) }, "GET", "/api/search"},{"Auth.Validate", func(c *Client) { c.Auth.Validate(ctx) }, "POST", "/api/auth/validate"},++ {"Profile.SetProfileName", func(c *Client) { c.Profile.SetProfileName(ctx, "s1", SetProfileNameRequest{}) }, "PUT", "/api/sessions/s1/profile/name"},+ {"Profile.SetProfileStatus", func(c *Client) { c.Profile.SetProfileStatus(ctx, "s1", SetProfileStatusRequest{}) }, "PUT", "/api/sessions/s1/profile/status"},+ {"Profile.SetProfilePicture", func(c *Client) { c.Profile.SetProfilePicture(ctx, "s1", SetProfilePictureRequest{}) }, "PUT", "/api/sessions/s1/profile/picture"},++ {"Calls.RejectCall", func(c *Client) { c.Calls.RejectCall(ctx, "s1", "call1") }, "POST", "/api/sessions/s1/calls/call1/reject"},}for _, tc := range cases {diff --git a/sdk/go/types_group.go b/sdk/go/types_group.goindex cbe747451..862faac46 100644--- a/sdk/go/types_group.go+++ b/sdk/go/types_group.go@@ -51,6 +51,32 @@ type InviteCodeResponse struct {Message string `json:"message,omitempty"`}+// JoinGroupRequest joins a group via an invite code (the token from a+// https://chat.whatsapp.com/<code> link).+type JoinGroupRequest struct {+ InviteCode string `json:"inviteCode"`+}++// JoinGroupResponse is the join acknowledgement.+type JoinGroupResponse struct {+ Success bool `json:"success"`+ GroupID string `json:"groupId"`+}++// GroupSettings is the announce / locked / ephemeral-timer state of a group —+// the response of GetGroupSettings and the patch body of UpdateGroupSettings.+// Every field is a pointer: the engine may omit any of them on reads, and on+// updates unset fields are omitted from the body so only the provided settings+// are touched. At least one field must be set for an update — the server+// rejects an empty patch with a 400. EphemeralSeconds is the+// disappearing-messages timer in seconds (0 disables; known values 86400,+// 604800, 7776000) and is unsupported on the whatsapp-web.js engine (501).+type GroupSettings struct {+ Announce *bool `json:"announce,omitempty"`+ Locked *bool `json:"locked,omitempty"`+ EphemeralSeconds *int `json:"ephemeralSeconds,omitempty"`+}+// ListGroupsQuery paginates the group list.type ListGroupsQuery struct {Limit *intdiff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 6260f8133..a84562c26 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -90,6 +90,15 @@ type DeleteMessageRequest struct {ForEveryone *bool `json:"forEveryone,omitempty"`}+// EditMessageRequest edits the text of a message sent by this account. Body is+// the replacement text, capped at 4096 chars server-side (the same limit as+// send-text — an edit cannot exceed what a send allows).+type EditMessageRequest struct {+ ChatID string `json:"chatId"`+ MessageID string `json:"messageId"`+ Body string `json:"body"`+}+// ListMessagesQuery filters GET /sessions/:id/messages.type ListMessagesQuery struct {ChatID *stringdiff --git a/sdk/go/types_profile.go b/sdk/go/types_profile.gonew file mode 100644index 000000000..f8a85c567--- /dev/null+++ b/sdk/go/types_profile.go@@ -0,0 +1,22 @@+package openwa++// SetProfileNameRequest sets the account display name (WhatsApp limit: 25+// chars).+type SetProfileNameRequest struct {+ Name string `json:"name"`+}++// SetProfileStatusRequest sets the account about/status text (WhatsApp limit:+// 139 chars). An empty Status clears it.+type SetProfileStatusRequest struct {+ Status string `json:"status"`+}++// SetProfilePictureRequest sets the account profile picture. Provide exactly+// one of URL (a public http/https image the server fetches) or Base64 (inline+// image data, with Mimetype).+type SetProfilePictureRequest struct {+ URL string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+ Mimetype string `json:"mimetype,omitempty"`+}diff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.goindex 8059da4ce..710914528 100644--- a/sdk/go/types_webhook.go+++ b/sdk/go/types_webhook.go@@ -1,5 +1,65 @@package openwa+// WebhookEvent names an event a webhook may subscribe to. It is an alias for+// string so the Event* constants drop straight into the []string Events fields+// of CreateWebhookRequest / UpdateWebhookRequest without a conversion. Use+// EventAll ("*") to receive every event.+type WebhookEvent = string++// Events a webhook may subscribe to, mirroring the server's WEBHOOK_EVENTS+// catalog (src/modules/webhook/dto/webhook.dto.ts).+const (+ EventMessageReceived WebhookEvent = "message.received"+ EventMessageSent WebhookEvent = "message.sent"+ EventMessageAck WebhookEvent = "message.ack"+ EventMessageFailed WebhookEvent = "message.failed"+ EventMessageRevoked WebhookEvent = "message.revoked"+ EventMessageReaction WebhookEvent = "message.reaction"+ EventMessageEdited WebhookEvent = "message.edited"+ EventSessionStatus WebhookEvent = "session.status"+ EventSessionQR WebhookEvent = "session.qr"+ EventSessionAuthenticated WebhookEvent = "session.authenticated"+ EventSessionDisconnected WebhookEvent = "session.disconnected"+ EventSessionReconnectLoop WebhookEvent = "session.reconnect_loop"+ EventGroupJoin WebhookEvent = "group.join"+ EventGroupLeave WebhookEvent = "group.leave"+ EventGroupUpdate WebhookEvent = "group.update"+ EventCallReceived WebhookEvent = "call.received"+ EventAll WebhookEvent = "*"+)++// GroupEventChanges is the metadata delta on a group.update event. Fields are+// pointers: only the settings that actually changed are populated.+type GroupEventChanges struct {+ Subject *string `json:"subject,omitempty"`+ Description *string `json:"description,omitempty"`+ Announce *bool `json:"announce,omitempty"`+ Locked *bool `json:"locked,omitempty"`+}++// GroupEventPayload is the payload of the group.join / group.leave /+// group.update events (webhook and socket alike). ParticipantIDs carries the+// affected users for join/leave and is empty for metadata updates; Changes is+// the metadata delta, present on group.update. Timestamp is unix seconds.+type GroupEventPayload struct {+ GroupID string `json:"groupId"`+ ActorID *string `json:"actorId,omitempty"`+ ParticipantIDs []string `json:"participantIds"`+ Changes *GroupEventChanges `json:"changes,omitempty"`+ Timestamp int64 `json:"timestamp"`+}++// CallReceivedPayload is the payload of the call.received event. CallID is the+// handle Calls.RejectCall accepts while the call is still ringing. Timestamp+// is unix seconds.+type CallReceivedPayload struct {+ CallID string `json:"callId"`+ From string `json:"from"`+ IsVideo bool `json:"isVideo"`+ IsGroup bool `json:"isGroup"`+ Timestamp int64 `json:"timestamp"`+}+// WebhookFilterCondition is one condition in a webhook filter. Value is// polymorphic per field kind — the server accepts a string (text fields), a// []string (id/idArray/enum fields), or a bool (boolean fields). Passing adiff --git a/sdk/java/README.md b/sdk/java/README.mdindex 65f5ae0d6..e89af6c75 100644--- a/sdk/java/README.md+++ b/sdk/java/README.md@@ -66,7 +66,8 @@ The client exposes the same fluent resource surface as the JavaScript, Python,and PHP SDKs:`sessions` · `messages` · `contacts` · `groups` · `webhooks` · `chats` ·-`labels` · `channels` · `catalog` · `status` · `templates` · `health` · `search`,+`labels` · `channels` · `catalog` · `status` · `templates` · `health` · `search` ·+`profile` · `calls`,plus `client.auth()`.Operator-only modules (`docker`, `metrics`, `infra`, `plugins`, `mcp`) arediff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.javaindex 7bf63dd19..1729589e2 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java@@ -10,6 +10,7 @@ import com.rmyndharis.openwa.http.HttpRequestData;import com.rmyndharis.openwa.http.HttpResponseData;import com.rmyndharis.openwa.http.HttpTransport;import com.rmyndharis.openwa.model.AuthValidateResponse;+import com.rmyndharis.openwa.resources.CallsResource;import com.rmyndharis.openwa.resources.CatalogResource;import com.rmyndharis.openwa.resources.ChannelsResource;import com.rmyndharis.openwa.resources.ChatsResource;@@ -18,6 +19,7 @@ import com.rmyndharis.openwa.resources.GroupsResource;import com.rmyndharis.openwa.resources.HealthResource;import com.rmyndharis.openwa.resources.LabelsResource;import com.rmyndharis.openwa.resources.MessagesResource;+import com.rmyndharis.openwa.resources.ProfileResource;import com.rmyndharis.openwa.resources.SearchResource;import com.rmyndharis.openwa.resources.SessionsResource;import com.rmyndharis.openwa.resources.StatusResource;@@ -58,6 +60,8 @@ public final class OpenWAClient {public final StatusResource status = new StatusResource(this);public final TemplatesResource templates = new TemplatesResource(this);public final HealthResource health = new HealthResource(this);+ public final ProfileResource profile = new ProfileResource(this);+ public final CallsResource calls = new CallsResource(this);public OpenWAClient(ClientConfig config) {// ClientConfig's constructor validates baseUrl/apiKey/timeout, so config is already sound here.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.javanew file mode 100644index 000000000..ecbb72324--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.java@@ -0,0 +1,34 @@+package com.rmyndharis.openwa.model;++/** Request body for editing the text of a message sent by this account. */+public record EditMessageRequest(String chatId, String messageId, String body) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String chatId;+ private String messageId;+ private String body;++ public Builder chatId(String v) {+ this.chatId = v;+ return this;+ }++ public Builder messageId(String v) {+ this.messageId = v;+ return this;+ }++ /** The replacement message text. */+ public Builder body(String v) {+ this.body = v;+ return this;+ }++ public EditMessageRequest build() {+ return new EditMessageRequest(chatId, messageId, body);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.javanew file mode 100644index 000000000..e50b3efe4--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java@@ -0,0 +1,42 @@+package com.rmyndharis.openwa.model;++/**+ * Group settings — {@code announce} (only admins can send messages), {@code locked} (only admins+ * can edit group info) and {@code ephemeralSeconds} (disappearing-message timer). Every field is+ * optional: unset fields are omitted from the serialized body, so an update only touches the+ * settings that were set. Setting {@code ephemeralSeconds} returns HTTP 501 on the whatsapp-web.js+ * engine.+ */+public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralSeconds) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private Boolean announce;+ private Boolean locked;+ private Integer ephemeralSeconds;++ /** Only admins can send messages. */+ public Builder announce(Boolean v) {+ this.announce = v;+ return this;+ }++ /** Only admins can edit group info. */+ public Builder locked(Boolean v) {+ this.locked = v;+ return this;+ }++ /** Disappearing-message timer in seconds ({@code 0} disables). Not supported on the whatsapp-web.js engine. */+ public Builder ephemeralSeconds(Integer v) {+ this.ephemeralSeconds = v;+ return this;+ }++ public GroupSettings build() {+ return new GroupSettings(announce, locked, ephemeralSeconds);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupRequest.javanew file mode 100644index 000000000..de37b1852--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupRequest.java@@ -0,0 +1,22 @@+package com.rmyndharis.openwa.model;++/** Request body for joining a group via an invite code. */+public record JoinGroupRequest(String inviteCode) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String inviteCode;++ /** The invite code (from an invite link such as {@code https://chat.whatsapp.com/<code>}). */+ public Builder inviteCode(String v) {+ this.inviteCode = v;+ return this;+ }++ public JoinGroupRequest build() {+ return new JoinGroupRequest(inviteCode);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupResponse.javanew file mode 100644index 000000000..b6ceb949e--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/JoinGroupResponse.java@@ -0,0 +1,4 @@+package com.rmyndharis.openwa.model;++/** Returned when joining a group via an invite code — carries the joined group id. */+public record JoinGroupResponse(boolean success, String groupId) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileNameRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileNameRequest.javanew file mode 100644index 000000000..f7c10b776--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileNameRequest.java@@ -0,0 +1,22 @@+package com.rmyndharis.openwa.model;++/** Request body for setting the account display name. */+public record SetProfileNameRequest(String name) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String name;++ /** The new display name. */+ public Builder name(String v) {+ this.name = v;+ return this;+ }++ public SetProfileNameRequest build() {+ return new SetProfileNameRequest(name);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfilePictureRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfilePictureRequest.javanew file mode 100644index 000000000..79bb22575--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfilePictureRequest.java@@ -0,0 +1,35 @@+package com.rmyndharis.openwa.model;++/** Request body for setting the account profile picture. Provide {@code url} or {@code base64}. */+public record SetProfilePictureRequest(String url, String base64, String mimetype) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String url;+ private String base64;+ private String mimetype;++ /** Mutually exclusive with {@code base64}. */+ public Builder url(String v) {+ this.url = v;+ return this;+ }++ /** Requires {@code mimetype}. */+ public Builder base64(String v) {+ this.base64 = v;+ return this;+ }++ public Builder mimetype(String v) {+ this.mimetype = v;+ return this;+ }++ public SetProfilePictureRequest build() {+ return new SetProfilePictureRequest(url, base64, mimetype);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileStatusRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileStatusRequest.javanew file mode 100644index 000000000..0807b9f0c--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SetProfileStatusRequest.java@@ -0,0 +1,22 @@+package com.rmyndharis.openwa.model;++/** Request body for setting the account about/status text (an empty string clears it). */+public record SetProfileStatusRequest(String status) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String status;++ /** The new status text; empty string clears it. */+ public Builder status(String v) {+ this.status = v;+ return this;+ }++ public SetProfileStatusRequest build() {+ return new SetProfileStatusRequest(status);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.javaindex 4516a21f3..b224cf888 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java@@ -30,13 +30,16 @@ public enum WebhookEvent {SESSION_AUTHENTICATED,@SerializedName("session.disconnected")SESSION_DISCONNECTED,- // Reserved: accepted on subscribe but not dispatched yet.+ @SerializedName("session.reconnect_loop")+ SESSION_RECONNECT_LOOP,@SerializedName("group.join")GROUP_JOIN,@SerializedName("group.leave")GROUP_LEAVE,@SerializedName("group.update")GROUP_UPDATE,+ @SerializedName("call.received")+ CALL_RECEIVED,@SerializedName("*")ALL}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/CallsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/CallsResource.javanew file mode 100644index 000000000..4a44b2e41--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/CallsResource.java@@ -0,0 +1,33 @@+package com.rmyndharis.openwa.resources;++import static com.rmyndharis.openwa.http.Http.encodeSegment;++import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.http.HttpMethod;+import com.rmyndharis.openwa.model.SuccessResult;++/** Calls resource — incoming call handling. */+public final class CallsResource {+ private final OpenWAClient client;++ public CallsResource(OpenWAClient client) {+ this.client = client;+ }++ /**+ * Reject a ringing incoming call. The {@code callId} comes from a {@code call.received}+ * webhook event; 404 when the call is not found or no longer ringing.+ */+ public SuccessResult rejectCall(String sessionId, String callId) {+ return client.request(+ HttpMethod.POST,+ "/api/sessions/"+ + encodeSegment(sessionId)+ + "/calls/"+ + encodeSegment(callId)+ + "/reject",+ null,+ null,+ SuccessResult.class);+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.javaindex f8dca9a8e..8734e81e1 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java@@ -7,9 +7,12 @@ import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.CreateGroupRequest;import com.rmyndharis.openwa.model.GroupDescriptionRequest;import com.rmyndharis.openwa.model.GroupInfo;+import com.rmyndharis.openwa.model.GroupSettings;import com.rmyndharis.openwa.model.GroupSubjectRequest;import com.rmyndharis.openwa.model.GroupSummary;import com.rmyndharis.openwa.model.InviteCodeResponse;+import com.rmyndharis.openwa.model.JoinGroupRequest;+import com.rmyndharis.openwa.model.JoinGroupResponse;import com.rmyndharis.openwa.model.ListGroupsQuery;import com.rmyndharis.openwa.model.ParticipantsRequest;import com.rmyndharis.openwa.model.SuccessResult;@@ -100,6 +103,16 @@ public final class GroupsResource {SuccessResult.class);}+ /** Join a group via an invite code. Returns the joined group id. */+ public JoinGroupResponse joinGroup(String sessionId, String inviteCode) {+ return client.request(+ HttpMethod.POST,+ "/api/sessions/" + encodeSegment(sessionId) + "/groups/join",+ null,+ new JoinGroupRequest(inviteCode),+ JoinGroupResponse.class);+ }+/** Update the group description (empty string clears it). */public SuccessResult setDescription(String sessionId, String groupId, String description) {return client.request(@@ -110,6 +123,29 @@ public final class GroupsResource {SuccessResult.class);}+ /** Get the group settings (announce / locked / ephemeral timer). */+ public GroupSettings getGroupSettings(String sessionId, String groupId) {+ return client.request(+ HttpMethod.GET,+ "/api/sessions/" + encodeSegment(sessionId) + "/groups/" + encodeSegment(groupId) + "/settings",+ null,+ null,+ GroupSettings.class);+ }++ /**+ * Update the group settings. At least one field of {@code settings} must be set; absent fields+ * stay untouched. Setting {@code ephemeralSeconds} returns HTTP 501 on the whatsapp-web.js engine.+ */+ public SuccessResult updateGroupSettings(String sessionId, String groupId, GroupSettings settings) {+ return client.request(+ HttpMethod.PUT,+ "/api/sessions/" + encodeSegment(sessionId) + "/groups/" + encodeSegment(groupId) + "/settings",+ null,+ settings,+ SuccessResult.class);+ }+/** Leave a group. */public SuccessResult leave(String sessionId, String groupId) {return client.request(diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex 22f3ac640..2f2176831 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -8,6 +8,7 @@ import com.rmyndharis.openwa.model.BatchStatusResponse;import com.rmyndharis.openwa.model.BulkMessageResponse;import com.rmyndharis.openwa.model.ChatHistoryMessage;import com.rmyndharis.openwa.model.DeleteMessageRequest;+import com.rmyndharis.openwa.model.EditMessageRequest;import com.rmyndharis.openwa.model.ForwardMessageRequest;import com.rmyndharis.openwa.model.ListMessagesQuery;import com.rmyndharis.openwa.model.MessageHistoryQuery;@@ -143,6 +144,16 @@ public final class MessagesResource {SuccessResult.class);}+ /** Edit the text of a message sent by this account. 404 when the message is not found. */+ public MessageResponse editMessage(String sessionId, EditMessageRequest body) {+ return client.request(+ HttpMethod.POST,+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/edit",+ null,+ body,+ MessageResponse.class);+ }+/** Delete a message. */public SuccessResult delete(String sessionId, DeleteMessageRequest body) {return client.request(diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ProfileResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ProfileResource.javanew file mode 100644index 000000000..3ea30f288--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ProfileResource.java@@ -0,0 +1,49 @@+package com.rmyndharis.openwa.resources;++import static com.rmyndharis.openwa.http.Http.encodeSegment;++import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.http.HttpMethod;+import com.rmyndharis.openwa.model.SetProfileNameRequest;+import com.rmyndharis.openwa.model.SetProfilePictureRequest;+import com.rmyndharis.openwa.model.SetProfileStatusRequest;+import com.rmyndharis.openwa.model.SuccessResult;++/** Profile resource — the linked account's display name, status text and picture. */+public final class ProfileResource {+ private final OpenWAClient client;++ public ProfileResource(OpenWAClient client) {+ this.client = client;+ }++ /** Set the account display name. */+ public SuccessResult setProfileName(String sessionId, String name) {+ return client.request(+ HttpMethod.PUT,+ "/api/sessions/" + encodeSegment(sessionId) + "/profile/name",+ null,+ new SetProfileNameRequest(name),+ SuccessResult.class);+ }++ /** Set the account about/status text (an empty string clears it). */+ public SuccessResult setProfileStatus(String sessionId, String status) {+ return client.request(+ HttpMethod.PUT,+ "/api/sessions/" + encodeSegment(sessionId) + "/profile/status",+ null,+ new SetProfileStatusRequest(status),+ SuccessResult.class);+ }++ /** Set the account profile picture from a {@code url} or a {@code base64} + {@code mimetype} pair. */+ public SuccessResult setProfilePicture(String sessionId, SetProfilePictureRequest body) {+ return client.request(+ HttpMethod.PUT,+ "/api/sessions/" + encodeSegment(sessionId) + "/profile/picture",+ null,+ body,+ SuccessResult.class);+ }+}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.javanew file mode 100644index 000000000..af65d4880--- /dev/null+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.java@@ -0,0 +1,45 @@+package com.rmyndharis.openwa.resources;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.rmyndharis.openwa.ClientConfig;+import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.errors.OpenWANotFoundError;+import com.rmyndharis.openwa.http.HttpMethod;+import com.rmyndharis.openwa.support.MockTransport;+import org.junit.jupiter.api.Test;++class CallsResourceTest {+ final MockTransport tx = new MockTransport();+ final OpenWAClient client = new OpenWAClient(+ ClientConfig.builder().baseUrl("http://h").apiKey("k").transport(tx).build());++ @Test+ void rejectCallHitsRejectPath() {+ tx.respond(200, "{\"success\":true}");+ client.calls.rejectCall("s", "call-123");+ assertEquals("http://h/api/sessions/s/calls/call-123/reject", tx.lastRequest().url());+ assertEquals(HttpMethod.POST, tx.lastRequest().method());+ }++ @Test+ void rejectCallEncodesIds() {+ tx.respond(200, "{\"success\":true}");+ client.calls.rejectCall("a/b", "call/1");+ assertEquals("http://h/api/sessions/a%2Fb/calls/call%2F1/reject", tx.lastRequest().url());+ }++ @Test+ void rejectCallParsesSuccess() {+ tx.respond(200, "{\"success\":true}");+ assertTrue(client.calls.rejectCall("s", "call-123").success());+ }++ @Test+ void rejectCallNotRingingThrowsNotFound() {+ tx.respond(404, "{\"statusCode\":404,\"message\":\"Call not found or no longer ringing\",\"error\":\"Not Found\"}");+ assertThrows(OpenWANotFoundError.class, () -> client.calls.rejectCall("s", "call-123"));+ }+}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.javaindex b7695b828..305703a01 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java@@ -1,12 +1,15 @@package com.rmyndharis.openwa.resources;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;import com.rmyndharis.openwa.ClientConfig;import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.CreateGroupRequest;+import com.rmyndharis.openwa.model.GroupSettings;import com.rmyndharis.openwa.model.ListGroupsQuery;import com.rmyndharis.openwa.support.MockTransport;import java.util.List;@@ -105,6 +108,52 @@ class GroupsResourceTest {assertTrue(tx.lastRequest().body().contains("A description"));}+ @Test+ void joinGroupHitsJoinPath() {+ tx.respond(200, "{\"success\":true,\"groupId\":\"[email protected]\"}");+ client.groups.joinGroup("s", "AbCdEfGhIjKl");+ assertEquals("http://h/api/sessions/s/groups/join", tx.lastRequest().url());+ assertEquals(HttpMethod.POST, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("AbCdEfGhIjKl"));+ }++ @Test+ void getGroupSettingsHitsSettingsPath() {+ tx.respond(200, "{\"announce\":true,\"locked\":false,\"ephemeralSeconds\":604800}");+ client.groups.getGroupSettings("s", "[email protected]");+ assertEquals("http://h/api/sessions/s/groups/[email protected]/settings", tx.lastRequest().url());+ assertEquals(HttpMethod.GET, tx.lastRequest().method());+ }++ @Test+ void getGroupSettingsParsesOptionalFields() {+ tx.respond(200, "{\"announce\":true}");+ GroupSettings settings = client.groups.getGroupSettings("s", "[email protected]");+ assertEquals(Boolean.TRUE, settings.announce());+ assertNull(settings.locked());+ assertNull(settings.ephemeralSeconds());+ }++ @Test+ void updateGroupSettingsPutsOnlySetFields() {+ tx.respond(200, "{\"success\":true,\"message\":\"Group settings updated\"}");+ client.groups.updateGroupSettings("s", "[email protected]", GroupSettings.builder().announce(true).build());+ assertEquals("http://h/api/sessions/s/groups/[email protected]/settings", tx.lastRequest().url());+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("\"announce\":true"));+ assertFalse(tx.lastRequest().body().contains("locked"));+ assertFalse(tx.lastRequest().body().contains("ephemeralSeconds"));+ }++ @Test+ void updateGroupSettingsSendsEphemeralSeconds() {+ tx.respond(200, "{\"success\":true,\"message\":\"Group settings updated\"}");+ client.groups.updateGroupSettings(+ "s", "[email protected]", GroupSettings.builder().locked(true).ephemeralSeconds(86400).build());+ assertTrue(tx.lastRequest().body().contains("\"locked\":true"));+ assertTrue(tx.lastRequest().body().contains("\"ephemeralSeconds\":86400"));+ }+@Testvoid leaveHitsLeavePath() {tx.respond(200, "{\"success\":true}");diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.javaindex 1d5eb6efd..d421aeef7 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java@@ -10,6 +10,7 @@ import com.rmyndharis.openwa.model.BulkMessageContent;import com.rmyndharis.openwa.model.BulkMessageItem;import com.rmyndharis.openwa.model.BulkMessageType;import com.rmyndharis.openwa.model.DeleteMessageRequest;+import com.rmyndharis.openwa.model.EditMessageRequest;import com.rmyndharis.openwa.model.ForwardMessageRequest;import com.rmyndharis.openwa.model.ListMessagesQuery;import com.rmyndharis.openwa.model.MessageHistoryQuery;@@ -159,6 +160,17 @@ class MessagesResourceTest {assertTrue(tx.lastRequest().body().contains("react-msg"));}+ @Test+ void editMessageHitsEditPath() {+ tx.respond(200, MSG);+ client.messages.editMessage(+ "s", EditMessageRequest.builder().chatId("[email protected]").messageId("edit-msg").body("edited-text").build());+ assertEquals("http://h/api/sessions/s/messages/edit", tx.lastRequest().url());+ assertEquals(HttpMethod.POST, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("edit-msg"));+ assertTrue(tx.lastRequest().body().contains("edited-text"));+ }+@Testvoid deleteHitsDeletePath() {tx.respond(200, "{\"success\":true}");diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ProfileResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ProfileResourceTest.javanew file mode 100644index 000000000..cfc1249aa--- /dev/null+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ProfileResourceTest.java@@ -0,0 +1,66 @@+package com.rmyndharis.openwa.resources;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import com.rmyndharis.openwa.ClientConfig;+import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.http.HttpMethod;+import com.rmyndharis.openwa.model.SetProfilePictureRequest;+import com.rmyndharis.openwa.support.MockTransport;+import org.junit.jupiter.api.Test;++class ProfileResourceTest {+ final MockTransport tx = new MockTransport();+ final OpenWAClient client = new OpenWAClient(+ ClientConfig.builder().baseUrl("http://h").apiKey("k").transport(tx).build());++ @Test+ void setProfileNameHitsNamePath() {+ tx.respond(200, "{\"success\":true,\"message\":\"Profile name updated\"}");+ client.profile.setProfileName("s", "New Display Name");+ assertEquals("http://h/api/sessions/s/profile/name", tx.lastRequest().url());+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("New Display Name"));+ }++ @Test+ void setProfileStatusHitsStatusPath() {+ tx.respond(200, "{\"success\":true,\"message\":\"Profile status updated\"}");+ client.profile.setProfileStatus("s", "Busy");+ assertEquals("http://h/api/sessions/s/profile/status", tx.lastRequest().url());+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("Busy"));+ }++ @Test+ void setProfileStatusSendsEmptyStringToClear() {+ tx.respond(200, "{\"success\":true,\"message\":\"Profile status updated\"}");+ client.profile.setProfileStatus("s", "");+ assertEquals("http://h/api/sessions/s/profile/status", tx.lastRequest().url());+ assertTrue(tx.lastRequest().body().contains("\"status\":\"\""));+ }++ @Test+ void setProfilePictureSendsUrl() {+ tx.respond(200, "{\"success\":true,\"message\":\"Profile picture updated\"}");+ client.profile.setProfilePicture(+ "s", SetProfilePictureRequest.builder().url("http://pic-url/img.jpg").build());+ assertEquals("http://h/api/sessions/s/profile/picture", tx.lastRequest().url());+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("pic-url"));+ assertFalse(tx.lastRequest().body().contains("base64"));+ }++ @Test+ void setProfilePictureSendsBase64AndMimetype() {+ tx.respond(200, "{\"success\":true,\"message\":\"Profile picture updated\"}");+ client.profile.setProfilePicture(+ "s", SetProfilePictureRequest.builder().base64("aGVsbG8").mimetype("image/jpeg").build());+ assertEquals("http://h/api/sessions/s/profile/picture", tx.lastRequest().url());+ assertTrue(tx.lastRequest().body().contains("aGVsbG8"));+ assertTrue(tx.lastRequest().body().contains("image/jpeg"));+ assertFalse(tx.lastRequest().body().contains("\"url\""));+ }+}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.javaindex 27fcde35c..8d7db31d8 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java@@ -78,4 +78,21 @@ class WebhooksResourceTest {assertEquals("http://h/api/sessions/s/webhooks/w1/test", tx.lastRequest().url());assertEquals(HttpMethod.POST, tx.lastRequest().method());}++ @Test+ void createSerializesNewEventTypes() {+ tx.respond(200, WEBHOOK_JSON);+ client.webhooks.create(+ "s",+ CreateWebhookRequest.builder()+ .url("https://example.test/hook")+ .events(List.of(+ WebhookEvent.GROUP_JOIN, WebhookEvent.GROUP_LEAVE, WebhookEvent.GROUP_UPDATE,+ WebhookEvent.CALL_RECEIVED))+ .build());+ assertTrue(tx.lastRequest().body().contains("group.join"));+ assertTrue(tx.lastRequest().body().contains("group.leave"));+ assertTrue(tx.lastRequest().body().contains("group.update"));+ assertTrue(tx.lastRequest().body().contains("call.received"));+ }}diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex 067f0df82..96a513a30 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -24,6 +24,7 @@*/import { request, encodeSegment, warnIfInsecureHttpUrl, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';+import { CallsResource } from './resources/calls.js';import { CatalogResource } from './resources/catalog.js';import { ChannelsResource } from './resources/channels.js';import { ChatsResource } from './resources/chats.js';@@ -32,6 +33,7 @@ import { GroupsResource } from './resources/groups.js';import { HealthResource } from './resources/health.js';import { LabelsResource } from './resources/labels.js';import { MessagesResource } from './resources/messages.js';+import { ProfileResource } from './resources/profile.js';import { SearchResource } from './resources/search.js';import { SessionsResource } from './resources/sessions.js';import { StatusResource } from './resources/status.js';@@ -85,6 +87,8 @@ export class OpenWAClient {readonly catalog = new CatalogResource(this);readonly templates = new TemplatesResource(this);readonly search = new SearchResource(this);+ readonly profile = new ProfileResource(this);+ readonly calls = new CallsResource(this);// ── Auth ─────────────────────────────────────────────────────────diff --git a/sdk/javascript/src/resources/calls.ts b/sdk/javascript/src/resources/calls.tsnew file mode 100644index 000000000..572eab0a1--- /dev/null+++ b/sdk/javascript/src/resources/calls.ts@@ -0,0 +1,26 @@+/**+ * Calls resource — incoming-call handling.+ *+ * Backed by `src/modules/call/call.controller.ts` (`@Controller('sessions/:sessionId/calls')`).+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { SuccessResult } from '../types.js';++export class CallsResource {+ constructor(private readonly client: OpenWAClient) {}++ /**+ * Reject a ringing incoming call. The `callId` comes from the `call.received`+ * webhook/socket event; the server answers 404 when the call is not found or no+ * longer ringing. Requires an OPERATOR-level key.+ */+ rejectCall(sessionId: string, callId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/calls/${encodeSegment(callId)}/reject`,+ });+ }+}diff --git a/sdk/javascript/src/resources/groups.ts b/sdk/javascript/src/resources/groups.tsindex a43422bc6..0d39c59e1 100644--- a/sdk/javascript/src/resources/groups.ts+++ b/sdk/javascript/src/resources/groups.ts@@ -7,7 +7,17 @@import { encodeSegment } from '../http.js';import type { OpenWAClient } from '../client.js';-import type { CreateGroupRequest, GroupInfo, GroupSummary, InviteCodeResponse, SuccessResult } from '../types.js';+import type {+ CreateGroupRequest,+ GroupInfo,+ GroupSettingsResponse,+ GroupSummary,+ InviteCodeResponse,+ JoinGroupRequest,+ JoinGroupResponse,+ SuccessResult,+ UpdateGroupSettingsRequest,+} from '../types.js';export interface ListGroupsQuery {limit?: number;@@ -43,6 +53,15 @@ export class GroupsResource {});}+ /** Join a group via an invite code. */+ joinGroup(sessionId: string, body: JoinGroupRequest): Promise<JoinGroupResponse> {+ return this.client.request<JoinGroupResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/join`,+ body,+ });+ }+/** Add participants to a group. */addParticipants(sessionId: string, groupId: string, participants: string[]): Promise<SuccessResult> {return this.client.request<SuccessResult>({@@ -97,6 +116,26 @@ export class GroupsResource {});}+ /** Get the group settings (announce / locked / ephemeral timer). */+ getGroupSettings(sessionId: string, groupId: string): Promise<GroupSettingsResponse> {+ return this.client.request<GroupSettingsResponse>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/settings`,+ });+ }++ /**+ * Update the group settings. At least one field is required; `ephemeralSeconds`+ * is unsupported on the whatsapp-web.js engine (the server answers 501).+ */+ updateGroupSettings(sessionId: string, groupId: string, body: UpdateGroupSettingsRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/settings`,+ body,+ });+ }+/** Leave a group. */leave(sessionId: string, groupId: string): Promise<SuccessResult> {return this.client.request<SuccessResult>({diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex 46f902a88..5892ba88c 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -13,6 +13,7 @@ import type {BulkMessageResponse,ChatHistoryMessage,DeleteMessageRequest,+ EditMessageRequest,ForwardMessageRequest,ListMessagesQuery,MessageHistoryQuery,@@ -140,6 +141,15 @@ export class MessagesResource {});}+ /** Edit the text of an own message (404 if the message is not found). */+ editMessage(sessionId: string, body: EditMessageRequest): Promise<MessageResponse> {+ return this.client.request<MessageResponse>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/edit`,+ body,+ });+ }+/** Get the message history for a chat (read live from WhatsApp). */history(sessionId: string, chatId: string, query?: MessageHistoryQuery): Promise<ChatHistoryMessage[]> {return this.client.request<ChatHistoryMessage[]>({diff --git a/sdk/javascript/src/resources/profile.ts b/sdk/javascript/src/resources/profile.tsnew file mode 100644index 000000000..62d958b4c--- /dev/null+++ b/sdk/javascript/src/resources/profile.ts@@ -0,0 +1,42 @@+/**+ * Profile resource — the session's own account profile (name, about/status, picture).+ *+ * Backed by `src/modules/profile/profile.controller.ts` (`@Controller('sessions/:sessionId/profile')`).+ * All operations require an OPERATOR-level key.+ * @packageDocumentation+ */++import { encodeSegment } from '../http.js';+import type { OpenWAClient } from '../client.js';+import type { SetProfilePictureRequest, SuccessResult } from '../types.js';++export class ProfileResource {+ constructor(private readonly client: OpenWAClient) {}++ /** Set the account display name (max 25 chars). */+ setProfileName(sessionId: string, name: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/profile/name`,+ body: { name },+ });+ }++ /** Set the account about/status text (max 139 chars; empty string clears it). */+ setProfileStatus(sessionId: string, status: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/profile/status`,+ body: { status },+ });+ }++ /** Set the account profile picture (provide `url` OR `base64` + `mimetype`). */+ setProfilePicture(sessionId: string, body: SetProfilePictureRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/profile/picture`,+ body,+ });+ }+}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex a6419eb94..e65cdbf89 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -159,6 +159,13 @@ export interface DeleteMessageRequest {forEveryone?: boolean;}+export interface EditMessageRequest {+ chatId: Jid;+ messageId: string;+ /** New text body; max 4096 chars (same cap as a send). Own messages only — 404 if not found. */+ body: string;+}+export interface SendTemplateRequest {chatId: Jid;/** Provide exactly one of `templateId` or `templateName`. */@@ -416,6 +423,55 @@ export interface InviteCodeResponse {message?: string;}+export interface JoinGroupRequest {+ /** Group invite code (the token from a `https://chat.whatsapp.com/<code>` link); max 128 chars. */+ inviteCode: string;+}++export interface JoinGroupResponse {+ success: boolean;+ groupId: Jid;+}++/** Group settings as returned by `GET /sessions/:id/groups/:groupId/settings`. */+export interface GroupSettingsResponse {+ /** Only admins can send messages (announce group). */+ announce?: boolean;+ /** Only admins can edit group info (locked group). */+ locked?: boolean;+ /** Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d). */+ ephemeralSeconds?: number;+}++/**+ * Body for `PUT /sessions/:id/groups/:groupId/settings`. At least one field must be+ * present (the server answers 400 on an empty body); `ephemeralSeconds` is rejected+ * with 501 on the whatsapp-web.js engine.+ */+export type UpdateGroupSettingsRequest = GroupSettingsResponse;++// ── Profile (the session's own account) ───────────────────────────++export interface SetProfileNameRequest {+ /** New display name (WhatsApp limit: 25 characters). */+ name: string;+}++export interface SetProfileStatusRequest {+ /** New about/status text (may be empty to clear it; WhatsApp limit: 139 characters). */+ status: string;+}++/** Provide `url` OR `base64` (with `mimetype`). Mirrors the media acceptance pattern of sends. */+export interface SetProfilePictureRequest {+ /** Image URL (http/https); mutually exclusive with `base64`. */+ url?: string;+ /** Base64 encoded image data; requires `mimetype`. */+ base64?: string;+ /** Image MIME type (required when using `base64`). */+ mimetype?: string;+}+// ── Webhook ───────────────────────────────────────────────────────/** Events a webhook may subscribe to. Use `*` to receive all. */@@ -431,10 +487,11 @@ export type WebhookEvent =| 'session.qr'| 'session.authenticated'| 'session.disconnected'- // Reserved: accepted on subscribe but not dispatched yet.+ | 'session.reconnect_loop'| 'group.join'| 'group.leave'| 'group.update'+ | 'call.received'| '*';export interface WebhookFilterCondition {diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 2daa20ad6..ca0a6377e 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -102,7 +102,23 @@ describe('OpenWAClient', () => {it('exposes all expected resource properties', () => {const c = client(new MockTransport());- for (const r of ['sessions', 'messages', 'contacts', 'groups', 'webhooks', 'chats', 'status', 'health']) {+ for (const r of [+ 'sessions',+ 'messages',+ 'contacts',+ 'groups',+ 'webhooks',+ 'chats',+ 'status',+ 'health',+ 'labels',+ 'channels',+ 'catalog',+ 'templates',+ 'search',+ 'profile',+ 'calls',+ ]) {expect(c).toHaveProperty(r);}});diff --git a/sdk/javascript/test/messages.test.ts b/sdk/javascript/test/messages.test.tsindex 4221d440a..c499e92dd 100644--- a/sdk/javascript/test/messages.test.ts+++ b/sdk/javascript/test/messages.test.ts@@ -87,6 +87,15 @@ describe('MessagesResource — exact paths', () => {expect(t.lastCall!.url).toContain('/messages/delete');});+ it('editMessage posts to /messages/edit and returns the MessageResponse shape', async () => {+ const t = new MockTransport().on('POST', /\/messages\/edit$/, { body: { messageId: 'm1', timestamp: 4 } });+ const res = await client(t).messages.editMessage('s', { chatId: '[email protected]', messageId: 'm1', body: 'edited' });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/edit');+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', messageId: 'm1', body: 'edited' });+ expect(res.messageId).toBe('m1');+ expect(res.timestamp).toBe(4);+ });+it('history puts chatId in the path', async () => {const t = new MockTransport().on('GET', /\/messages\/[^/]+\/history$/, { body: [] });await client(t).messages.history('s', '[email protected]', { limit: 5 });diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.tsindex fb3a4bf66..4cb914964 100644--- a/sdk/javascript/test/resources.test.ts+++ b/sdk/javascript/test/resources.test.ts@@ -57,6 +57,63 @@ describe('GroupsResource — exact paths and bodies', () => {await c.groups.revokeInviteCode('s', 'g');expect(t.lastCall!.url).toContain('/invite-code/revoke');});++ it('joinGroup posts the invite code to /groups/join', async () => {+ const t = new MockTransport().on('POST', /\/groups\/join$/, { body: { success: true, groupId: '[email protected]' } });+ const res = await client(t).groups.joinGroup('s', { inviteCode: 'AbCdEf' });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/groups/join');+ expect(t.lastCall!.body).toEqual({ inviteCode: 'AbCdEf' });+ expect(res.groupId).toBe('[email protected]');+ });++ it('getGroupSettings / updateGroupSettings hit /groups/:id/settings', async () => {+ const t = new MockTransport()+ .on('GET', /\/groups\/g1@g\.us\/settings$/, { body: { announce: true, ephemeralSeconds: 604800 } })+ .on('PUT', /\/groups\/g1@g\.us\/settings$/, { body: { success: true, message: 'Group settings updated' } });+ const c = client(t);+ const settings = await c.groups.getGroupSettings('s', '[email protected]');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/groups/[email protected]/settings');+ expect(settings.announce).toBe(true);+ expect(settings.ephemeralSeconds).toBe(604800);+ await c.groups.updateGroupSettings('s', '[email protected]', { locked: true });+ expect(t.lastCall!.method).toBe('PUT');+ expect(t.lastCall!.body).toEqual({ locked: true });+ });+});++describe('ProfileResource — exact paths and bodies', () => {+ it('setProfileName / setProfileStatus / setProfilePicture PUT to /profile/*', async () => {+ const t = new MockTransport()+ .on('PUT', /\/profile\/name$/, { body: { success: true, message: 'Profile name updated' } })+ .on('PUT', /\/profile\/status$/, { body: { success: true, message: 'Profile status updated' } })+ .on('PUT', /\/profile\/picture$/, { body: { success: true, message: 'Profile picture updated' } });+ const c = client(t);+ await c.profile.setProfileName('s', 'My Bot');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/profile/name');+ expect(t.lastCall!.body).toEqual({ name: 'My Bot' });+ await c.profile.setProfileStatus('s', '');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/profile/status');+ expect(t.lastCall!.body).toEqual({ status: '' });+ await c.profile.setProfilePicture('s', { url: 'https://e.com/avatar.jpg' });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/profile/picture');+ expect(t.lastCall!.body).toEqual({ url: 'https://e.com/avatar.jpg' });+ });++ it('setProfilePicture forwards the base64 + mimetype variant verbatim', async () => {+ const t = new MockTransport().on('PUT', /\/profile\/picture$/, { body: { success: true } });+ await client(t).profile.setProfilePicture('s', { base64: 'aGVsbG8=', mimetype: 'image/png' });+ expect(t.lastCall!.body).toEqual({ base64: 'aGVsbG8=', mimetype: 'image/png' });+ });+});++describe('CallsResource — exact paths', () => {+ it('rejectCall POSTs to /calls/:callId/reject with no body', async () => {+ const t = new MockTransport().on('POST', /\/calls\/CALL123\/reject$/, { body: { success: true } });+ const res = await client(t).calls.rejectCall('s', 'CALL123');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/calls/CALL123/reject');+ expect(t.lastCall!.body).toBeUndefined();+ expect(res.success).toBe(true);+ });});describe('ContactsResource — exact paths', () => {diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.phpindex cfca3c441..981a40e14 100644--- a/sdk/php/src/Client.php+++ b/sdk/php/src/Client.php@@ -8,6 +8,7 @@ use GuzzleHttp\ClientInterface;use OpenWA\Exceptions\OpenWAException;use OpenWA\Http\HttpExecutor;use OpenWA\Resources\CatalogResource;+use OpenWA\Resources\CallsResource;use OpenWA\Resources\ChannelsResource;use OpenWA\Resources\ChatsResource;use OpenWA\Resources\ContactsResource;@@ -15,6 +16,7 @@ use OpenWA\Resources\GroupsResource;use OpenWA\Resources\HealthResource;use OpenWA\Resources\LabelsResource;use OpenWA\Resources\MessagesResource;+use OpenWA\Resources\ProfileResource;use OpenWA\Resources\SearchResource;use OpenWA\Resources\SessionsResource;use OpenWA\Resources\StatusResource;@@ -63,6 +65,8 @@ class Clientpublic ChannelsResource $channels;public CatalogResource $catalog;public TemplatesResource $templates;+ public ProfileResource $profile;+ public CallsResource $calls;/*** @param array{@@ -107,6 +111,8 @@ class Client$this->channels = new ChannelsResource($this->http);$this->catalog = new CatalogResource($this->http);$this->templates = new TemplatesResource($this->http);+ $this->profile = new ProfileResource($this->http);+ $this->calls = new CallsResource($this->http);}/**diff --git a/sdk/php/src/Resources/CallsResource.php b/sdk/php/src/Resources/CallsResource.phpnew file mode 100644index 000000000..a36320f79--- /dev/null+++ b/sdk/php/src/Resources/CallsResource.php@@ -0,0 +1,34 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Calls resource — incoming voice/video call handling.+ *+ * Backed by src/modules/call/call.controller.ts.+ */+class CallsResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * Reject a ringing incoming call (the callId from the call.received event).+ * 404 when the call is not found or no longer ringing. Requires an+ * OPERATOR-level key.+ *+ * @return array<string,mixed>+ */+ public function rejectCall(string $sessionId, string $callId): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/calls/{$this->http->encodeSegment($callId)}/reject");+ }+}diff --git a/sdk/php/src/Resources/GroupsResource.php b/sdk/php/src/Resources/GroupsResource.phpindex 07ba115f0..2eb05fae0 100644--- a/sdk/php/src/Resources/GroupsResource.php+++ b/sdk/php/src/Resources/GroupsResource.php@@ -44,6 +44,17 @@ class GroupsResourcereturn $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups", [], $body);}+ /**+ * Join a group via an invite code (the token from a chat.whatsapp.com/<code>+ * link). Returns {success: true, groupId}.+ *+ * @return array<string,mixed>+ */+ public function joinGroup(string $sessionId, string $inviteCode): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/join", [], ['inviteCode' => $inviteCode]);+ }+/** @return array<string,mixed> */public function addParticipants(string $sessionId, string $groupId, array $participants): array{@@ -80,6 +91,30 @@ class GroupsResourcereturn $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/description", [], ['description' => $description]);}+ /**+ * Get group settings. Only the settings the active engine supports are+ * present — any of {announce, locked, ephemeralSeconds} may be absent.+ *+ * @return array<string,mixed>+ */+ public function getGroupSettings(string $sessionId, string $groupId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/settings");+ }++ /**+ * Update group settings. At least one of {announce, locked,+ * ephemeralSeconds} is required (400 otherwise); ephemeralSeconds responds+ * 501 on engines without disappearing-message support (whatsapp-web.js).+ *+ * @param array<string,mixed> $settings+ * @return array<string,mixed>+ */+ public function updateGroupSettings(string $sessionId, string $groupId, array $settings): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/settings", [], $settings);+ }+/** @return array<string,mixed> */public function leave(string $sessionId, string $groupId): array{diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 0c698bef8..d04dfbfcb 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -125,6 +125,18 @@ class MessagesResourcereturn $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/delete", [], $body);}+ /**+ * Edit the text of a message sent by this account. Body is+ * {chatId, messageId, body}; 404 when the message is not found.+ *+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function editMessage(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/edit", [], $body);+ }+/*** @param array<string,mixed> $query* @return array<int,array<string,mixed>>diff --git a/sdk/php/src/Resources/ProfileResource.php b/sdk/php/src/Resources/ProfileResource.phpnew file mode 100644index 000000000..a30ac81a2--- /dev/null+++ b/sdk/php/src/Resources/ProfileResource.php@@ -0,0 +1,55 @@+<?php++declare(strict_types=1);++namespace OpenWA\Resources;++use OpenWA\Http\HttpExecutor;++/**+ * Profile resource — the connected account's own profile.+ *+ * Backed by src/modules/profile/profile.controller.ts.+ */+class ProfileResource+{+ private HttpExecutor $http;++ public function __construct(HttpExecutor $http)+ {+ $this->http = $http;+ }++ /**+ * Set the account display name. Requires an OPERATOR-level key.+ *+ * @return array<string,mixed>+ */+ public function setProfileName(string $sessionId, string $name): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/profile/name", [], ['name' => $name]);+ }++ /**+ * Set the account about/status text; an empty string clears it. Requires an+ * OPERATOR-level key.+ *+ * @return array<string,mixed>+ */+ public function setProfileStatus(string $sessionId, string $status): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/profile/status", [], ['status' => $status]);+ }++ /**+ * Set the account profile picture. Body is either {url} or+ * {base64, mimetype}. Requires an OPERATOR-level key.+ *+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function setProfilePicture(string $sessionId, array $body): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/profile/picture", [], $body);+ }+}diff --git a/sdk/php/tests/MessagesTest.php b/sdk/php/tests/MessagesTest.phpindex b863edc30..936411829 100644--- a/sdk/php/tests/MessagesTest.php+++ b/sdk/php/tests/MessagesTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace OpenWA\Tests;+use OpenWA\Exceptions\OpenWANotFoundException;use PHPUnit\Framework\TestCase;class MessagesTest extends TestCase@@ -78,6 +79,29 @@ class MessagesTest extends TestCase$this->assertStringContainsString('/messages/delete', $backend->calls()[3]['url']);}+ public function testEditMessageUsesEditPath(): void+ {+ $backend = (new MockBackend())->on(200, ['messageId' => 'm1', 'timestamp' => 123]);+ $client = $backend->makeClient();+ $result = $client->messages->editMessage('s1', ['chatId' => '[email protected]', 'messageId' => 'm1', 'body' => 'edited']);+ $call = $backend->lastCall();+ $this->assertSame('POST', $call['method']);+ $this->assertSame('/api/sessions/s1/messages/edit', $call['path']);+ $this->assertSame(['chatId' => '[email protected]', 'messageId' => 'm1', 'body' => 'edited'], $call['body']);+ $this->assertSame('m1', $result['messageId']);+ }++ public function testEditMessage404MapsToNotFoundException(): void+ {+ $backend = (new MockBackend())->on(404, [+ 'statusCode' => 404,+ 'message' => 'Message not found',+ 'error' => 'Not Found',+ ]);+ $this->expectException(OpenWANotFoundException::class);+ $backend->makeClient()->messages->editMessage('s1', ['chatId' => '[email protected]', 'messageId' => 'missing', 'body' => 'x']);+ }+public function testHistoryAndReactionsPath(): void{$backend = new MockBackend();diff --git a/sdk/php/tests/ProfileCallsTest.php b/sdk/php/tests/ProfileCallsTest.phpnew file mode 100644index 000000000..aaea2a1a1--- /dev/null+++ b/sdk/php/tests/ProfileCallsTest.php@@ -0,0 +1,62 @@+<?php++declare(strict_types=1);++namespace OpenWA\Tests;++use OpenWA\Exceptions\OpenWANotFoundException;+use PHPUnit\Framework\TestCase;++class ProfileCallsTest extends TestCase+{+ public function testProfileNameStatus(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true, 'message' => 'Profile name updated']);+ $backend->on(200, ['success' => true, 'message' => 'Profile status updated']);+ $client = $backend->makeClient();+ $client->profile->setProfileName('s', 'My Business');+ $this->assertSame('PUT', $backend->calls()[0]['method']);+ $this->assertSame('/api/sessions/s/profile/name', $backend->calls()[0]['path']);+ $this->assertSame(['name' => 'My Business'], $backend->calls()[0]['body']);+ $client->profile->setProfileStatus('s', '');+ $this->assertSame('/api/sessions/s/profile/status', $backend->calls()[1]['path']);+ $this->assertSame(['status' => ''], $backend->calls()[1]['body']);+ }++ public function testProfilePictureUrlAndBase64(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true, 'message' => 'Profile picture updated']);+ $backend->on(200, ['success' => true, 'message' => 'Profile picture updated']);+ $client = $backend->makeClient();+ $client->profile->setProfilePicture('s', ['url' => 'https://example.com/avatar.jpg']);+ $this->assertSame('PUT', $backend->calls()[0]['method']);+ $this->assertSame('/api/sessions/s/profile/picture', $backend->calls()[0]['path']);+ $this->assertSame(['url' => 'https://example.com/avatar.jpg'], $backend->calls()[0]['body']);+ $client->profile->setProfilePicture('s', ['base64' => 'aW1hZ2U=', 'mimetype' => 'image/jpeg']);+ $this->assertSame(['base64' => 'aW1hZ2U=', 'mimetype' => 'image/jpeg'], $backend->calls()[1]['body']);+ }++ public function testRejectCall(): void+ {+ $backend = (new MockBackend())->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $result = $client->calls->rejectCall('s', 'call-123');+ $call = $backend->lastCall();+ $this->assertSame('POST', $call['method']);+ $this->assertSame('/api/sessions/s/calls/call-123/reject', $call['path']);+ $this->assertTrue($result['success']);+ }++ public function testRejectCall404MapsToNotFoundException(): void+ {+ $backend = (new MockBackend())->on(404, [+ 'statusCode' => 404,+ 'message' => 'Call not found or no longer ringing',+ 'error' => 'Not Found',+ ]);+ $this->expectException(OpenWANotFoundException::class);+ $backend->makeClient()->calls->rejectCall('s', 'missing');+ }+}diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpindex 0c26b4684..8568b4cc4 100644--- a/sdk/php/tests/ResourcesTest.php+++ b/sdk/php/tests/ResourcesTest.php@@ -106,6 +106,26 @@ class ResourcesTest extends TestCase$this->assertStringContainsString('/revoke', $backend->calls()[4]['url']);}+ public function testGroupJoinAndSettings(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true, 'groupId' => '[email protected]']);+ $backend->on(200, ['announce' => true, 'locked' => false]);+ $backend->on(200, ['success' => true, 'message' => 'Group settings updated']);+ $client = $backend->makeClient();+ $joined = $client->groups->joinGroup('s', 'AbCdEf123');+ $this->assertSame('POST', $backend->calls()[0]['method']);+ $this->assertSame('/api/sessions/s/groups/join', $backend->calls()[0]['path']);+ $this->assertSame(['inviteCode' => 'AbCdEf123'], $backend->calls()[0]['body']);+ $this->assertSame('[email protected]', $joined['groupId']);+ $settings = $client->groups->getGroupSettings('s', '[email protected]');+ $this->assertSame('/api/sessions/s/groups/[email protected]/settings', $backend->calls()[1]['path']);+ $this->assertTrue($settings['announce']);+ $client->groups->updateGroupSettings('s', '[email protected]', ['announce' => true, 'ephemeralSeconds' => 604800]);+ $this->assertSame('PUT', $backend->calls()[2]['method']);+ $this->assertSame(['announce' => true, 'ephemeralSeconds' => 604800], $backend->calls()[2]['body']);+ }+// ── Contacts ──────────────────────────────────────────────────────public function testContactPaths(): voiddiff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.pyindex 39b57fb50..f76b41bc2 100644--- a/sdk/python/openwa/client.py+++ b/sdk/python/openwa/client.py@@ -32,6 +32,7 @@ import httpxfrom ._http import HttpExecutor, HttpMethodfrom .resources import (+ CallsResource,CatalogResource,ChannelsResource,ChatsResource,@@ -40,6 +41,7 @@ from .resources import (HealthResource,LabelsResource,MessagesResource,+ ProfileResource,SearchResource,SessionsResource,StatusResource,@@ -149,6 +151,14 @@ class OpenWAClient:def search(self) -> SearchResource:return SearchResource(self._http)+ @property+ def profile(self) -> ProfileResource:+ return ProfileResource(self._http)++ @property+ def calls(self) -> CallsResource:+ return CallsResource(self._http)+# ── Auth ─────────────────────────────────────────────────────────def auth(self) -> AuthValidateResponse:diff --git a/sdk/python/openwa/resources/__init__.py b/sdk/python/openwa/resources/__init__.pyindex eaefeca09..dd18533dc 100644--- a/sdk/python/openwa/resources/__init__.py+++ b/sdk/python/openwa/resources/__init__.py@@ -6,6 +6,7 @@ API path group. They are constructed by :class:`openwa.client.OpenWAClient`.from __future__ import annotations+from .calls import CallsResourcefrom .catalog import CatalogResourcefrom .channels import ChannelsResourcefrom .chats import ChatsResource@@ -14,6 +15,7 @@ from .groups import GroupsResourcefrom .health import HealthResourcefrom .labels import LabelsResourcefrom .messages import MessagesResource+from .profile import ProfileResourcefrom .search import SearchResourcefrom .sessions import SessionsResourcefrom .status import StatusResource@@ -21,6 +23,7 @@ from .templates import TemplatesResourcefrom .webhooks import WebhooksResource__all__ = [+ "CallsResource","CatalogResource","ChannelsResource","ChatsResource",@@ -29,6 +32,7 @@ __all__ = ["HealthResource","LabelsResource","MessagesResource",+ "ProfileResource","SearchResource","SessionsResource","StatusResource",diff --git a/sdk/python/openwa/resources/calls.py b/sdk/python/openwa/resources/calls.pynew file mode 100644index 000000000..395690f1b--- /dev/null+++ b/sdk/python/openwa/resources/calls.py@@ -0,0 +1,28 @@+"""Calls resource — incoming-call handling.++Backed by ``src/modules/call/call.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import SuccessResult++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class CallsResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def reject_call(self, session_id: str, call_id: str) -> SuccessResult:+ """Reject a ringing incoming call (the id comes from the ``call.received`` event).++ Requires an OPERATOR-level key. 404 when the call is not found or no longer ringing.+ """+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/calls/{quote_segment(call_id)}/reject"+ )diff --git a/sdk/python/openwa/resources/groups.py b/sdk/python/openwa/resources/groups.pyindex 5494cab8a..0ad9330c6 100644--- a/sdk/python/openwa/resources/groups.py+++ b/sdk/python/openwa/resources/groups.py@@ -11,8 +11,11 @@ from .._http import quote_segmentfrom ..types import (CreateGroupRequest,GroupInfo,+ GroupSettings,GroupSummary,InviteCodeResponse,+ JoinGroupRequest,+ JoinGroupResponse,SuccessResult,)@@ -85,3 +88,23 @@ class GroupsResource:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/invite-code/revoke")++ def join_group(self, session_id: str, body: JoinGroupRequest) -> JoinGroupResponse:+ """Join a group via an invite code. Requires an OPERATOR-level key."""+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups/join", body=body)++ def get_group_settings(self, session_id: str, group_id: str) -> GroupSettings:+ """Read the group's announce/locked/ephemeral settings."""+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/settings"+ )++ def update_group_settings(self, session_id: str, group_id: str, body: GroupSettings) -> SuccessResult:+ """Update group settings — at least one of announce/locked/ephemeralSeconds is required.++ Requires an OPERATOR-level key. ``ephemeralSeconds`` is unsupported on the+ whatsapp-web.js engine (the request then fails with 501).+ """+ return self._http.request(+ "PUT", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/settings", body=body+ )diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex 9dcd1a2f0..369cbca71 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -14,6 +14,7 @@ from ..types import (BulkMessageResponse,ChatHistoryMessage,DeleteMessageRequest,+ EditMessageRequest,ForwardMessageRequest,ListMessagesQuery,MessageHistoryQuery,@@ -85,6 +86,10 @@ class MessagesResource:def delete(self, session_id: str, body: DeleteMessageRequest) -> SuccessResult:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/delete", body=body)+ def edit_message(self, session_id: str, body: EditMessageRequest) -> MessageResponse:+ """Edit the text of a message sent by this account. 404 when the message is not found."""+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/edit", body=body)+def history(self, session_id: str, chat_id: str, query: MessageHistoryQuery | None = None) -> list[ChatHistoryMessage]:diff --git a/sdk/python/openwa/resources/profile.py b/sdk/python/openwa/resources/profile.pynew file mode 100644index 000000000..3d5fe6c83--- /dev/null+++ b/sdk/python/openwa/resources/profile.py@@ -0,0 +1,39 @@+"""Profile resource — the session account's own profile (name, status, picture).++Backed by ``src/modules/profile/profile.controller.ts``.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .._http import quote_segment+from ..types import (+ SetProfileNameRequest,+ SetProfilePictureRequest,+ SetProfileStatusRequest,+ SuccessResult,+)++if TYPE_CHECKING:+ from .._http import HttpExecutor+++class ProfileResource:+ def __init__(self, http: "HttpExecutor") -> None:+ self._http = http++ def set_profile_name(self, session_id: str, body: SetProfileNameRequest) -> SuccessResult:+ """Set the account display name. Requires an OPERATOR-level key."""+ return self._http.request("PUT", f"/api/sessions/{quote_segment(session_id)}/profile/name", body=body)++ def set_profile_status(self, session_id: str, body: SetProfileStatusRequest) -> SuccessResult:+ """Set the account about/status text (empty clears). Requires an OPERATOR-level key."""+ return self._http.request("PUT", f"/api/sessions/{quote_segment(session_id)}/profile/status", body=body)++ def set_profile_picture(self, session_id: str, body: SetProfilePictureRequest) -> SuccessResult:+ """Set the account profile picture — ``url`` OR ``base64`` (+ ``mimetype``).++ Requires an OPERATOR-level key.+ """+ return self._http.request("PUT", f"/api/sessions/{quote_segment(session_id)}/profile/picture", body=body)diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 81e603503..9a93f809d 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -23,9 +23,8 @@ BulkMessageType = Literal["text", "image", "video", "audio", "document"]WebhookEvent = Literal["message.received", "message.sent", "message.ack", "message.failed", "message.revoked","message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",- "session.disconnected",- # Reserved: accepted on subscribe but not dispatched yet.- "group.join", "group.leave", "group.update",+ "session.disconnected", "session.reconnect_loop",+ "group.join", "group.leave", "group.update", "call.received","*",]@@ -163,6 +162,13 @@ class DeleteMessageRequest(TypedDict, total=False):forEveryone: bool+class EditMessageRequest(TypedDict):+ chatId: Jid+ messageId: str+ # Same 4096-char cap as SendTextRequest.text — an edit cannot exceed what a send allows.+ body: str++class SendTemplateRequest(TypedDict, total=False):# chatId required; provide exactly one of templateId / templateName.# Modeled total=False (callers pass plain dicts); the backend validates.@@ -429,6 +435,46 @@ class InviteCodeResponse(TypedDict, total=False):message: str+class JoinGroupRequest(TypedDict):+ # The token from a https://chat.whatsapp.com/<code> link.+ inviteCode: str+++class JoinGroupResponse(TypedDict, total=False):+ success: bool+ groupId: Jid+++# All fields optional, but an update must carry at least one — modeled total=False+# (callers pass plain dicts); the backend validates (empty body -> 400).+# `ephemeralSeconds` is the disappearing-messages timer (0 disables); the+# whatsapp-web.js engine does not support it (request -> 501).+class GroupSettings(TypedDict, total=False):+ announce: bool+ locked: bool+ ephemeralSeconds: int+++# ── Profile (own account) ─────────────────────────────────────────+++class SetProfileNameRequest(TypedDict):+ # WhatsApp limit: 25 characters.+ name: str+++class SetProfileStatusRequest(TypedDict):+ # May be empty to clear the about/status text (WhatsApp limit: 139 characters).+ status: str+++class SetProfilePictureRequest(TypedDict, total=False):+ # Provide `url` OR `base64` (+ `mimetype`); the backend validates.+ url: str+ base64: str+ mimetype: str++# ── Webhook ───────────────────────────────────────────────────────diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 0fa02d436..5905418f0 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -110,7 +110,7 @@ class TestClientCore:def test_exposes_all_resources(self):client = make_client(MockBackend())- for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "search"]:+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "search", "profile", "calls"]:assert hasattr(client, r)@@ -179,6 +179,13 @@ class TestMessages:assert "/messages/react" in backend.calls[-2].urlassert "/messages/delete" in backend.calls[-1].url+ def test_edit_message(self):+ backend = MockBackend().on("POST", "/messages/edit", body={"messageId": "m1", "timestamp": 3})+ res = make_client(backend).messages.edit_message("s1", {"chatId": "[email protected]", "messageId": "m1", "body": "edited"})+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s1/messages/edit"+ assert backend.last_call.body == {"chatId": "[email protected]", "messageId": "m1", "body": "edited"}+ assert res["messageId"] == "m1"+def test_history_and_reactions_path(self):backend = MockBackend()backend.on("GET", "/history", body=[])@@ -319,6 +326,72 @@ class TestGroups:assert "/revoke" in backend.calls[-1].url+ def test_join_group(self):+ backend = MockBackend().on("POST", "/groups/join", body={"success": True, "groupId": "[email protected]"})+ res = make_client(backend).groups.join_group("s", {"inviteCode": "ABCxyz"})+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/groups/join"+ assert backend.last_call.body == {"inviteCode": "ABCxyz"}+ assert res["groupId"] == "[email protected]"++ def test_group_settings_get_and_update(self):+ backend = MockBackend()+ backend.on("GET", "/settings", body={"announce": True, "locked": False, "ephemeralSeconds": 604800})+ backend.on("PUT", "/settings", body={"success": True, "message": "Group settings updated"})+ client = make_client(backend)+ settings = client.groups.get_group_settings("s", "[email protected]")+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions/s/groups/[email protected]/settings"+ assert settings["announce"] is True+ assert settings["ephemeralSeconds"] == 604800+ res = client.groups.update_group_settings("s", "[email protected]", {"announce": False, "ephemeralSeconds": 0})+ assert backend.calls[-1].method == "PUT"+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions/s/groups/[email protected]/settings"+ assert backend.calls[-1].body == {"announce": False, "ephemeralSeconds": 0}+ assert res["success"] is True+++class TestProfile:+ def test_set_profile_name_and_status(self):+ backend = MockBackend()+ backend.on("PUT", "/profile/name", body={"success": True, "message": "Profile name updated"})+ backend.on("PUT", "/profile/status", body={"success": True, "message": "Profile status updated"})+ client = make_client(backend)+ client.profile.set_profile_name("s", {"name": "My Business"})+ assert backend.calls[-1].method == "PUT"+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions/s/profile/name"+ assert backend.calls[-1].body == {"name": "My Business"}+ # An empty status clears the about text; the body is forwarded verbatim.+ client.profile.set_profile_status("s", {"status": ""})+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions/s/profile/status"+ assert backend.calls[-1].body == {"status": ""}++ def test_set_profile_picture_url_and_base64(self):+ backend = MockBackend().on("PUT", "/profile/picture", body={"success": True, "message": "Profile picture updated"})+ client = make_client(backend)+ client.profile.set_profile_picture("s", {"url": "https://example.com/avatar.jpg"})+ assert backend.calls[-1].method == "PUT"+ assert backend.calls[-1].url == "http://localhost:2785/api/sessions/s/profile/picture"+ assert backend.calls[-1].body == {"url": "https://example.com/avatar.jpg"}+ client.profile.set_profile_picture("s", {"base64": "aGVsbG8=", "mimetype": "image/jpeg"})+ assert backend.calls[-1].body == {"base64": "aGVsbG8=", "mimetype": "image/jpeg"}+++class TestCalls:+ def test_reject_call(self):+ backend = MockBackend().on("POST", "/reject", body={"success": True})+ res = make_client(backend).calls.reject_call("s", "CALL1")+ assert backend.last_call.method == "POST"+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/calls/CALL1/reject"+ assert backend.last_call.body is None # no request body+ assert res["success"] is True++ def test_reject_call_404_maps_to_not_found(self):+ backend = MockBackend().on("POST", "/reject", status=404, body={+ "statusCode": 404, "message": "Call not found or no longer ringing", "error": "Not Found"+ })+ with pytest.raises(OpenWANotFoundError):+ make_client(backend).calls.reject_call("s", "CALL1")++class TestContacts:def test_paths(self):backend = MockBackend()@@ -502,7 +575,7 @@ class TestLabelsChannelsCatalog:def test_client_exposes_all_resources(self):client = make_client(MockBackend())- for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "labels", "channels", "catalog", "templates", "search"]:+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "labels", "channels", "catalog", "templates", "search", "profile", "calls"]:assert hasattr(client, r)diff --git a/src/app.module.ts b/src/app.module.tsindex 18cdfa693..9f4711591 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -23,6 +23,8 @@ import { InfraModule } from './modules/infra/infra.module';import { EventsModule } from './modules/events/events.module';import { ContactModule } from './modules/contact/contact.module';import { GroupModule } from './modules/group/group.module';+import { ProfileModule } from './modules/profile/profile.module';+import { CallModule } from './modules/call/call.module';import { LabelModule } from './modules/label/label.module';import { ChannelModule } from './modules/channel/channel.module';import { CacheModule } from './common/cache';@@ -275,6 +277,8 @@ if (dashboardServingEnabled && dashboardBuildPresent) {InfraModule,ContactModule,GroupModule,+ ProfileModule, // Own-profile API (name / status / picture)+ CallModule, // Incoming-call API (reject a ringing call)LabelModule, // Phase 3: Labels ManagementChannelModule, // Phase 3: Channels/NewsletterStatsModule, // Phase 3: Statistics Dashboarddiff --git a/src/common/errors/call-not-found.error.spec.ts b/src/common/errors/call-not-found.error.spec.tsnew file mode 100644index 000000000..65545dc6d--- /dev/null+++ b/src/common/errors/call-not-found.error.spec.ts@@ -0,0 +1,16 @@+import { NotFoundException } from '@nestjs/common';+import { CallNotFoundError } from './call-not-found.error';++// Rejecting an unknown/expired call id must surface as HTTP 404, not a raw 500 — same mapping+// discipline as MessageNotFoundError (built-in NestJS handler, no custom global filter).+describe('CallNotFoundError', () => {+ it('is a NotFoundException -> HTTP 404 without a custom global filter', () => {+ const err = new CallNotFoundError('CALL1');+ expect(err).toBeInstanceOf(NotFoundException);+ expect(err.getStatus()).toBe(404);+ });++ it('formats the message with the call id', () => {+ expect(new CallNotFoundError('CALL1').message).toBe('Call CALL1 not found or no longer ringing');+ });+});diff --git a/src/common/errors/call-not-found.error.ts b/src/common/errors/call-not-found.error.tsnew file mode 100644index 000000000..186b71dc3--- /dev/null+++ b/src/common/errors/call-not-found.error.ts@@ -0,0 +1,15 @@+import { NotFoundException } from '@nestjs/common';++/**+ * Thrown by the engine layer when a call referenced by id can't be rejected — it is not (or no+ * longer) ringing: the id was never seen, the call already ended, or the adapter's live-call+ * cache entry expired (calls ring for roughly a minute).+ *+ * Extends NestJS `NotFoundException` so it maps to **HTTP 404** through the built-in exception+ * handler — no custom global filter required. Mirrors {@link MessageNotFoundError}.+ */+export class CallNotFoundError extends NotFoundException {+ constructor(callId: string) {+ super(`Call ${callId} not found or no longer ringing`);+ }+}diff --git a/src/common/errors/engine-refused.error.spec.ts b/src/common/errors/engine-refused.error.spec.tsnew file mode 100644index 000000000..31fd536dc--- /dev/null+++ b/src/common/errors/engine-refused.error.spec.ts@@ -0,0 +1,20 @@+import { ForbiddenException } from '@nestjs/common';+import { EngineRefusedError } from './engine-refused.error';++// A WhatsApp-side refusal (editing someone else's message, a settings write without admin rights)+// thrown as a generic Error surfaces as HTTP 500. EngineRefusedError extends ForbiddenException so+// NestJS maps it to 403 through the built-in handler (no global filter) — same mapping discipline+// as CallNotFoundError.+describe('EngineRefusedError', () => {+ it('is a ForbiddenException -> HTTP 403 without a custom global filter', () => {+ const err = new EngineRefusedError('admin rights required');+ expect(err).toBeInstanceOf(ForbiddenException);+ expect(err.getStatus()).toBe(403);+ });++ it('carries the refusal detail as the message', () => {+ expect(new EngineRefusedError("only the account's own messages can be edited").message).toBe(+ "only the account's own messages can be edited",+ );+ });+});diff --git a/src/common/errors/engine-refused.error.ts b/src/common/errors/engine-refused.error.tsnew file mode 100644index 000000000..2c166cd67--- /dev/null+++ b/src/common/errors/engine-refused.error.ts@@ -0,0 +1,15 @@+import { ForbiddenException } from '@nestjs/common';++/**+ * Thrown by the engine layer when WhatsApp refuses an otherwise well-formed operation — e.g. editing+ * a message that is not the account's own, a group settings write without admin rights, or a profile+ * change the engine reports as rejected. The request was valid; the refusal happened WhatsApp-side.+ *+ * Extends NestJS `ForbiddenException` so it maps to **HTTP 403** through the built-in exception+ * handler — no custom global filter required. Mirrors {@link CallNotFoundError} (404).+ */+export class EngineRefusedError extends ForbiddenException {+ constructor(detail: string) {+ super(detail);+ }+}diff --git a/src/common/errors/group-not-found.error.spec.ts b/src/common/errors/group-not-found.error.spec.tsnew file mode 100644index 000000000..f1d431eee--- /dev/null+++ b/src/common/errors/group-not-found.error.spec.ts@@ -0,0 +1,17 @@+import { NotFoundException } from '@nestjs/common';+import { GroupNotFoundError } from './group-not-found.error';++// A group settings write against an unknown/non-group id thrown as a generic Error surfaces as+// HTTP 500. GroupNotFoundError extends NotFoundException so NestJS maps it to 404 through the+// built-in handler (no global filter) — same mapping discipline as MessageNotFoundError.+describe('GroupNotFoundError', () => {+ it('is a NotFoundException -> HTTP 404 without a custom global filter', () => {+ const err = new GroupNotFoundError('[email protected]');+ expect(err).toBeInstanceOf(NotFoundException);+ expect(err.getStatus()).toBe(404);+ });++ it('formats the message with the group id', () => {+ expect(new GroupNotFoundError('[email protected]').message).toBe('Group [email protected] not found');+ });+});diff --git a/src/common/errors/group-not-found.error.ts b/src/common/errors/group-not-found.error.tsnew file mode 100644index 000000000..7d560e341--- /dev/null+++ b/src/common/errors/group-not-found.error.ts@@ -0,0 +1,15 @@+import { NotFoundException } from '@nestjs/common';++/**+ * Thrown by the engine layer when a group id does not resolve to a group chat — the id is unknown+ * (whatsapp-web.js `getChatById` resolves undefined rather than throwing) or it addresses a 1:1+ * chat instead of a group. Same message shape as GroupService.getGroupInfo's 404.+ *+ * Extends NestJS `NotFoundException` so it maps to **HTTP 404** through the built-in exception+ * handler — no custom global filter required. Mirrors {@link MessageNotFoundError}.+ */+export class GroupNotFoundError extends NotFoundException {+ constructor(groupId: string) {+ super(`Group ${groupId} not found`);+ }+}diff --git a/src/common/errors/invalid-invite-code.error.spec.ts b/src/common/errors/invalid-invite-code.error.spec.tsnew file mode 100644index 000000000..6ad8a1966--- /dev/null+++ b/src/common/errors/invalid-invite-code.error.spec.ts@@ -0,0 +1,19 @@+import { BadRequestException } from '@nestjs/common';+import { InvalidInviteCodeError } from './invalid-invite-code.error';++// Joining via an invalid/expired/revoked invite code is a client error, not a server fault:+// InvalidInviteCodeError extends BadRequestException so NestJS maps it to 400 through the built-in+// handler (no global filter) — same mapping discipline as CallNotFoundError.+describe('InvalidInviteCodeError', () => {+ it('is a BadRequestException -> HTTP 400 without a custom global filter', () => {+ const err = new InvalidInviteCodeError();+ expect(err).toBeInstanceOf(BadRequestException);+ expect(err.getStatus()).toBe(400);+ });++ it('states the possible causes in the message', () => {+ expect(new InvalidInviteCodeError().message).toBe(+ 'could not join the group — the invite code may be invalid, expired, or revoked',+ );+ });+});diff --git a/src/common/errors/invalid-invite-code.error.ts b/src/common/errors/invalid-invite-code.error.tsnew file mode 100644index 000000000..caaad4b18--- /dev/null+++ b/src/common/errors/invalid-invite-code.error.ts@@ -0,0 +1,15 @@+import { BadRequestException } from '@nestjs/common';++/**+ * Thrown by the engine layer when a group invite code cannot be redeemed — it is invalid, expired,+ * or revoked. Both engines report this without a distinguishing detail: whatsapp-web.js throws a+ * page-side error (or resolves a gid-less result), Baileys resolves undefined or fails the IQ.+ *+ * Extends NestJS `BadRequestException` so it maps to **HTTP 400** through the built-in exception+ * handler — no custom global filter required. Mirrors {@link CallNotFoundError} (404).+ */+export class InvalidInviteCodeError extends BadRequestException {+ constructor() {+ super('could not join the group — the invite code may be invalid, expired, or revoked');+ }+}diff --git a/src/engine/adapters/baileys-group-mapper.spec.ts b/src/engine/adapters/baileys-group-mapper.spec.tsindex 11042b3f1..8e8dd32ff 100644--- a/src/engine/adapters/baileys-group-mapper.spec.ts+++ b/src/engine/adapters/baileys-group-mapper.spec.ts@@ -59,6 +59,22 @@ describe('mapBaileysGroupInfo', () => {]);});+ it('maps the group settings fields (announce / restrict→locked / ephemeralDuration→ephemeralSeconds)', () => {+ const info = mapBaileysGroupInfo(meta({ announce: true, restrict: true, ephemeralDuration: 86400 }));+ expect(info.announce).toBe(true);+ expect(info.locked).toBe(true);+ expect(info.ephemeralSeconds).toBe(86400);+ });++ it('leaves the settings fields undefined when the metadata does not carry them', () => {+ const m = meta();+ delete m.announce;+ const info = mapBaileysGroupInfo(m);+ expect(info.announce).toBeUndefined();+ expect(info.locked).toBeUndefined();+ expect(info.ephemeralSeconds).toBeUndefined();+ });+it('canonicalizes participant ids and owner through the supplied normalizer (lid -> resolved phone)', () => {// A lid-addressed group: participants/owner arrive as @lid. The normalizer (the adapter's// session-store) resolves the known lid to its phone so both sides of the admin check share a dialect.diff --git a/src/engine/adapters/baileys-group-mapper.ts b/src/engine/adapters/baileys-group-mapper.tsindex 0052a6198..672d36765 100644--- a/src/engine/adapters/baileys-group-mapper.ts+++ b/src/engine/adapters/baileys-group-mapper.ts@@ -54,6 +54,9 @@ export function mapBaileysGroupInfo(metadata: GroupMetadata, normalizeJid: Norma// WhatsApp "announce" = only admins can post; surface as both isAnnounce and (members') isReadOnly (best-effort).isAnnounce: metadata.announce,isReadOnly: metadata.announce,+ announce: metadata.announce,+ locked: metadata.restrict,+ ephemeralSeconds: metadata.ephemeralDuration,linkedParentJID: metadata.linkedParent ?? null,};}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex f3d4ce80f..03cdae518 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -34,7 +34,13 @@ class FakeSock extends EventEmitter {public groupUpdateDescription = jest.fn().mockResolvedValue(undefined);public groupInviteCode = jest.fn();public groupRevokeInvite = jest.fn();+ public groupAcceptInvite = jest.fn();+ public groupSettingUpdate = jest.fn().mockResolvedValue(undefined);+ public groupToggleEphemeral = jest.fn().mockResolvedValue(undefined);public profilePictureUrl = jest.fn();+ public updateProfileName = jest.fn().mockResolvedValue(undefined);+ public updateProfileStatus = jest.fn().mockResolvedValue(undefined);+ public updateProfilePicture = jest.fn().mockResolvedValue(undefined);public updateBlockStatus = jest.fn().mockResolvedValue(undefined);public readMessages = jest.fn().mockResolvedValue(undefined);public chatModify = jest.fn().mockResolvedValue(undefined);@@ -43,6 +49,7 @@ class FakeSock extends EventEmitter {public newsletterMetadata = jest.fn();public newsletterFollow = jest.fn().mockResolvedValue(undefined);public newsletterUnfollow = jest.fn().mockResolvedValue(undefined);+ public rejectCall = jest.fn().mockResolvedValue(undefined);public signalRepository: { lidMapping: { getLIDForPN: jest.Mock } } | undefined;fire(event: string, arg: unknown): void {this.emitter.emit(event, arg);@@ -90,9 +97,19 @@ jest.mock('@whiskeysockets/baileys', () => ({}));import { BaileysAdapter } from './baileys.adapter';-import { EditedMessage, EngineStatus, EngineEventCallbacks } from '../interfaces/whatsapp-engine.interface';+import {+ EditedMessage,+ EngineStatus,+ EngineEventCallbacks,+ GroupEvent,+ IncomingCallEvent,+} from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';@@ -2008,6 +2025,13 @@ describe('BaileysAdapter store-backed ops', () => {message: { conversation: 'hi' },};+ // An outbound (own) variant of `stored` — editMessage refuses inbound keys, so its happy-path+ // tests must store a fromMe: true message.+ const ownStored = {+ key: { id: 'TARGET', remoteJid: '[email protected]', fromMe: true },+ message: { conversation: 'hi' },+ };+it('replyToMessage quotes the stored message', async () => {fakeStore.getMessage.mockResolvedValue(stored);const adapter = await ready();@@ -2095,6 +2119,74 @@ describe('BaileysAdapter store-backed ops', () => {expect(fakeSock.sendMessage).not.toHaveBeenCalled();});+ it('editMessage edits via the stored key and returns the (unchanged) message id', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeSock.sendMessage.mockResolvedValue({ key: { ...ownStored.key }, messageTimestamp: 1700000010 });+ const adapter = await ready();+ const res = await adapter.editMessage('[email protected]', 'TARGET', 'edited body');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ text: 'edited body',+ edit: ownStored.key,+ });+ expect(res).toEqual({ id: 'TARGET', timestamp: 1700000010 });+ });++ it('editMessage falls back to the requested id when the send echoes nothing back', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeSock.sendMessage.mockResolvedValue(undefined);+ const adapter = await ready();+ const res = await adapter.editMessage('[email protected]', 'TARGET', 'edited body');+ expect(res.id).toBe('TARGET');+ });++ it('editMessage throws MessageNotFoundError when the message is not in the store', async () => {+ fakeStore.getMessage.mockResolvedValue(null);+ const adapter = await ready();+ await expect(adapter.editMessage('[email protected]', 'GONE', 'x')).rejects.toBeInstanceOf(+ MessageNotFoundError,+ );+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ });++ it('editMessage refuses an inbound (not own) message with EngineRefusedError (403), no send', async () => {+ fakeStore.getMessage.mockResolvedValue(stored); // the shared fixture is fromMe: false+ const adapter = await ready();+ await expect(adapter.editMessage('[email protected]', 'TARGET', 'x')).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ });++ it('editMessage throws MessageNotFoundError when the stored key belongs to another chat', async () => {+ fakeStore.getMessage.mockResolvedValue({+ ...ownStored,+ key: { ...ownStored.key, remoteJid: '[email protected]' },+ });+ const adapter = await ready();+ await expect(adapter.editMessage('[email protected]', 'TARGET', 'x')).rejects.toBeInstanceOf(+ MessageNotFoundError,+ );+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();+ });++ it('editMessage matches the chat across dialects (@c.us request vs @s.whatsapp.net stored key)', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeSock.sendMessage.mockResolvedValue(undefined);+ const adapter = await ready();+ await expect(adapter.editMessage('[email protected]', 'TARGET', 'x')).resolves.toBeDefined();+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'x', edit: ownStored.key });+ });++ it('editMessage sends to the LID-resolved deliverable jid (463 tctoken fix, same as the send path)', async () => {+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeSock.sendMessage.mockResolvedValue(undefined);+ fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue('484848@lid') } };+ const adapter = await ready();+ await adapter.editMessage('[email protected]', 'TARGET', 'edited body');+ expect(fakeSock.signalRepository.lidMapping.getLIDForPN).toHaveBeenCalledWith('[email protected]');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', { text: 'edited body', edit: ownStored.key });+ });+it('addLabelToChat wires 1:1 to sock.addChatLabel(chatId, labelId)', async () => {const adapter = await ready();await adapter.addLabelToChat('[email protected]', 'LABEL8');@@ -2320,6 +2412,87 @@ describe('BaileysAdapter group management', () => {expect(await adapter.revokeGroupInviteCode('[email protected]')).toBe('NEW456');});+ it('joinGroupViaInviteCode returns the joined group id (neutral dialect)', async () => {+ fakeSock.groupAcceptInvite.mockResolvedValue('[email protected]');+ const adapter = await ready();+ await expect(adapter.joinGroupViaInviteCode('CODE123')).resolves.toBe('[email protected]');+ expect(fakeSock.groupAcceptInvite).toHaveBeenCalledWith('CODE123');+ });++ it('joinGroupViaInviteCode throws InvalidInviteCodeError (400) when Baileys resolves undefined', async () => {+ // Baileys' groupAcceptInvite resolves undefined for an invalid/expired/revoked invite.+ fakeSock.groupAcceptInvite.mockResolvedValue(undefined);+ const adapter = await ready();+ const err = await adapter.joinGroupViaInviteCode('BAD').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(InvalidInviteCodeError);+ expect((err as Error).message).toMatch(/invalid, expired, or revoked/);+ });++ it('joinGroupViaInviteCode maps an IQ error to InvalidInviteCodeError (400)', async () => {+ // A rejected groupAcceptInvite (not-authorized / gone IQ) is the same client-facing cause.+ fakeSock.groupAcceptInvite.mockRejectedValue(new Error('not-authorized'));+ const adapter = await ready();+ await expect(adapter.joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(InvalidInviteCodeError);+ });++ it.each([+ ['setGroupMessagesAdminsOnly', true, 'announcement'],+ ['setGroupMessagesAdminsOnly', false, 'not_announcement'],+ ['setGroupInfoAdminsOnly', true, 'locked'],+ ['setGroupInfoAdminsOnly', false, 'unlocked'],+ ])('%s(%s) maps to groupSettingUpdate %s', async (method, value, setting) => {+ const adapter = await ready();+ await (adapter as unknown as Record<string, (g: string, v: boolean) => Promise<void>>)[method](+ '[email protected]',+ value,+ );+ expect(fakeSock.groupSettingUpdate).toHaveBeenCalledWith('[email protected]', setting);+ });++ it('setGroupEphemeral delegates to groupToggleEphemeral (0 disables)', async () => {+ const adapter = await ready();+ await adapter.setGroupEphemeral('[email protected]', 86400);+ expect(fakeSock.groupToggleEphemeral).toHaveBeenCalledWith('[email protected]', 86400);+ await adapter.setGroupEphemeral('[email protected]', 0);+ expect(fakeSock.groupToggleEphemeral).toHaveBeenCalledWith('[email protected]', 0);+ });++ it('getGroupInfo populates announce/locked/ephemeralSeconds from the metadata', async () => {+ fakeSock.groupMetadata.mockResolvedValueOnce({+ ...META,+ announce: true,+ restrict: true,+ ephemeralDuration: 7776000,+ });+ const adapter = await ready();+ const info = await adapter.getGroupInfo('[email protected]');+ expect(info?.announce).toBe(true);+ expect(info?.locked).toBe(true);+ expect(info?.ephemeralSeconds).toBe(7776000);+ });++ it('setProfileName / setProfileStatus delegate to the socket', async () => {+ const adapter = await ready();+ await adapter.setProfileName('New Name');+ expect(fakeSock.updateProfileName).toHaveBeenCalledWith('New Name');+ await adapter.setProfileStatus('about text');+ expect(fakeSock.updateProfileStatus).toHaveBeenCalledWith('about text');+ });++ it('setProfilePicture resolves the media and uploads it under the own JID (device suffix stripped)', async () => {+ // fakeSock.user.id is '628999:[email protected]' (see beforeEach) — the own JID the adapter+ // normalizes the same way as everywhere else.+ const adapter = await ready();+ await adapter.setProfilePicture({ mimetype: 'image/png', data: Buffer.from('IMG').toString('base64') });+ expect(fakeSock.updateProfilePicture).toHaveBeenCalledWith('[email protected]', Buffer.from('IMG'));+ });++ it('setProfilePicture throws when the own JID is not known', async () => {+ fakeSock.user = undefined;+ const adapter = await ready();+ await expect(adapter.setProfilePicture({ mimetype: 'image/png', data: 'AAAA' })).rejects.toThrow(/own JID/);+ });+it('group ops reject with EngineNotReadyError before connect', async () => {const adapter = newAdapter();await adapter.initialize({});@@ -2327,6 +2500,394 @@ describe('BaileysAdapter group management', () => {});});+describe('BaileysAdapter group events (group-participants.update / groups.update)', () => {+ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ });++ const readyWithGroupEvents = async (): Promise<{ onGroupEvent: jest.Mock }> => {+ const onGroupEvent = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onGroupEvent }));+ fakeSock.fire('connection.update', { connection: 'open' });+ return { onGroupEvent };+ };++ const firstEvent = (mock: jest.Mock): GroupEvent => {+ const calls = mock.mock.calls as Array<[GroupEvent]>;+ if (!calls[0]) throw new Error('Expected a group event');+ return calls[0][0];+ };++ it('maps action add to a join GroupEvent, normalizing the v7 participant objects to neutral ids', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();+ const now = jest.spyOn(Date, 'now').mockReturnValue(1782000000123);++ try {+ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ author: '[email protected]',+ action: 'add',+ // The v7 wire shape: parsed JSON objects ({ id, phoneNumber?, lid?, ... }), not JID strings+ // (Socket/messages-recv.js stringifies them into messageStubParameters).+ participants: [+ { id: '[email protected]', admin: null },+ // A lid-addressed participant carrying its phone twin: the inline phoneNumber wins, so the+ // neutral id does not depend on whether the lid->pn mapping was learned.+ { id: '555@lid', phoneNumber: '[email protected]' },+ ],+ });+ } finally {+ now.mockRestore();+ }++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent)).toEqual({+ kind: 'join',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]', '[email protected]'],+ timestamp: 1782000000, // the Baileys event is undated: stamped at receipt+ });+ });++ it('maps action remove to a leave GroupEvent', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ author: '[email protected]',+ action: 'remove',+ participants: [{ id: '[email protected]' }],+ });++ expect(firstEvent(onGroupEvent)).toMatchObject({+ kind: 'leave',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ });+ });++ it.each(['promote', 'demote', 'modify'])('skips action %s (no membership change)', async action => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ author: '[email protected]',+ action,+ participants: [{ id: '[email protected]' }],+ });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });++ it('still normalizes plain-string participants (the pre-v7 shape)', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ author: '[email protected]',+ action: 'add',+ participants: ['[email protected]'],+ });++ expect(firstEvent(onGroupEvent).participantIds).toEqual(['[email protected]']);+ });++ it('resolves a lid-only participant through the learned lid->pn mapping, else keeps the lid', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ action: 'add',+ participants: [{ id: '111@lid' }],+ });+ // No mapping known yet: the privacy id is kept, not faked into a phone number.+ expect(firstEvent(onGroupEvent).participantIds).toEqual(['111@lid']);++ fakeSock.fire('lid-mapping.update', { lid: '111@lid', pn: '[email protected]' });+ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ action: 'add',+ participants: [{ id: '111@lid' }],+ });+ const calls = onGroupEvent.mock.calls as Array<[GroupEvent]>;+ expect(calls[1][0].participantIds).toEqual(['[email protected]']);+ });++ it('prefers authorPn over a lid author for the neutral actorId', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ author: '999@lid',+ authorPn: '[email protected]',+ action: 'add',+ participants: [{ id: '[email protected]' }],+ });++ expect(firstEvent(onGroupEvent).actorId).toBe('[email protected]');+ });++ it('omits actorId when the event reports no author at all', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group-participants.update', {+ id: '[email protected]',+ action: 'add',+ participants: [{ id: '[email protected]' }],+ });++ expect(firstEvent(onGroupEvent).actorId).toBeUndefined();+ });++ it('maps groups.update entries to update GroupEvents with the neutral changes delta', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('groups.update', [+ { id: '[email protected]', subject: 'New name', author: '[email protected]' },+ { id: '[email protected]', desc: 'New description' },+ { id: '[email protected]', announce: true },+ { id: '[email protected]', restrict: false },+ ]);++ const calls = onGroupEvent.mock.calls as Array<[GroupEvent]>;+ expect(calls).toHaveLength(4);+ expect(calls[0][0]).toMatchObject({+ kind: 'update',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: [],+ changes: { subject: 'New name' },+ });+ expect(calls[1][0].changes).toEqual({ description: 'New description' }); // desc -> description+ expect(calls[2][0].changes).toEqual({ announce: true });+ expect(calls[3][0].changes).toEqual({ locked: false }); // restrict -> locked+ });++ it('still emits an update with empty changes for unmodeled fields (inviteCode & co.)', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('groups.update', [{ id: '[email protected]', inviteCode: 'ABCDEF' }]);++ // Parity with the wwebjs adapter: the occurrence is never dropped silently.+ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent)).toMatchObject({ kind: 'update', groupId: '[email protected]', changes: {} });+ });++ it('skips groups.update entries without an id but still emits the rest', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('groups.update', [{ subject: 'orphan' }, { id: '[email protected]', subject: 'Kept' }]);++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent).changes).toEqual({ subject: 'Kept' });+ });++ it('skips full-metadata snapshots (groupFetchAllParticipating emits them via the same event)', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ // The extractGroupMetadata shape emitted by groupFetchAllParticipating (Socket/groups.js:56) —+ // fired on every connect (hydrateNames) and every REST getGroups(). Treating it as a delta+ // would flood consumers with bogus group.update webhooks on each reconnect / GET /groups.+ fakeSock.fire('groups.update', [+ {+ id: '[email protected]',+ subject: 'Existing name',+ desc: 'Existing description',+ announce: false,+ restrict: false,+ participants: [{ id: '[email protected]', admin: 'admin' }],+ creation: 1700000000,+ subjectTime: 1700000001,+ owner: '[email protected]',+ size: 2,+ },+ // A real delta in the same batch still emits (process-message.js emitGroupUpdate shape).+ { id: '[email protected]', subject: 'Renamed' },+ ]);++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent).changes).toEqual({ subject: 'Renamed' });+ });+});++describe('BaileysAdapter call events (call offer) + rejectCall', () => {+ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ });++ const readyWithCallEvents = async (): Promise<{ adapter: BaileysAdapter; onCall: jest.Mock }> => {+ const onCall = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onCall }));+ fakeSock.fire('connection.update', { connection: 'open' });+ return { adapter, onCall };+ };++ const offer = (over: Record<string, unknown> = {}) => ({+ chatId: '[email protected]',+ from: '[email protected]',+ id: 'CALL1',+ date: new Date(1782000000000),+ isVideo: false,+ isGroup: false,+ status: 'offer',+ offline: false,+ ...over,+ });++ const firstCallEvent = (mock: jest.Mock): IncomingCallEvent => {+ const calls = mock.mock.calls as Array<[IncomingCallEvent]>;+ if (!calls[0]) throw new Error('Expected a call event');+ return calls[0][0];+ };++ it('maps an offer to a neutral IncomingCallEvent (timestamp from the event date)', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer({ isVideo: true })]);++ expect(onCall).toHaveBeenCalledTimes(1);+ expect(firstCallEvent(onCall)).toEqual({+ callId: 'CALL1',+ from: '[email protected]', // @s.whatsapp.net folded to the neutral @c.us+ isVideo: true,+ isGroup: false,+ timestamp: 1782000000,+ });+ });++ it('prefers callerPn over a lid caller for the neutral from', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer({ from: '555@lid', callerPn: '[email protected]' })]);++ expect(firstCallEvent(onCall).from).toBe('[email protected]');+ });++ it.each(['ringing', 'preaccept', 'transport', 'relaylatency', 'timeout', 'reject', 'accept', 'terminate'])(+ 'skips status %s (lifecycle update, not a new incoming call)',+ async status => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer({ status })]);++ expect(onCall).not.toHaveBeenCalled();+ },+ );++ it('rejectCall passes the cached raw callFrom JID to the socket and evicts the entry', async () => {+ const { adapter } = await readyWithCallEvents();+ fakeSock.fire('call', [offer({ from: '555@lid', callerPn: '[email protected]' })]);++ await adapter.rejectCall('CALL1');++ // The raw `from` (the lid JID), NOT the neutralized/phone twin — Baileys expects the wire id.+ expect(fakeSock.rejectCall).toHaveBeenCalledWith('CALL1', '555@lid');+ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ });++ it('rejectCall on an unknown id throws CallNotFoundError (HTTP 404)', async () => {+ const { adapter } = await readyWithCallEvents();++ await expect(adapter.rejectCall('NOPE')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });++ it('rejectCall on an expired entry throws CallNotFoundError without touching the socket', async () => {+ const { adapter } = await readyWithCallEvents();+ fakeSock.fire('call', [offer()]);+ // Age the cached entry past the TTL (calls ring ~a minute; the handle dies with the call).+ const cache = (adapter as unknown as { liveCalls: Map<string, { expiresAt: number }> }).liveCalls;+ cache.get('CALL1')!.expiresAt = Date.now() - 1;++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });++ it('teardown clears the live-call cache (reject after disconnect -> not found)', async () => {+ const { adapter } = await readyWithCallEvents();+ fakeSock.fire('call', [offer()]);++ await adapter.disconnect();++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });++ it('skips an offline-replayed offer (missed while disconnected) — no event, nothing cached', async () => {+ const { adapter, onCall } = await readyWithCallEvents();++ // Baileys replays offers for calls missed while offline with offline: true+ // (messages-recv.js:1458); the call is long dead, so rejecting it later must 404.+ fakeSock.fire('call', [offer({ offline: true })]);++ expect(onCall).not.toHaveBeenCalled();+ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });++ it("skips an offer from the account's own JID (relayed outgoing-call signaling)", async () => {+ const { onCall } = await readyWithCallEvents();++ // fakeSock.user.id is 628999:[email protected] -> own neutral id [email protected].+ fakeSock.fire('call', [offer({ from: '[email protected]', chatId: '[email protected]' })]);++ expect(onCall).not.toHaveBeenCalled();+ });++ it('skips an offer whose chatId is the own JID even when from is someone else', async () => {+ const { onCall } = await readyWithCallEvents();++ fakeSock.fire('call', [offer({ from: '[email protected]', chatId: '628999:[email protected]' })]);++ expect(onCall).not.toHaveBeenCalled();+ });++ it('still emits an offer when the own id is unknown (sock.user undefined) — null-safe guard', async () => {+ const { onCall } = await readyWithCallEvents();+ fakeSock.user = undefined;++ fakeSock.fire('call', [offer()]);++ expect(onCall).toHaveBeenCalledTimes(1);+ expect(firstCallEvent(onCall).from).toBe('[email protected]');+ });++ it('a terminal close (440 connectionReplaced) clears the live-call cache', async () => {+ const { adapter } = await readyWithCallEvents();+ fakeSock.fire('call', [offer()]);++ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 440 } } },+ });++ // Dead entries must surface as 404, not as a reject attempted on the dead connection.+ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });++ it('a terminal close (403 forbidden) clears the live-call cache', async () => {+ const { adapter } = await readyWithCallEvents();+ fakeSock.fire('call', [offer()]);++ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 403 } } },+ });++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(fakeSock.rejectCall).not.toHaveBeenCalled();+ });+});+describe('BaileysAdapter profile + block', () => {beforeEach(() => {fakeSock.user = { id: '628999:[email protected]', name: 'Me' };diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 5835b4d9c..83fa53272 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -2,7 +2,13 @@ import * as fs from 'fs';import * as path from 'path';import * as qrcode from 'qrcode';import type * as BaileysLib from '@whiskeysockets/baileys';-import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';+import type {+ AnyMessageContent,+ MiscMessageGenerationOptions,+ WACallEvent,+ WAMessage,+ WASocket,+} from '@whiskeysockets/baileys';import { buildIncomingMessageFromBaileys, extractBaileysBody, mapBaileysStatus } from './baileys-message-mapper';import { buildEditedMessage } from './message-mapper';import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';@@ -18,7 +24,9 @@ import {EngineStatus,EditedMessage,Group,+ GroupEvent,GroupInfo,+ IncomingCallEvent,IncomingMessage,IWhatsAppEngine,Label,@@ -41,6 +49,9 @@ import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { createLogger } from '../../common/services/logger.service';import { BaileysAdapterConfig, BaileysLogger } from '../types/baileys.types';@@ -148,6 +159,12 @@ export class BaileysAdapter implements IWhatsAppEngine {private connectedAt = 0;private reconnectAttempts = 0;private reconnectTimer?: ReturnType<typeof setTimeout>;+ /** How long a received call's handle stays rejectable. Calls ring for roughly a minute, so+ * two minutes covers the ringing window with margin without pinning dead calls for long. */+ private static readonly LIVE_CALL_TTL_MS = 2 * 60_000;+ /** Live incoming calls by call id, holding the raw `from` JID sock.rejectCall() needs — the+ * call event is long gone by the time a reject arrives, so it must be cached at event time. */+ private readonly liveCalls = new Map<string, { callFrom: string; expiresAt: number }>();/** Date.now() of the last close that scheduled a reconnect — input to the stability reset. */private lastConnectionCloseAt = 0;/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */@@ -225,7 +242,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}// An internal reconnect (transient drop) overwrites this.sock WITHOUT going through- // disconnect/logout/destroy, so the previous socket's WebSocket and the 10 ev listeners we+ // disconnect/logout/destroy, so the previous socket's WebSocket and the 13 ev listeners we// register below would leak on every reconnect. Tear the prior socket down first. Detach OUR// connection.update listener BEFORE end(): Baileys' own end() synchronously emits a synthetic// connection.update {connection:'close'}, which — if still wired — would re-enter@@ -243,6 +260,9 @@ export class BaileysAdapter implements IWhatsAppEngine {previous.ev.removeAllListeners('chats.update');previous.ev.removeAllListeners('messaging-history.set');previous.ev.removeAllListeners('lid-mapping.update');+ previous.ev.removeAllListeners('group-participants.update');+ previous.ev.removeAllListeners('groups.update');+ previous.ev.removeAllListeners('call');void previous.end(undefined);} catch {// end() may already have run from Baileys' own close handler — a safe no-op.@@ -302,6 +322,8 @@ export class BaileysAdapter implements IWhatsAppEngine {});this.sessionStore.upsertChats(updates);});+ sock.ev.on('group-participants.update', event => this.handleGroupParticipantsUpdate(event));+ sock.ev.on('groups.update', updates => this.handleGroupsUpdate(updates));sock.ev.on('messaging-history.set', history => {this.sessionStore.upsertContacts(history.contacts);this.sessionStore.upsertChats(history.chats);@@ -324,6 +346,7 @@ export class BaileysAdapter implements IWhatsAppEngine {// WhatsApp pushes this when a lid<->phone mapping is learned (renamed from the pre-v7// 'chats.phoneNumberShare' event, whose { lid, jid } payload this shape directly replaces).sock.ev.on('lid-mapping.update', ({ lid, pn }) => this.sessionStore.addLidMappings([{ lid, pn }]));+ sock.ev.on('call', calls => this.handleCallEvents(calls));}private handleConnectionUpdate(update: {@@ -374,6 +397,9 @@ export class BaileysAdapter implements IWhatsAppEngine {// Baileys silently retries them instead of emitting a new QR, leaving the session stuck (no QR).this.setStatus(EngineStatus.DISCONNECTED);this.sock = null;+ // Cached call handles die with the connection — drop them so a later rejectCall() reports+ // not-found (404) instead of acting on a dead socket (mirrors disconnect/logout/destroy).+ this.liveCalls.clear();void this.clearAuthState();this.callbacks.onDisconnected?.('logged out');return;@@ -385,6 +411,7 @@ export class BaileysAdapter implements IWhatsAppEngine {// the operator stops the other instance, then starts this session again (onError = terminal// + evict in the session service). Auth state is NOT cleared: the link itself is still valid.this.setStatus(EngineStatus.FAILED);+ this.liveCalls.clear(); // terminal close: dead call handles, like the loggedOut branch abovethis.callbacks.onError?.('Connection replaced by another instance (440) — stop the other instance, then start this session again',);@@ -398,6 +425,7 @@ export class BaileysAdapter implements IWhatsAppEngine {// 401): this is an account-level refusal, not dead credentials — the operator keeps the auth// files for inspection and can retry manually once the account issue is resolved.this.setStatus(EngineStatus.FAILED);+ this.liveCalls.clear(); // terminal close: dead call handles, like the loggedOut branch abovethis.callbacks.onError?.('Account rejected by WhatsApp (403) — the number is likely banned or blocked; reconnecting will not help',);@@ -476,6 +504,9 @@ export class BaileysAdapter implements IWhatsAppEngine {}void this.sock?.end(undefined);this.sock = null;+ // Cached call handles die with the socket — drop them so a later rejectCall() reports+ // not-found instead of acting on a closed connection.+ this.liveCalls.clear();this.setStatus(EngineStatus.DISCONNECTED);return Promise.resolve();}@@ -495,6 +526,7 @@ export class BaileysAdapter implements IWhatsAppEngine {void this.sock?.end(undefined);}this.sock = null;+ this.liveCalls.clear();this.setStatus(EngineStatus.DISCONNECTED);await this.config.messageStore?.clearSession(this.config.dbSessionId).catch(() => undefined);// Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be@@ -526,6 +558,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}void this.sock?.end(undefined);this.sock = null;+ this.liveCalls.clear();this.setStatus(EngineStatus.DISCONNECTED);return Promise.resolve();}@@ -740,6 +773,31 @@ export class BaileysAdapter implements IWhatsAppEngine {);}+ async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ this.ensureReady();+ const target = await this.requireStored(messageId);+ // Only the account's own messages are editable: WhatsApp refuses the edit of an inbound message+ // but the send would still resolve, dressing the refusal up as success (and the service layer+ // would then "update" the stored body). Refuse first — mirrors the wwjs null-edit guard.+ if (target.key.fromMe !== true) {+ throw new EngineRefusedError(+ `the edit of message ${messageId} was rejected — only the account's own messages can be edited`,+ );+ }+ // The stored key must belong to the requested chat — editing with another chat's key is a+ // not-found here, not a cross-chat write. Both sides are neutralized so @c.us/@s.whatsapp.net+ // (and a known lid<->pn twin) compare equal.+ if (this.sessionStore.toNeutralJid(target.key.remoteJid ?? '') !== this.sessionStore.toNeutralJid(chatId)) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ // An edit keeps the original message id, so it is neither re-persisted nor echoed as a new send.+ // The destination is resolved like any other send: a lid-migrated contact rejects PN-addressed+ // sends with ack error 463 (see toDeliverableJid).+ const jid = await this.toDeliverableJid(chatId);+ const sent = await this.sock!.sendMessage(jid, { text: body, edit: target.key });+ return { id: sent?.key?.id ?? messageId, timestamp: this.toUnixSeconds(sent?.messageTimestamp) };+ }+// ----- Groups -----async getGroups(): Promise<Group[]> {@@ -834,6 +892,39 @@ export class BaileysAdapter implements IWhatsAppEngine {return (await this.sock!.groupRevokeInvite(groupId)) ?? '';}+ async joinGroupViaInviteCode(inviteCode: string): Promise<string> {+ this.ensureReady();+ // Baileys resolves undefined when the invite is invalid/expired/revoked — no group id surfaces —+ // and rejects with an IQ error (e.g. not-authorized / gone) for the same client-facing cause.+ // Both map to a 400, not a 500.+ let jid: string | undefined;+ try {+ jid = await this.sock!.groupAcceptInvite(inviteCode);+ } catch {+ jid = undefined;+ }+ if (!jid) {+ throw new InvalidInviteCodeError();+ }+ // The returned group JID crosses the engine boundary, so it is neutralized like every other emission.+ return this.sessionStore.toNeutralJid(jid);+ }++ async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ this.ensureReady();+ await this.sock!.groupSettingUpdate(groupId, adminsOnly ? 'announcement' : 'not_announcement');+ }++ async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ this.ensureReady();+ await this.sock!.groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked');+ }++ async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {+ this.ensureReady();+ await this.sock!.groupToggleEphemeral(groupId, durationSec);+ }+async getProfilePicture(contactId: string): Promise<string | null> {this.ensureReady();try {@@ -857,6 +948,30 @@ export class BaileysAdapter implements IWhatsAppEngine {await this.sock!.updateBlockStatus(contactId, 'unblock');}+ // ----- Profile (own account) -----++ async setProfileName(name: string): Promise<void> {+ this.ensureReady();+ await this.sock!.updateProfileName(name);+ }++ async setProfileStatus(status: string): Promise<void> {+ this.ensureReady();+ await this.sock!.updateProfileStatus(status);+ }++ async setProfilePicture(media: MediaInput): Promise<void> {+ this.ensureReady();+ const selfJid = this.normalizedSelfJid();+ if (!selfJid) {+ throw new Error('cannot set the profile picture: the own JID is not known yet');+ }+ // updateProfilePicture takes a WAMediaUpload; resolveMediaBuffer covers Buffer | base64 | URL,+ // the same conversion the media sends use.+ const { data } = await this.resolveMediaBuffer(media);+ await this.sock!.updateProfilePicture(selfJid, data);+ }+// ----- Contacts & chats -----// eslint-disable-next-line @typescript-eslint/require-await@@ -1261,6 +1376,203 @@ export class BaileysAdapter implements IWhatsAppEngine {}}+ /**+ * 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+ * membership and are skipped. The event carries no timestamp, so it is stamped at receipt.+ */+ private handleGroupParticipantsUpdate(event: {+ id?: string;+ author?: string;+ authorPn?: string;+ participants?: unknown[];+ action?: string;+ }): void {+ const kind = event.action === 'add' ? 'join' : event.action === 'remove' ? 'leave' : undefined;+ if (!kind || !event.id) {+ return;+ }+ const participantIds = (Array.isArray(event.participants) ? event.participants : [])+ .map(entry => this.toNeutralGroupParticipantId(entry))+ .filter((jid): jid is string => jid !== null);+ const payload: GroupEvent = {+ kind,+ groupId: this.sessionStore.toNeutralJid(event.id),+ participantIds,+ timestamp: Math.floor(Date.now() / 1000),+ };+ // authorPn is the phone-dialect twin of a lid author: prefer it so the neutral actor id does+ // not depend on whether the lid->pn mapping happens to be learned yet.+ const actor = event.authorPn ?? event.author;+ if (actor) {+ payload.actorId = this.sessionStore.toNeutralJid(actor);+ }+ this.callbacks.onGroupEvent?.(payload);+ }++ /**+ * Baileys `groups.update`: partial group metadata. Each entry becomes one neutral 'update'+ * GroupEvent with `changes` filled from whichever of subject/desc/announce/restrict it carries+ * (desc → description, restrict → locked). Entries about fields the neutral shape does not model+ * (inviteCode, memberAddMode, joinApprovalMode, ...) still emit with empty changes — parity with+ * the wwebjs adapter, which emits uninterpretable updates the same way rather than dropping them.+ *+ * The same event also carries FULL metadata snapshots: groupFetchAllParticipating() emits its+ * entire result set through it (Socket/groups.js:56 `sock.ev.emit('groups.update', ...)`), and+ * this adapter calls that on every connect (hydrateNames) and every REST getGroups(). Real deltas+ * (Utils/process-message.js emitGroupUpdate) carry only `{id, ...oneChangedField, author?}`;+ * snapshots are recognized by their full-metadata markers (participants/creation/subjectTime/+ * owner/size) and skipped — otherwise every reconnect / GET /groups would flood consumers with+ * bogus group.update webhooks whose `changes` were fabricated from the snapshot.+ */+ private handleGroupsUpdate(+ updates: Array<{+ id?: string;+ subject?: string;+ desc?: string;+ announce?: boolean;+ restrict?: boolean;+ author?: string;+ authorPn?: string;+ // Full-snapshot markers (extractGroupMetadata); the values are unused — presence is the signal.+ participants?: unknown;+ creation?: unknown;+ subjectTime?: unknown;+ owner?: unknown;+ size?: unknown;+ }>,+ ): void {+ for (const update of Array.isArray(updates) ? updates : []) {+ if (!update?.id) {+ continue;+ }+ // Skip full-metadata snapshots (see the docblock): only real deltas become GroupEvents.+ if ('participants' in update || 'creation' in update || 'subjectTime' in update || 'owner' in update) {+ continue;+ }+ const changes: NonNullable<GroupEvent['changes']> = {};+ if (typeof update.subject === 'string') changes.subject = update.subject;+ if (typeof update.desc === 'string') changes.description = update.desc;+ if (typeof update.announce === 'boolean') changes.announce = update.announce;+ if (typeof update.restrict === 'boolean') changes.locked = update.restrict;+ const payload: GroupEvent = {+ kind: 'update',+ groupId: this.sessionStore.toNeutralJid(update.id),+ participantIds: [],+ changes,+ timestamp: Math.floor(Date.now() / 1000),+ };+ const actor = update.authorPn ?? update.author;+ if (actor) {+ payload.actorId = this.sessionStore.toNeutralJid(actor);+ }+ this.callbacks.onGroupEvent?.(payload);+ }+ }++ /**+ * Baileys `call` events carry the whole call lifecycle; only the `offer` status is a NEW incoming+ * call (ringing/preaccept/timeout/reject/accept/terminate are progress and hang-up updates and+ * are skipped). Offline-replayed offers (missed-while-disconnected) and the account's own+ * outgoing calls are skipped too. The raw `from` JID is cached keyed by call id —+ * sock.rejectCall() needs it verbatim later, when the event itself is long gone.+ */+ private handleCallEvents(calls: WACallEvent[]): void {+ for (const call of Array.isArray(calls) ? calls : []) {+ if (!call || call.status !== 'offer' || !call.id || !call.from) {+ continue;+ }+ // Baileys replays offers for calls missed while disconnected with offline: true+ // (Socket/messages-recv.js:1458 `offline: !!attrs.offline`; WACallEvent.offline is+ // non-optional). Those calls are long dead — emitting call.received (and, with+ // autoRejectCalls, rejecting a stale call) would be wrong, so drop them before caching.+ if (call.offline) {+ continue;+ }+ // WACallEvent has no fromMe flag, but WhatsApp can relay the account's own outgoing-call+ // signaling — skip a call whose from/chatId is ourselves (the wwjs adapter's call.fromMe+ // guard). Null-safe: with no socket user there is no own id to compare, so nothing is skipped.+ const selfJid = this.normalizedSelfJid();+ if (selfJid) {+ const self = this.sessionStore.toNeutralJid(selfJid);+ if (+ this.sessionStore.toNeutralJid(call.from) === self ||+ this.sessionStore.toNeutralJid(call.chatId) === self+ ) {+ continue;+ }+ }+ this.cacheLiveCall(call.id, call.from);+ const payload: IncomingCallEvent = {+ callId: call.id,+ // callerPn is the phone-dialect twin of a lid caller: prefer it so the neutral caller id+ // does not depend on whether the lid->pn mapping happens to be learned yet (same rule as+ // the group actor ids above).+ from: this.sessionStore.toNeutralJid(call.callerPn ?? call.from),+ isVideo: call.isVideo === true,+ isGroup: call.isGroup === true,+ // The event carries a real Date; fall back to receipt time when absent/unparseable.+ timestamp:+ call.date instanceof Date && !Number.isNaN(call.date.getTime())+ ? Math.floor(call.date.getTime() / 1000)+ : Math.floor(Date.now() / 1000),+ };+ this.callbacks.onCall?.(payload);+ }+ }++ /**+ * Cache a ringing call's raw caller JID for a later rejectCall(). Lazy expiry: inserting a new+ * call drops already-expired entries, so a session that receives calls but never rejects them+ * can't grow the map without bound; an entry that never sees another call is tiny and is dropped+ * on teardown (disconnect/logout/destroy) or at the next call. No per-entry timer to clean up.+ */+ private cacheLiveCall(callId: string, callFrom: string): void {+ const now = Date.now();+ for (const [id, entry] of this.liveCalls) {+ if (entry.expiresAt <= now) {+ this.liveCalls.delete(id);+ }+ }+ this.liveCalls.set(callId, { callFrom, expiresAt: now + BaileysAdapter.LIVE_CALL_TTL_MS });+ }++ /**+ * Reject a currently-ringing call. The entry is evicted on ANY attempt (a rejected/ended call+ * will not become rejectable again); an unknown id or an expired entry maps to CallNotFoundError+ * (HTTP 404). A failure of the library's rejectCall() itself propagates as-is.+ */+ async rejectCall(callId: string): Promise<void> {+ const entry = this.liveCalls.get(callId);+ this.liveCalls.delete(callId);+ if (!entry || entry.expiresAt <= Date.now()) {+ throw new CallNotFoundError(callId);+ }+ if (!this.sock) {+ throw new EngineNotReadyError('Cannot reject a call before the engine is initialized.');+ }+ await this.sock.rejectCall(callId, entry.callFrom);+ }++ /**+ * Coerce one `group-participants.update` entry to a neutral user id. Since Baileys v7 the entries+ * are parsed JSON objects (`{ id, phoneNumber?, lid?, ... }`, see Socket/messages-recv.js), not+ * plain JID strings: prefer the phone JID when present (a lid `id` with a known phone resolves to+ * the same neutral @c.us via the mapping, but the inline phoneNumber needs no lookup), then the+ * bare id, then the lid. Plain-string entries (the pre-v7 shape) pass through the same normalizer.+ */+ private toNeutralGroupParticipantId(entry: unknown): string | null {+ if (typeof entry === 'string') {+ return entry ? this.sessionStore.toNeutralJid(entry) : null;+ }+ if (entry && typeof entry === 'object') {+ const e = entry as { phoneNumber?: unknown; id?: unknown; lid?: unknown };+ const jid = [e.phoneNumber, e.id, e.lid].find((v): v is string => typeof v === 'string' && v.length > 0);+ return jid ? this.sessionStore.toNeutralJid(jid) : null;+ }+ return null;+ }+/*** Download inbound media via a stream, accumulating chunks but ABORTING (destroy + discard) once the* running total exceeds `maxBytes`. Returns null on abort. Uses `downloadMediaMessage(..., 'stream')`@@ -1627,8 +1939,12 @@ export class BaileysAdapter implements IWhatsAppEngine {}if (/^https?:\/\//i.test(media.data)) {const fetched = await loadRemoteMediaBuffer(media.data);- // Caller's declared mimetype wins; fall back to the response content-type.- return { data: fetched.data, mimetype: media.mimetype || fetched.mimetype };+ // A generic placeholder mimetype (buildMediaInput's 'application/octet-stream' default when the+ // caller supplied none) carries no real signal — defer to the fetched response content-type,+ // which was sniffed from the actual bytes. This fixes URL-based sends where the caller has no+ // mimetype to pass through the conversation-send facade (e.g. chatwoot-adapter outbound relay).+ const callerMimetype = media.mimetype && media.mimetype !== 'application/octet-stream' ? media.mimetype : null;+ return { data: fetched.data, mimetype: callerMimetype ?? fetched.mimetype };}return { data: Buffer.from(media.data, 'base64'), mimetype: media.mimetype };}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 0ecb769fb..3f63558b4 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -18,9 +18,15 @@ import * as path from 'path';import * as qrcode from 'qrcode';import { InternalServerErrorException, UnprocessableEntityException } from '@nestjs/common';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';-import { EditedMessage, EngineStatus } from '../interfaces/whatsapp-engine.interface';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { EditedMessage, EngineStatus, GroupEvent, IncomingCallEvent } from '../interfaces/whatsapp-engine.interface';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { fetch as undiciFetch } from 'undici';@@ -1789,6 +1795,377 @@ describe('WhatsAppWebJsAdapter message_edit', () => {});});+describe('WhatsAppWebJsAdapter group notifications (group_join / group_leave / group_update)', () => {+ const wireGroupHandler = (): { onGroupEvent: jest.Mock; client: EventEmitter } => {+ const adapter = new WhatsAppWebJsAdapter({+ sessionId: 'sess-group-test',+ sessionDataPath: './data/sessions',+ puppeteer: {},+ });+ const client = Object.assign(new EventEmitter(), {+ info: { wid: { _serialized: '[email protected]', user: '628123' }, pushname: 'Tester' },+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ });+ (adapter as unknown as { client: unknown }).client = client;+ const onGroupEvent = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onGroupEvent };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();+ return { onGroupEvent, client };+ };++ const groupArg = (mock: jest.Mock): GroupEvent => {+ const calls = mock.mock.calls as Array<[GroupEvent]>;+ return calls[0][0];+ };++ it('maps group_join to a neutral join GroupEvent with the notification timestamp', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_join', {+ id: { _serialized: 'NOTIF_JOIN' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: ['[email protected]', '[email protected]'],+ body: '',+ timestamp: 1700000100,+ type: 'add',+ });++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ // wwebjs ids are already neutral (@c.us/@g.us): they pass through untranslated. A join+ // carries no metadata delta, so `changes` stays absent (kind is carried by the event name).+ expect(groupArg(onGroupEvent)).toEqual({+ kind: 'join',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]', '[email protected]'],+ timestamp: 1700000100,+ });+ });++ it('maps group_leave to a neutral leave GroupEvent', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_leave', {+ id: { _serialized: 'NOTIF_LEAVE' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: ['[email protected]'],+ body: '',+ timestamp: 1700000200,+ type: 'remove',+ });++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(groupArg(onGroupEvent)).toEqual({+ kind: 'leave',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000200,+ });+ });++ it('omits actorId when the notification has no author', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_join', {+ id: { _serialized: 'NOTIF_NOAUTHOR' },+ chatId: '[email protected]',+ author: '',+ recipientIds: ['[email protected]'],+ body: '',+ timestamp: 1700000250,+ type: 'invite',+ });++ expect(groupArg(onGroupEvent).actorId).toBeUndefined();+ });++ it('falls back to receipt time when the notification carries no usable timestamp', () => {+ const { onGroupEvent, client } = wireGroupHandler();+ const now = jest.spyOn(Date, 'now').mockReturnValue(1700000300123);++ try {+ client.emit('group_join', {+ id: { _serialized: 'NOTIF_NOTS' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: ['[email protected]'],+ body: '',+ type: 'add',+ });+ } finally {+ now.mockRestore();+ }++ expect(groupArg(onGroupEvent).timestamp).toBe(1700000300);+ });++ it('coerces $1-renamed recipientIds entries (#747) and drops unreadable ones', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_join', {+ id: { _serialized: 'NOTIF_RENAMED' },+ chatId: '[email protected]',+ author: '[email protected]',+ // GroupNotification._patch assigns data.recipients straight through, outside upstream's id+ // normalization — a renamed WA Web build hands us raw id objects here.+ recipientIds: [{ $1: '[email protected]' }, { _serialized: '[email protected]' }, { someFutureName: 'x' }, '[email protected]'],+ body: '',+ timestamp: 1700000400,+ type: 'add',+ });++ expect(groupArg(onGroupEvent).participantIds).toEqual(['[email protected]', '[email protected]', '[email protected]']);+ });++ it('maps group_update subject/description bodies into the changes delta', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_update', {+ id: { _serialized: 'NOTIF_SUBJ' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: 'New group name',+ timestamp: 1700000500,+ type: 'subject',+ });+ client.emit('group_update', {+ id: { _serialized: 'NOTIF_DESC' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: 'New description',+ timestamp: 1700000501,+ type: 'description',+ });++ const calls = onGroupEvent.mock.calls as Array<[GroupEvent]>;+ expect(calls[0][0]).toMatchObject({ kind: 'update', changes: { subject: 'New group name' } });+ expect(calls[1][0]).toMatchObject({ kind: 'update', changes: { description: 'New description' } });+ });++ it('maps group_update announce/restrict on-off bodies to the neutral booleans', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_update', {+ id: { _serialized: 'NOTIF_ANNOUNCE' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: 'on',+ timestamp: 1700000600,+ type: 'announce',+ });+ client.emit('group_update', {+ id: { _serialized: 'NOTIF_RESTRICT' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: 'off',+ timestamp: 1700000601,+ type: 'restrict',+ });++ const calls = onGroupEvent.mock.calls as Array<[GroupEvent]>;+ expect(calls[0][0].changes).toEqual({ announce: true });+ expect(calls[1][0].changes).toEqual({ locked: false });+ });++ it('still emits an update with empty changes when the subtype is uninterpretable (picture)', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_update', {+ id: { _serialized: 'NOTIF_PIC' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: '',+ timestamp: 1700000700,+ type: 'picture',+ });++ // Never dropped silently: the occurrence reaches consumers, just without guessed fields.+ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(groupArg(onGroupEvent)).toMatchObject({ kind: 'update', groupId: '[email protected]', changes: {} });+ });++ it('emits a join with empty participantIds when recipientIds is missing (malformed payload)', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ expect(() =>+ client.emit('group_join', {+ id: { _serialized: 'NOTIF_MALFORMED' },+ chatId: '[email protected]',+ author: '[email protected]',+ body: '',+ timestamp: 1700000800,+ type: 'add',+ }),+ ).not.toThrow();++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(groupArg(onGroupEvent).participantIds).toEqual([]);+ });++ it('logs and drops a null notification instead of throwing into the client emitter', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ expect(() => client.emit('group_update', null)).not.toThrow();+ expect(onGroupEvent).not.toHaveBeenCalled();+ });++ it('drops a notification without a chatId before building the payload', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_join', {+ id: { _serialized: 'NOTIF_NOCHAT' },+ author: '[email protected]',+ recipientIds: ['[email protected]'],+ body: '',+ timestamp: 1700000900,+ type: 'add',+ });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });+});++describe('WhatsAppWebJsAdapter call event + rejectCall', () => {+ const wireCallHandler = (): { adapter: WhatsAppWebJsAdapter; onCall: jest.Mock; client: EventEmitter } => {+ const adapter = new WhatsAppWebJsAdapter({+ sessionId: 'sess-call-test',+ sessionDataPath: './data/sessions',+ puppeteer: {},+ });+ const client = Object.assign(new EventEmitter(), {+ info: { wid: { _serialized: '[email protected]', user: '628123' }, pushname: 'Tester' },+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ destroy: jest.fn().mockResolvedValue(undefined),+ });+ (adapter as unknown as { client: unknown }).client = client;+ const onCall = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onCall };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();+ return { adapter, onCall, client };+ };++ const liveCall = (over: Record<string, unknown> = {}) => ({+ id: 'CALL1',+ from: '[email protected]',+ timestamp: 1700000200,+ isVideo: false,+ isGroup: false,+ fromMe: false,+ canHandleLocally: false,+ webClientShouldHandle: false,+ participants: {},+ reject: jest.fn().mockResolvedValue(undefined),+ ...over,+ });++ const firstCallEvent = (mock: jest.Mock): IncomingCallEvent => {+ const calls = mock.mock.calls as Array<[IncomingCallEvent]>;+ if (!calls[0]) throw new Error('Expected a call event');+ return calls[0][0];+ };++ it('maps the call event to a neutral IncomingCallEvent', () => {+ const { onCall, client } = wireCallHandler();++ client.emit('call', liveCall({ isVideo: true }));++ expect(onCall).toHaveBeenCalledTimes(1);+ expect(firstCallEvent(onCall)).toEqual({+ callId: 'CALL1',+ from: '[email protected]',+ isVideo: true,+ isGroup: false,+ timestamp: 1700000200,+ });+ });++ it('skips own-account (fromMe) calls — they are outgoing, not incoming', () => {+ const { onCall, client } = wireCallHandler();++ client.emit('call', liveCall({ fromMe: true }));++ expect(onCall).not.toHaveBeenCalled();+ });++ it.each([{ id: '' }, { id: undefined }, { from: '' }, { from: undefined }, null])(+ 'drops a malformed call (%o) — nothing emitted, nothing cached',+ async malformed => {+ const { adapter, onCall, client } = wireCallHandler();++ client.emit('call', malformed === null ? null : liveCall(malformed as Record<string, unknown>));++ expect(onCall).not.toHaveBeenCalled();+ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ },+ );++ it('drops a call arriving during teardown', () => {+ const { adapter, onCall, client } = wireCallHandler();+ (adapter as unknown as { tearingDown: boolean }).tearingDown = true;++ client.emit('call', liveCall());++ expect(onCall).not.toHaveBeenCalled();+ });++ it('rejectCall rejects the cached live call and evicts it (second reject -> not found)', async () => {+ const { adapter, client } = wireCallHandler();+ const call = liveCall();+ client.emit('call', call);++ await adapter.rejectCall('CALL1');++ expect(call.reject).toHaveBeenCalledTimes(1);+ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ });++ it('rejectCall on an unknown id throws CallNotFoundError (HTTP 404)', async () => {+ const { adapter } = wireCallHandler();++ await expect(adapter.rejectCall('NOPE')).rejects.toBeInstanceOf(CallNotFoundError);+ });++ it('rejectCall on an expired entry throws CallNotFoundError without touching the call', async () => {+ const { adapter, client } = wireCallHandler();+ const call = liveCall();+ client.emit('call', call);+ // Age the cached entry past the TTL (calls ring ~a minute; the handle dies with the call).+ const cache = (adapter as unknown as { liveCalls: Map<string, { expiresAt: number }> }).liveCalls;+ cache.get('CALL1')!.expiresAt = Date.now() - 1;++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(call.reject).not.toHaveBeenCalled();+ });++ it('teardown clears the live-call cache (reject after disconnect -> not found)', async () => {+ const { adapter, client } = wireCallHandler();+ const call = liveCall();+ client.emit('call', call);++ await adapter.disconnect();++ await expect(adapter.rejectCall('CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ expect(call.reject).not.toHaveBeenCalled();+ });++ it('logs and drops a malformed call instead of throwing into the client emitter', () => {+ const { onCall, client } = wireCallHandler();++ expect(() => client.emit('call', null)).not.toThrow();+ expect(onCall).not.toHaveBeenCalled();+ });+});+describe('outbound mentions (#530)', () => {const ready = (client: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });@@ -2030,6 +2407,58 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lid});});+describe('editMessage', () => {+ const ready = (client: unknown): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = client;+ return adapter;+ };+ const chatWith = (messages: unknown[]) => ({+ getChatById: jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue(messages) }),+ });++ it('edits a message found by _serialized id and returns its (unchanged) id', async () => {+ const edit = jest.fn().mockResolvedValue({ id: { _serialized: 'M1' }, timestamp: 1700000002 });+ const adapter = ready(chatWith([{ id: { _serialized: 'M1', id: 'RAW1' }, edit }]));+ const res = await adapter.editMessage('[email protected]', 'M1', 'new body');+ expect(edit).toHaveBeenCalledWith('new body');+ expect(res).toEqual({ id: 'M1', timestamp: 1700000002 });+ });++ it('also matches the bare id.id fallback (like deleteMessage)', async () => {+ const edit = jest.fn().mockResolvedValue({ id: { _serialized: '[email protected]_RAW1' }, timestamp: 1700000002 });+ const adapter = ready(chatWith([{ id: { _serialized: '[email protected]_RAW1', id: 'RAW1' }, edit }]));+ const res = await adapter.editMessage('[email protected]', 'RAW1', 'new body');+ expect(edit).toHaveBeenCalledWith('new body');+ expect(res.id).toBe('[email protected]_RAW1');+ });++ it('throws MessageNotFoundError when the message is outside the fetch window', async () => {+ const adapter = ready(chatWith([]));+ await expect(adapter.editMessage('[email protected]', 'GONE', 'x')).rejects.toBeInstanceOf(MessageNotFoundError);+ });++ it('propagates an engine edit failure unchanged', async () => {+ const edit = jest.fn().mockRejectedValue(new Error('Evaluation failed'));+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, edit }]));+ await expect(adapter.editMessage('[email protected]', 'M1', 'x')).rejects.toThrow('Evaluation failed');+ });++ it('throws MessageNotFoundError when the chat id itself is unknown (getChatById resolves undefined)', async () => {+ const adapter = ready({ getChatById: jest.fn().mockResolvedValue(undefined) });+ await expect(adapter.editMessage('[email protected]', 'M1', 'x')).rejects.toBeInstanceOf(MessageNotFoundError);+ });++ it('treats a null edit result as a refusal (EngineRefusedError, 403), not a phantom success', async () => {+ const edit = jest.fn().mockResolvedValue(null);+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, edit }]));+ const err = await adapter.editMessage('[email protected]', 'M1', 'x').catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/was rejected/);+ });+});+describe('LID mapping persistence to LidMappingStore (#583 R3)', () => {const readyWithStore = (client: unknown, lidMappingStore: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({@@ -2854,3 +3283,175 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(adapter.getStatus()).toBe(EngineStatus.READY);});});++describe('WhatsAppWebJsAdapter group join + settings + own profile', () => {+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = client;+ return adapter;+ };++ describe('joinGroupViaInviteCode', () => {+ it('returns the joined group id from acceptInvite', async () => {+ const acceptInvite = jest.fn().mockResolvedValue('[email protected]');+ await expect(readyAdapter({ acceptInvite }).joinGroupViaInviteCode('CODE123')).resolves.toBe('[email protected]');+ expect(acceptInvite).toHaveBeenCalledWith('CODE123');+ });++ it('maps a thrown page error to InvalidInviteCodeError (400)', async () => {+ const acceptInvite = jest.fn().mockRejectedValue(new Error('Evaluation failed: invite revoked'));+ await expect(readyAdapter({ acceptInvite }).joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(+ InvalidInviteCodeError,+ );+ });++ it('maps a gid-less result to InvalidInviteCodeError (400)', async () => {+ const acceptInvite = jest.fn().mockResolvedValue(undefined);+ await expect(readyAdapter({ acceptInvite }).joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(+ InvalidInviteCodeError,+ );+ });+ });++ describe('setGroupMessagesAdminsOnly / setGroupInfoAdminsOnly', () => {+ const groupClient = (impl: Record<string, jest.Mock>) => ({+ getChatById: jest.fn().mockResolvedValue({ isGroup: true, ...impl }),+ });++ it('resolves the group chat and calls setMessagesAdminsOnly', async () => {+ const setMessagesAdminsOnly = jest.fn().mockResolvedValue(true);+ await readyAdapter(groupClient({ setMessagesAdminsOnly })).setGroupMessagesAdminsOnly('[email protected]', true);+ expect(setMessagesAdminsOnly).toHaveBeenCalledWith(true);+ });++ it('resolves the group chat and calls setInfoAdminsOnly', async () => {+ const setInfoAdminsOnly = jest.fn().mockResolvedValue(true);+ await readyAdapter(groupClient({ setInfoAdminsOnly })).setGroupInfoAdminsOnly('[email protected]', false);+ expect(setInfoAdminsOnly).toHaveBeenCalledWith(false);+ });++ it('throws GroupNotFoundError (404) when the chat is not a group', async () => {+ const getChatById = jest.fn().mockResolvedValue({ isGroup: false });+ await expect(+ readyAdapter({ getChatById }).setGroupMessagesAdminsOnly('[email protected]', true),+ ).rejects.toBeInstanceOf(GroupNotFoundError);+ });++ it('throws GroupNotFoundError (404) when the chat id is unknown (getChatById resolves undefined)', async () => {+ const getChatById = jest.fn().mockResolvedValue(undefined);+ await expect(readyAdapter({ getChatById }).setGroupMessagesAdminsOnly('[email protected]', true)).rejects.toBeInstanceOf(+ GroupNotFoundError,+ );+ });++ it.each([+ ['setGroupMessagesAdminsOnly', 'setMessagesAdminsOnly'],+ ['setGroupInfoAdminsOnly', 'setInfoAdminsOnly'],+ ])('%s throws EngineRefusedError (403) when the engine reports false (no admin rights)', async (method, native) => {+ // wwebjs RESOLVES false (instead of throwing) on a ServerStatusCodeError — a silent no-op+ // would dress up a refused write as a success.+ const client = groupClient({ [native]: jest.fn().mockResolvedValue(false) });+ const call = (readyAdapter(client) as unknown as Record<string, (g: string, v: boolean) => Promise<void>>)[+ method+ ]('[email protected]', true);+ const err = await call.catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/admin rights required/);+ });+ });++ describe('setGroupEphemeral (no wwjs 1.34.7 API → honest 501)', () => {+ it('rejects with EngineNotSupportedError (501)', async () => {+ const err = await readyAdapter({})+ .setGroupEphemeral('[email protected]', 86400)+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineNotSupportedError);+ expect((err as EngineNotSupportedError).getStatus()).toBe(501);+ });+ });++ describe('setProfileName / setProfileStatus', () => {+ it('setProfileName resolves when the engine accepts', async () => {+ const setDisplayName = jest.fn().mockResolvedValue(true);+ await expect(readyAdapter({ setDisplayName }).setProfileName('New Name')).resolves.toBeUndefined();+ expect(setDisplayName).toHaveBeenCalledWith('New Name');+ });++ it('setProfileName throws EngineRefusedError (403) when the engine resolves false', async () => {+ const setDisplayName = jest.fn().mockResolvedValue(false);+ const err = await readyAdapter({ setDisplayName })+ .setProfileName('New Name')+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/rejected the profile name change/);+ });++ it('setProfileStatus delegates to client.setStatus', async () => {+ const setStatus = jest.fn().mockResolvedValue(undefined);+ await readyAdapter({ setStatus }).setProfileStatus('busy');+ expect(setStatus).toHaveBeenCalledWith('busy');+ });+ });++ describe('setProfilePicture', () => {+ it('converts base64 MediaInput to a MessageMedia (same helper as media sends)', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(true);+ await readyAdapter({ setProfilePicture }).setProfilePicture({+ mimetype: 'image/png',+ data: Buffer.from([1, 2, 3]).toString('base64'),+ });+ const calls = setProfilePicture.mock.calls as Array<[MessageMedia]>;+ const media = calls[0][0];+ expect(media).toBeInstanceOf(MessageMedia);+ expect(media.mimetype).toBe('image/png');+ expect(media.data).toBe(Buffer.from([1, 2, 3]).toString('base64'));+ });++ it('converts a Buffer payload to base64 MessageMedia', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(true);+ await readyAdapter({ setProfilePicture }).setProfilePicture({ mimetype: 'image/jpeg', data: Buffer.from('IMG') });+ const calls = setProfilePicture.mock.calls as Array<[MessageMedia]>;+ expect(calls[0][0].data).toBe(Buffer.from('IMG').toString('base64'));+ });++ it('throws EngineRefusedError (403) when the engine resolves false', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(false);+ const err = await readyAdapter({ setProfilePicture })+ .setProfilePicture({ mimetype: 'image/jpeg', data: 'AAAA' })+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/rejected the profile picture change/);+ });+ });++ describe('getGroupInfo settings fields', () => {+ it('populates announce/locked/ephemeralSeconds from the native groupMetadata', async () => {+ const getChatById = jest.fn().mockResolvedValue({+ isGroup: true,+ id: { _serialized: '[email protected]' },+ name: 'G',+ participants: [],+ groupMetadata: { announce: true, restrict: true, ephemeralDuration: 604800 },+ });+ const info = await readyAdapter({ getChatById }).getGroupInfo('[email protected]');+ expect(info?.announce).toBe(true);+ expect(info?.locked).toBe(true);+ expect(info?.ephemeralSeconds).toBe(604800);+ });++ it('leaves the settings fields undefined when the metadata does not carry them', async () => {+ const getChatById = jest.fn().mockResolvedValue({+ isGroup: true,+ id: { _serialized: '[email protected]' },+ name: 'G',+ participants: [],+ groupMetadata: {},+ });+ const info = await readyAdapter({ getChatById }).getGroupInfo('[email protected]');+ expect(info?.announce).toBeUndefined();+ expect(info?.locked).toBeUndefined();+ expect(info?.ephemeralSeconds).toBeUndefined();+ });+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex bee3aedda..a38e8f034 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1,6 +1,15 @@import { EventEmitter } from 'events';import { InternalServerErrorException } from '@nestjs/common';-import { Client, LocalAuth, MessageMedia, MessageTypes, WAState, type Message } from 'whatsapp-web.js';+import {+ Client,+ LocalAuth,+ MessageMedia,+ MessageTypes,+ WAState,+ type Call,+ type GroupNotification,+ type Message,+} from 'whatsapp-web.js';import * as qrcode from 'qrcode';import * as path from 'path';import * as fs from 'fs';@@ -36,6 +45,8 @@ import {RevokedMessage,EditedMessage,ReactionEvent,+ GroupEvent,+ IncomingCallEvent,} from '../interfaces/whatsapp-engine.interface';import { resolveWebVersionPin } from '../wa-web-version';import { isChannelJid, userPart } from '../identity/wa-id';@@ -45,6 +56,10 @@ import { createLogger } from '../../common/services/logger.service';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';@@ -83,6 +98,66 @@ export function wwebjsAckToDeliveryStatus(ack: number): DeliveryStatus {return 'pending';}+/**+ * Interpret the on/off value a group settings notification carries in `body` ('on'/'true' → true,+ * 'off'/'false' → false). Undefined when the body holds anything else (e.g. a rendered template+ * string), in which case the caller emits the update without that change rather than guess.+ */+function parseWwebjsOnOff(body: string): boolean | undefined {+ const v = body.trim().toLowerCase();+ if (v === 'on' || v === 'true') return true;+ if (v === 'off' || v === 'false') return false;+ return undefined;+}++/**+ * Reduce a `group_update` GroupNotification to the neutral `changes` delta. `subject`/`description`+ * carry the new value in `body`; `announce`/`restrict` encode the new setting as on/off text (the+ * latter maps to the neutral `locked`). Anything uninterpretable — a `picture` change, or a WA Web+ * build that stops putting the value in `body` — yields an empty delta: the occurrence is still+ * emitted, just without fields we would be guessing at. Compared as strings because the runtime+ * gp2 subtypes can exceed the GroupNotificationTypes enum (e.g. a 'locked' rename of 'restrict').+ */+export function wwebjsGroupUpdateChanges(notification: GroupNotification): NonNullable<GroupEvent['changes']> {+ const body = typeof notification.body === 'string' ? notification.body : '';+ switch (String(notification.type)) {+ case 'subject':+ return { subject: body };+ case 'description':+ return { description: body };+ case 'announce': {+ const on = parseWwebjsOnOff(body);+ return on === undefined ? {} : { announce: on };+ }+ case 'restrict':+ case 'locked': {+ const on = parseWwebjsOnOff(body);+ return on === undefined ? {} : { locked: on };+ }+ default:+ return {};+ }+}++/**+ * A GroupNotification's `recipientIds` are assigned straight through from the wire+ * (`this.recipientIds = data.recipients`), outside upstream's id normalization — so on a WA Web+ * build that renamed `_serialized` to `$1` (#747) an entry can arrive as a raw id object instead+ * of a string. Coerce both shapes to the neutral (already @c.us/@g.us) string form; entries that+ * resolve to nothing are dropped rather than forwarded as "undefined".+ */+export function wwebjsGroupRecipientIds(notification: GroupNotification): string[] {+ const raw = notification.recipientIds as unknown;+ if (!Array.isArray(raw)) return [];+ return raw+ .map(entry => {+ if (typeof entry === 'string') return entry;+ const wid = entry as SerializedWid | undefined;+ return wid?._serialized ?? wid?.$1 ?? '';+ })+ .filter(id => id.length > 0);+}+/*** Extract call detail from a whatsapp-web.js `call_log` message, or `undefined` for any other type.* The public Message wrapper doesn't expose call fields, so we read them off the raw `_data`. An@@ -258,6 +333,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate readyReconcileTimer: ReturnType<typeof setTimeout> | null = null;private readyReconcileStartedAt = 0;private readyReconcileProbeInFlight = false;+ /** How long a received call's handle stays rejectable. Calls ring for roughly a minute, so+ * two minutes covers the ringing window with margin without pinning dead calls for long. */+ private static readonly LIVE_CALL_TTL_MS = 2 * 60_000;+ /** Live incoming calls by call id. The wwebjs `Call` object is only usable while the call is+ * live, so it must be cached at event time for a later rejectCall() to act on. */+ private readonly liveCalls = new Map<string, { call: Call; expiresAt: number }>();// Guards the stuck-auth self-heal so it runs at most once per engine: a re-paired session that still// can't reach readiness fails terminally instead of looping QR -> timeout -> clear forever.private stuckAuthRecoveryAttempted = false;@@ -753,6 +834,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}});+ this.client.on('group_join', notification => this.handleGroupNotification('join', notification));+ this.client.on('group_leave', notification => this.handleGroupNotification('leave', notification));+ this.client.on('group_update', notification => this.handleGroupNotification('update', notification));++ this.client.on('call', call => this.handleIncomingCall(call));+this.client.on('disconnected', reason => {this.clearReadyReconcile();this.setStatus(EngineStatus.DISCONNECTED);@@ -769,6 +856,106 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin});}+ /**+ * Map a whatsapp-web.js GroupNotification (`group_join` / `group_leave` / `group_update`) to the+ * neutral GroupEvent and forward it. wwebjs ids are already in the neutral dialect (@c.us/@g.us),+ * so no jid translation is needed here. The try/catch mirrors message_edit: a malformed+ * notification is logged and dropped, never thrown back into the client's emitter.+ */+ private handleGroupNotification(kind: GroupEvent['kind'], notification: GroupNotification): void {+ try {+ // A notification without a chat id carries no usable target — drop it before payload building.+ if (!notification.chatId) {+ return;+ }+ const payload: GroupEvent = {+ kind,+ groupId: notification.chatId,+ actorId: notification.author || undefined,+ participantIds: wwebjsGroupRecipientIds(notification),+ // The notification's own timestamp IS the occurrence time (unlike message_edit, where+ // wwebjs keeps the original creation time). Fall back to receipt time when absent.+ timestamp:+ typeof notification.timestamp === 'number' && notification.timestamp > 0+ ? Math.floor(notification.timestamp)+ : Math.floor(Date.now() / 1000),+ };+ if (kind === 'update') {+ // Join/leave carry no metadata delta. An update whose subtype/body cannot be interpreted+ // still emits with empty changes rather than being dropped silently.+ payload.changes = wwebjsGroupUpdateChanges(notification);+ }+ this.callbacks.onGroupEvent?.(payload);+ } catch (error) {+ this.logger.error(`Error processing group_${kind} notification`, String(error));+ }+ }++ /**+ * Map a whatsapp-web.js `Call` (client `call` event) to the neutral IncomingCallEvent and cache+ * the live Call so rejectCall() can act on it later — the Call object is only usable while the+ * call is live. Own-account calls (fromMe) are skipped: they are outgoing, not incoming. wwebjs+ * ids are already neutral (@c.us), so no jid translation is needed. The try/catch mirrors+ * message_edit: a malformed call is logged and dropped, never thrown back into the emitter.+ */+ private handleIncomingCall(call: Call): void {+ try {+ // Symmetry with the other client-event handlers (qr/authenticated): a call landing during or+ // after teardown is dropped. A malformed call without the id/from rejectCall() later depends+ // on is dropped too — never cached, never emitted.+ if (this.tearingDown || !call?.id || !call.from) {+ return;+ }+ if (call.fromMe) {+ return;+ }+ this.cacheLiveCall(call.id, call);+ const payload: IncomingCallEvent = {+ callId: call.id,+ from: call.from ?? '',+ isVideo: call.isVideo === true,+ isGroup: call.isGroup === true,+ timestamp:+ typeof call.timestamp === 'number' && call.timestamp > 0+ ? Math.floor(call.timestamp)+ : Math.floor(Date.now() / 1000),+ };+ this.callbacks.onCall?.(payload);+ } catch (error) {+ this.logger.error('Error processing call event', String(error));+ }+ }++ /**+ * Cache a live call for a later rejectCall(). Lazy expiry: inserting a new call drops+ * already-expired entries, so a session that receives calls but never rejects them can't grow+ * the map without bound; an entry that never sees another call is tiny and is dropped on+ * teardown (beginClientTeardown) or at the next call. No per-entry timer to clean up.+ */+ private cacheLiveCall(callId: string, call: Call): void {+ const now = Date.now();+ for (const [id, entry] of this.liveCalls) {+ if (entry.expiresAt <= now) {+ this.liveCalls.delete(id);+ }+ }+ this.liveCalls.set(callId, { call, expiresAt: now + WhatsAppWebJsAdapter.LIVE_CALL_TTL_MS });+ }++ /**+ * Reject a currently-ringing call. The entry is evicted on ANY attempt (a rejected/ended call+ * will not become rejectable again); an unknown id or an expired entry maps to CallNotFoundError+ * (HTTP 404). A failure of the library's reject() itself propagates as-is.+ */+ async rejectCall(callId: string): Promise<void> {+ const entry = this.liveCalls.get(callId);+ this.liveCalls.delete(callId);+ if (!entry || entry.expiresAt <= Date.now()) {+ throw new CallNotFoundError(callId);+ }+ await entry.call.reject();+ }+/*** Attach to the loosely-typed whatsapp-web.js puppeteer handles (same cast pattern as* isClientRuntimeReady/forceDestroy). whatsapp-web.js itself never listens to these, so without@@ -1035,6 +1222,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate beginClientTeardown(): Client | null {this.tearingDown = true;+ // Any cached call handle is dead once the client goes away — drop them all so a later+ // rejectCall() reports not-found instead of acting on a destroyed page.+ this.liveCalls.clear();const client = this.client;if (!client) return null;@@ -1292,22 +1482,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.ensureReady();this.ensureNotChannelRecipient(chatId);- let messageMedia: MessageMedia;-- if (typeof media.data === 'string') {- if (isHttpUrl(media.data)) {- // URL- messageMedia = await loadRemoteMedia(media.data);- } else {- // Base64- messageMedia = new MessageMedia(media.mimetype, media.data, media.filename);- }- } else {- // Buffer- messageMedia = new MessageMedia(media.mimetype, media.data.toString('base64'), media.filename);- }-// Build the media once (a remote URL is fetched here); sendResolved may retry the send itself.+ const messageMedia = await this.toMessageMedia(media);const msg = await this.sendResolved(chatId, to =>this.client!.sendMessage(to, messageMedia, {caption: media.caption,@@ -1598,6 +1774,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginparticipants,isReadOnly: Boolean(groupChat.isReadOnly),isAnnounce: Boolean(groupChat.isAnnounce),+ announce: groupChat.groupMetadata?.announce,+ locked: groupChat.groupMetadata?.restrict,+ ephemeralSeconds: groupChat.groupMetadata?.ephemeralDuration,linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};} catch (error) {@@ -1979,6 +2158,36 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);}+ // Edit Message+ async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ this.ensureReady();+ // Same lookup window as react/delete: fetchMessages sees only the 100 most recent messages.+ // NOTE: do NOT resolve chatId to @lid here — edit operates on the found message's own key, not+ // this chatId, so LID-resolving the lookup would miss a message stored under the pre-migration+ // @c.us chat (#583 R1 review).+ const chat = await this.client!.getChatById(chatId);+ // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw) — that is the same+ // client-facing outcome as a message outside the fetch window, not a TypeError (-> 500).+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const edited = await message.edit(body);+ if (!edited) {+ // wwebjs RESOLVES null (instead of throwing) when the page-side edit is refused — only the+ // account's own text messages are editable; surface the refusal, not a phantom success.+ throw new EngineRefusedError(+ `the edit of message ${messageId} was rejected — only the account's own text messages can be edited`,+ );+ }+ this.logger.log(`Edited message ${messageId} in chat ${chatId}`);+ return this.toMessageResult(edited);+ }+// Get Profile Pictureasync getProfilePicture(contactId: string): Promise<string | null> {this.ensureReady();@@ -2008,6 +2217,35 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.logger.log(`Unblocked contact ${contactId}`);}+ // ========== Profile (own account) ==========++ async setProfileName(name: string): Promise<void> {+ this.ensureReady();+ // setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.+ const ok = await this.client!.setDisplayName(name);+ if (!ok) {+ throw new EngineRefusedError('the engine rejected the profile name change');+ }+ this.logger.log('Updated profile name');+ }++ async setProfileStatus(status: string): Promise<void> {+ this.ensureReady();+ await this.client!.setStatus(status);+ this.logger.log('Updated profile status');+ }++ async setProfilePicture(media: MediaInput): Promise<void> {+ this.ensureReady();+ const messageMedia = await this.toMessageMedia(media);+ // setProfilePicture resolves false (rather than throwing) when the upload is refused.+ const ok = await this.client!.setProfilePicture(messageMedia);+ if (!ok) {+ throw new EngineRefusedError('the engine rejected the profile picture change');+ }+ this.logger.log('Updated profile picture');+ }+// Get Group Invite Codeasync getGroupInviteCode(groupId: string): Promise<string> {this.ensureReady();@@ -2032,6 +2270,70 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn String(newCode);}+ // Join Group via Invite Code+ async joinGroupViaInviteCode(inviteCode: string): Promise<string> {+ this.ensureReady();+ // acceptInvite throws a page-side evaluation error when the invite is refused (invalid/expired/+ // revoked); otherwise it resolves the joined group's id (`res.gid._serialized || res.gid.$1`,+ // Client.js:1836-1845) — already the neutral `<id>@g.us` dialect. A gid-less result is the same+ // client-facing outcome as a thrown refusal: no such invite (400, not a 500).+ let groupId: string | undefined;+ try {+ groupId = await this.client!.acceptInvite(inviteCode);+ } catch {+ groupId = undefined;+ }+ if (!groupId) {+ throw new InvalidInviteCodeError();+ }+ this.logger.log(`Joined group ${groupId} via invite code`);+ return groupId;+ }++ /** Resolve a group chat or throw — the shared preamble of the group settings writes. */+ private async requireGroupChat(groupId: string): Promise<GroupChat> {+ this.ensureReady();+ const chat = await this.client!.getChatById(groupId);+ // getChatById RESOLVES undefined for an unknown id (wwebjs does not throw): unknown id and a+ // non-group id are the same client-facing outcome — there is no such group (404, not a 500).+ if (!chat?.isGroup) {+ throw new GroupNotFoundError(groupId);+ }+ return chat as unknown as GroupChat;+ }++ // Set "only admins can send messages" (announce)+ async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ const groupChat = await this.requireGroupChat(groupId);+ // Resolves false instead of throwing when the account lacks admin rights (GroupChat.js:503) —+ // surface that as an error rather than a silent no-op.+ const ok = await groupChat.setMessagesAdminsOnly(adminsOnly);+ if (!ok) {+ throw new EngineRefusedError(+ `Failed to update the messages-admins-only setting for group ${groupId} — admin rights required`,+ );+ }+ }++ // Set "only admins can edit group info" (locked/restrict)+ async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ const groupChat = await this.requireGroupChat(groupId);+ const ok = await groupChat.setInfoAdminsOnly(adminsOnly);+ if (!ok) {+ throw new EngineRefusedError(+ `Failed to update the info-admins-only setting for group ${groupId} — admin rights required`,+ );+ }+ }++ // whatsapp-web.js 1.34.7 exposes no disappearing-messages setter (no Client/GroupChat symbol in+ // index.d.ts; only a create-time messageTimer option, Client.js:2371) — an honest 501, not a no-op.+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async setGroupEphemeral(_groupId: string, _durationSec: number): Promise<void> {+ this.ensureReady();+ throw new EngineNotSupportedError('setGroupEphemeral');+ }+// ========== Status/Stories (Phase 3) ==========// Note: These are stub implementations - whatsapp-web.js has limited Status API support/* eslint-disable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */@@ -2119,7 +2421,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate async postMediaStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {this.ensureReady();this.warnStatusRecipientsOnce(options);- const messageMedia = await this.toStatusMessageMedia(media);+ const messageMedia = await this.toMessageMedia(media);const msg = await this.client!.sendMessage('status@broadcast', messageMedia, {...(options.caption !== undefined ? { caption: options.caption } : {}),});@@ -2127,7 +2429,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}/** Build a MessageMedia from a MediaInput (URL → fetched, base64/Buffer → wrapped). */- private async toStatusMessageMedia(media: MediaInput): Promise<MessageMedia> {+ private async toMessageMedia(media: MediaInput): Promise<MessageMedia> {if (typeof media.data === 'string') {if (isHttpUrl(media.data)) return loadRemoteMedia(media.data);return new MessageMedia(media.mimetype, media.data, media.filename);diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex e0ef3c209..7d75efe82 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -18,8 +18,9 @@* fixable without a raw-proto/fork effort or an event-cache hack.* 'uncertain' — source trace was inconclusive; needs a live spike.*- * `evidence` (present only when at least one adapter is `not-available`) cites the library symbol(s)- * that were inspected, so an engineer can open the exact file and start wiring immediately.+ * `evidence` cites the library symbol(s) that were inspected, so an engineer can open the exact file+ * and start wiring immediately. REQUIRED when at least one adapter is `not-available`; may also+ * annotate a newly-wired `supported` row with the symbols it now calls.** This is a SNAPSHOT. `engine-parity.spec.ts` enforces exact matrix-key↔interface-method correspondence* and the throw-invariants it can observe in live adapter method bodies. It does not read the operator@@ -48,7 +49,7 @@ export interface AdapterCapability {export interface MethodCapability {wwjs: AdapterCapability;baileys: AdapterCapability;- /** Cited library symbols (baileys; wwjs). Present only when at least one adapter is not-available. */+ /** Cited library symbols (baileys; wwjs). Required when at least one adapter is not-available. */evidence?: string;}@@ -64,6 +65,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {demoteParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },destroy: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },disconnect: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ editMessage: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Message.edit(content,options?) (index.d.ts:1362; MessageEditOptions:1600); baileys Editable.edit?: WAMessageKey on the text content variant (Types/Message.d.ts:86, AnyRegularMessageContent:168) via sendMessage(jid,{text,edit:key})',+ },forceDestroy: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },forwardMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },getCatalog: {@@ -151,6 +158,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {'baileys no enumerate-newsletters fn; all 23 Socket/newsletter.d.ts exports are per-jid (newsletterMetadata requires a key; newsletterSubscribers returns the count of ONE). Only the newsletter EVENT surfaces jids opportunistically (incremental, not list-all); wwjs Client.getChannels (Client.js:1680)',},initialize: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ joinGroupViaInviteCode: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.acceptInvite(inviteCode) → res.gid._serialized (index.d.ts:23; Client.js:1836-1844); baileys groupAcceptInvite(code) → string|undefined (Socket/groups.d.ts:25) — undefined mapped to a thrown error',+ },leaveGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },logout: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },markUnread: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },@@ -161,6 +174,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {reactToMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },removeLabelFromChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },removeParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ rejectCall: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs Call.reject() (index.d.ts:2417) on the live Call cached from the client 'call' event (index.d.ts:643); baileys rejectCall(callId, callFrom) (Socket/messages-recv.d.ts:10) with the raw `from` JID cached from the 'offer' call event (Types/Call.d.ts)",+ },replyToMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },requestPairingCode: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },resolveContactPhone: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },@@ -189,7 +208,43 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {sendTextMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendVideoMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },setGroupDescription: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setGroupEphemeral: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs 1.34.7 exposes NO ephemeral setter — 0 hits for ephemeral in index.d.ts; only a create-time messageTimer option (Client.js:2371); adapter throws EngineNotSupportedError; baileys groupToggleEphemeral(jid, ephemeralExpiration) (Socket/groups.d.ts:40)',+ },+ setGroupInfoAdminsOnly: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.setInfoAdminsOnly(adminsOnly?) (index.d.ts:2216; sets groupMetadata.restrict, GroupChat.js:544); baileys groupSettingUpdate(jid, 'locked'|'unlocked') (Socket/groups.d.ts:41)",+ },+ setGroupMessagesAdminsOnly: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.setMessagesAdminsOnly(adminsOnly?) (index.d.ts:2210; sets groupMetadata.announce, GroupChat.js:513); baileys groupSettingUpdate(jid, 'announcement'|'not_announcement') (Socket/groups.d.ts:41)",+ },setGroupSubject: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setProfileName: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.setDisplayName(displayName) → boolean (index.d.ts:251; false → adapter throws); baileys updateProfileName(name) (Socket/chats.d.ts:50)',+ },+ setProfilePicture: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.setProfilePicture(MessageMedia) → boolean (index.d.ts:336; false → adapter throws); baileys updateProfilePicture(ownJid, WAMediaUpload) (Socket/chats.d.ts:44)',+ },+ setProfileStatus: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.setStatus(status) (index.d.ts:245); baileys updateProfileStatus(status) (Socket/chats.d.ts:49)',+ },subscribeToChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },unsubscribeFromChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex a66dd1440..e1743c94e 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -191,6 +191,12 @@ export interface GroupInfo {participants: GroupParticipant[];isReadOnly?: boolean;isAnnounce?: boolean;+ /** Only admins can send messages (the WhatsApp "announce" group setting). */+ announce?: boolean;+ /** Only admins can edit group info — subject, description, picture (the WhatsApp "locked"/restrict setting). */+ locked?: boolean;+ /** Disappearing-messages timer in seconds; 0 or undefined = off. */+ ephemeralSeconds?: number;/** JID of the parent community this group is linked to, or null if standalone. */linkedParentJID?: string | null;}@@ -407,6 +413,49 @@ export interface ReactionEvent {senderId: string;}+/**+ * A group membership or metadata change, mapped at the adapter boundary to this neutral+ * shape so consumers never see engine-specific payloads:+ * - whatsapp-web.js: `group_join` / `group_leave` / `group_update` (GroupNotification).+ * - Baileys: `group-participants.update` (add/remove only — promote/demote are not+ * surfaced) and `groups.update` (subject/desc/announce/restrict).+ * All ids are in the neutral dialect (`@g.us` / `@c.us`; a lid stays `<id>@lid` when the+ * lid->phone mapping is unknown).+ */+export interface GroupEvent {+ kind: 'join' | 'leave' | 'update';+ /** Neutral group id (`@g.us`). */+ groupId: string;+ /** Who performed the action, neutral user id when the engine reports one. */+ actorId?: string;+ /** Affected users (join/leave), neutral ids. Empty for metadata updates. */+ participantIds: string[];+ /** Metadata delta for kind 'update'; absent or partially populated for join/leave. */+ changes?: { subject?: string; description?: string; announce?: boolean; locked?: boolean };+ /** Unix seconds when the change occurred (engine timestamp when available, else receipt time). */+ timestamp: number;+}++/**+ * An incoming (ringing) call, mapped at the adapter boundary to this neutral shape:+ * - whatsapp-web.js: the client `call` event (a `Call` object the adapter caches so a later+ * `rejectCall` can act on it — the object is only usable while the call is live).+ * - Baileys: the `call` event's `offer` status entries (other statuses are lifecycle updates and+ * are not surfaced).+ * All ids are in the neutral dialect (`@c.us`; a lid caller stays `<id>@lid` when the lid->phone+ * mapping is unknown, resolved via the inline phone twin when the engine provides one).+ */+export interface IncomingCallEvent {+ /** Engine call id; the handle `rejectCall` accepts while the call is still ringing. */+ callId: string;+ /** Neutral caller id. */+ from: string;+ isVideo: boolean;+ isGroup: boolean;+ /** Unix seconds when the call was created (engine timestamp). */+ timestamp: number;+}+export interface EngineEventCallbacks {onQRCode?: (qr: string) => void;onReady?: (phone: string, pushName: string) => void;@@ -424,6 +473,18 @@ export interface EngineEventCallbacks {onMessageRevoked?: (message: RevokedMessage) => void;onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;+ /**+ * Fired on group membership changes (join/leave) and group metadata updates+ * (subject/description/announce/locked). The `kind` selects the consumer event name+ * (`group.join` / `group.leave` / `group.update`).+ */+ onGroupEvent?: (event: GroupEvent) => void;+ /**+ * Fired when an incoming call starts ringing (consumers emit `call.received`). The call can be+ * rejected via `rejectCall(callId)` only while it is still ringing — the adapter keeps the+ * engine's live call handle cached for that window.+ */+ onCall?: (event: IncomingCallEvent) => void;/*** Bulk historical messages from an engine's initial sync (e.g. Baileys `messaging-history.set`).* They predate the live session, so consumers persist them for the chat view but must not dispatch.@@ -522,16 +583,51 @@ export interface IWhatsAppEngine {setGroupDescription(groupId: string, description: string): Promise<void>;getGroupInviteCode(groupId: string): Promise<string>;revokeGroupInviteCode(groupId: string): Promise<string>;+ /**+ * Join a group via an invite code (the token from a `https://chat.whatsapp.com/<code>` link).+ * Resolves with the joined group's neutral id (`<id>@g.us`).+ */+ joinGroupViaInviteCode(inviteCode: string): Promise<string>;+ /** Set the "only admins can send messages" group setting (WhatsApp announce). */+ setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void>;+ /** Set the "only admins can edit group info" group setting (WhatsApp locked/restrict). */+ setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void>;+ /**+ * Set the group's disappearing-messages timer in seconds; 0 disables it.+ * Known values: 86400 (24h), 604800 (7d), 7776000 (90d).+ */+ setGroupEphemeral(groupId: string, durationSec: number): Promise<void>;// Message OperationsdeleteMessage(chatId: string, messageId: string, forEveryone?: boolean): Promise<void>;+ /**+ * Edit the body of a text message. Only the account's OWN messages can be edited; engines reject+ * non-text or foreign messages at their own layer — the engine's error is surfaced as-is.+ */+ editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult>;getChatHistory(chatId: string, limit?: number, includeMedia?: boolean): Promise<IncomingMessage[]>;+ // Calls+ /**+ * Reject an incoming call. Only a currently-ringing call can be rejected: the adapter keeps the+ * engine's live call handle (keyed by the `callId` from {@link IncomingCallEvent}) for the+ * ringing window, and an unknown or expired callId fails with a not-found error (HTTP 404).+ */+ rejectCall(callId: string): Promise<void>;+// Contact Extended OperationsgetProfilePicture(contactId: string): Promise<string | null>;blockContact(contactId: string): Promise<void>;unblockContact(contactId: string): Promise<void>;+ // Profile (own account)+ /** Set the account's display name. */+ setProfileName(name: string): Promise<void>;+ /** Set the account's "about" / status text. */+ setProfileStatus(status: string): Promise<void>;+ /** Set the account's profile picture (a URL payload is fetched server-side). */+ setProfilePicture(media: MediaInput): Promise<void>;+// Labels (Phase 3) - WhatsApp Business onlygetLabels(): Promise<Label[]>;getLabelById(labelId: string): Promise<Label | null>;diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex e2fb2295d..7e6a67fc3 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -28,6 +28,12 @@ export interface GroupMetadataRaw {parentGroup?: SerializedWid | string | null;linkedParentGroup?: SerializedWid | string | null;linkedParent?: SerializedWid | string | null;+ /** Only admins can post (WA Web group model; written by GroupChat.setMessagesAdminsOnly). */+ announce?: boolean;+ /** Only admins can edit group info (written by GroupChat.setInfoAdminsOnly). */+ restrict?: boolean;+ /** Disappearing-messages timer in seconds, when WA Web reports one on the group model. */+ ephemeralDuration?: number;}/**@@ -58,6 +64,10 @@ export interface GroupChat extends Omit<Chat, 'isReadOnly' | 'getLabels'> {removeLabel(id: string): Promise<void>;getInviteCode(): Promise<string>;revokeInvite(): Promise<string>;+ /** Resolves false when the account lacks admin rights (does not throw). */+ setMessagesAdminsOnly(adminsOnly?: boolean): Promise<boolean>;+ /** Resolves false when the account lacks admin rights (does not throw). */+ setInfoAdminsOnly(adminsOnly?: boolean): Promise<boolean>;}/**diff --git a/src/modules/call/call.controller.spec.ts b/src/modules/call/call.controller.spec.tsnew file mode 100644index 000000000..241525e20--- /dev/null+++ b/src/modules/call/call.controller.spec.ts@@ -0,0 +1,31 @@+import { BadRequestException } from '@nestjs/common';+import { CallController } from './call.controller';+import { CallService } from './call.service';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';++describe('CallController', () => {+ const build = (service: Partial<Record<keyof CallService, jest.Mock>>) => {+ const controller = new CallController(service as unknown as CallService);+ return { controller, service };+ };++ it('POST :callId/reject returns the success envelope', async () => {+ const { controller, service } = build({ rejectCall: jest.fn().mockResolvedValue(undefined) });+ await expect(controller.reject('s1', 'CALL1')).resolves.toEqual({ success: true });+ expect(service.rejectCall).toHaveBeenCalledWith('s1', 'CALL1');+ });++ it('propagates a service rejection (session not started -> 400)', async () => {+ const { controller } = build({+ rejectCall: jest.fn().mockRejectedValue(new BadRequestException('Session is not started')),+ });+ await expect(controller.reject('s1', 'CALL1')).rejects.toThrow(BadRequestException);+ });++ it('propagates a service rejection (unknown/expired call id -> 404)', async () => {+ const { controller } = build({+ rejectCall: jest.fn().mockRejectedValue(new CallNotFoundError('CALL1')),+ });+ await expect(controller.reject('s1', 'CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ });+});diff --git a/src/modules/call/call.controller.ts b/src/modules/call/call.controller.tsnew file mode 100644index 000000000..c77c91ad8--- /dev/null+++ b/src/modules/call/call.controller.ts@@ -0,0 +1,25 @@+import { Controller, Post, Param, HttpCode, HttpStatus } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';+import { CallService } from './call.service';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++@ApiTags('calls')+@Controller('sessions/:sessionId/calls')+export class CallController {+ constructor(private readonly callService: CallService) {}++ @Post(':callId/reject')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Reject a ringing incoming call' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'callId', description: 'Call ID from the call.received event' })+ @ApiResponse({ status: 200, description: 'Call rejected' })+ @ApiResponse({ status: 400, description: 'Session is not started' })+ @ApiResponse({ status: 404, description: 'Call not found or no longer ringing' })+ async reject(@Param('sessionId') sessionId: string, @Param('callId') callId: string) {+ await this.callService.rejectCall(sessionId, callId);+ return { success: true };+ }+}diff --git a/src/modules/call/call.module.ts b/src/modules/call/call.module.tsnew file mode 100644index 000000000..be2b3e2e8--- /dev/null+++ b/src/modules/call/call.module.ts@@ -0,0 +1,12 @@+import { Module } from '@nestjs/common';+import { CallController } from './call.controller';+import { CallService } from './call.service';+import { SessionModule } from '../session/session.module';++@Module({+ imports: [SessionModule],+ controllers: [CallController],+ providers: [CallService],+ exports: [CallService],+})+export class CallModule {}diff --git a/src/modules/call/call.service.spec.ts b/src/modules/call/call.service.spec.tsnew file mode 100644index 000000000..c85a0afe8--- /dev/null+++ b/src/modules/call/call.service.spec.ts@@ -0,0 +1,33 @@+import { BadRequestException } from '@nestjs/common';+import { CallService } from './call.service';+import { SessionService } from '../session/session.service';+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { CallNotFoundError } from '../../common/errors/call-not-found.error';++describe('CallService', () => {+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;+ return new CallService(sessionService);+ };++ it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {+ // The guard throws synchronously; the controller method is `async`, so this still surfaces+ // as a rejected promise -> 400 at the HTTP layer (same shape as GroupService).+ const svc = makeService(undefined);+ expect(() => svc.rejectCall('s1', 'CALL1')).toThrow(BadRequestException);+ expect(() => svc.rejectCall('s1', 'CALL1')).toThrow('Session is not started');+ });++ it('delegates rejectCall to the engine when the session is started', async () => {+ const rejectCall = jest.fn().mockResolvedValue(undefined);+ const svc = makeService({ rejectCall });+ await svc.rejectCall('s1', 'CALL1');+ expect(rejectCall).toHaveBeenCalledWith('CALL1');+ });++ it('propagates the engine not-found error (unknown/expired call id -> 404)', async () => {+ const rejectCall = jest.fn().mockRejectedValue(new CallNotFoundError('CALL1'));+ const svc = makeService({ rejectCall });+ await expect(svc.rejectCall('s1', 'CALL1')).rejects.toBeInstanceOf(CallNotFoundError);+ });+});diff --git a/src/modules/call/call.service.ts b/src/modules/call/call.service.tsnew file mode 100644index 000000000..e10196284--- /dev/null+++ b/src/modules/call/call.service.ts@@ -0,0 +1,30 @@+import { Injectable, BadRequestException } from '@nestjs/common';+import { SessionService } from '../session/session.service';+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';++/**+ * Owns engine access for call operations. Controllers depend on this service instead of+ * reaching for the raw `IWhatsAppEngine` via `sessionService.getEngine`, so the "session not+ * started" guard lives in one place (mirrors GroupService).+ */+@Injectable()+export class CallService {+ constructor(private readonly sessionService: SessionService) {}++ private getEngine(sessionId: string): IWhatsAppEngine {+ const engine = this.sessionService.getEngine(sessionId);+ if (!engine) {+ throw new BadRequestException('Session is not started');+ }+ return engine;+ }++ /**+ * Reject a currently-ringing incoming call. An unknown or no-longer-ringing callId surfaces+ * as 404 via the adapter's CallNotFoundError; EngineNotSupportedError would map to 501 (both+ * engines support rejectCall today, so no special-casing here).+ */+ rejectCall(sessionId: string, callId: string): Promise<void> {+ return this.getEngine(sessionId).rejectCall(callId);+ }+}diff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex f51f665b4..d72ba5665 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -12,8 +12,6 @@ export type WSServerMessageType = 'subscribed' | 'unsubscribed' | 'event' | 'err// Valid event types that can be subscribed to over the socket. Every entry here MUST have a// matching EventsGateway.emit* producer — the drift guard in events.gateway.spec asserts this.-// (group.* are NOT listed: they have no engine emit source and were never delivered; they stay-// reserved on the webhook side via WEBHOOK_RESERVED_EVENTS.)export const SUBSCRIBABLE_EVENTS = ['message.received','message.sent',@@ -25,6 +23,10 @@ export const SUBSCRIBABLE_EVENTS = ['session.qr','session.authenticated','session.disconnected',+ 'group.join',+ 'group.leave',+ 'group.update',+ 'call.received',] as const;export type SubscribableEvent = (typeof SUBSCRIBABLE_EVENTS)[number] | '*';diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 7ebe1ea15..68eeeacb7 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -137,7 +137,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.join).toHaveBeenCalled();});- it('rejects a subscription to a reserved, never-emitted event (group.*) with INVALID_EVENTS', async () => {+ it('accepts a subscription to group.join (a live, engine-emitted event)', async () => {authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });const sock = makeSocket({ apiKey: 'good' });await gateway.handleConnection(asSocket(sock));@@ -145,6 +145,21 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {const res = (await gateway.handleMessage(asSocket(sock),subscribeMsg('sess-1', ['group.join']),+ )) as WSSubscribedResponse;++ expect(res.type).toBe('subscribed');+ expect(res.events).toEqual(['group.join']);+ expect(sock.join).toHaveBeenCalledWith(buildRoomName('sess-1', 'group.join'));+ });++ it('rejects a subscription to an unknown, never-emitted event with INVALID_EVENTS', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['session.connected']),)) as WSErrorResponse;expect(res.type).toBe('error');@@ -152,14 +167,14 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.join).not.toHaveBeenCalled();});- it('keeps the valid events when a subscription mixes a valid and a reserved event', async () => {+ it('keeps the valid events when a subscription mixes a valid and an unknown event', async () => {authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });const sock = makeSocket({ apiKey: 'good' });await gateway.handleConnection(asSocket(sock));const res = (await gateway.handleMessage(asSocket(sock),- subscribeMsg('sess-1', ['message.received', 'group.join']),+ subscribeMsg('sess-1', ['message.received', 'session.connected']),)) as WSSubscribedResponse;expect(res.type).toBe('subscribed');@@ -425,7 +440,12 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {expect(new Set(SUBSCRIBABLE_EVENTS)).toEqual(deriveEmittedEvents());});- it('reserved webhook group.* events are NOT advertised as socket-subscribable', () => {+ it('reserved webhook events (currently none) never overlap the socket-subscribable catalog', () => {+ // WEBHOOK_RESERVED_EVENTS is intentionally empty — the former group.* occupants are now live,+ // engine-emitted (and socket-subscribable) events covered by the equality guard above. The+ // export stays so a future declared-but-undispatched event can be whitelisted there; whenever+ // the list is non-empty, no reserved event may also be advertised as subscribable.+ expect(WEBHOOK_RESERVED_EVENTS).toHaveLength(0);for (const reserved of WEBHOOK_RESERVED_EVENTS) {expect(SUBSCRIBABLE_EVENTS).not.toContain(reserved);}diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 18e85d094..63e8dabf3 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -466,4 +466,36 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateemitMessageEdited(sessionId: string, data: Record<string, unknown>) {this.emitToRooms(sessionId, 'message.edited', data);}++ /**+ * Emit a group membership join (a user was added or joined via invite). Payload mirrors the+ * `group.join` webhook: `{ groupId, participantIds, timestamp, actorId? }`.+ */+ emitGroupJoin(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'group.join', data);+ }++ /**+ * Emit a group membership leave (a user left or was removed). Payload mirrors the+ * `group.leave` webhook: `{ groupId, participantIds, timestamp, actorId? }`.+ */+ emitGroupLeave(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'group.leave', data);+ }++ /**+ * Emit a group metadata update (subject/description/announce/locked). Payload mirrors the+ * `group.update` webhook: `{ groupId, participantIds, changes, timestamp, actorId? }`.+ */+ emitGroupUpdate(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'group.update', data);+ }++ /**+ * Emit an incoming-call notification (a call is ringing). Payload mirrors the `call.received`+ * webhook: `{ callId, from, isVideo, isGroup, timestamp }`.+ */+ emitCallReceived(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'call.received', data);+ }}diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.tsindex e1abb7ec9..66313151c 100644--- a/src/modules/group/dto/group.dto.spec.ts+++ b/src/modules/group/dto/group.dto.spec.ts@@ -1,7 +1,14 @@import 'reflect-metadata';import { validate, ValidationError } from 'class-validator';import { plainToInstance } from 'class-transformer';-import { ParticipantsDto, CreateGroupDto, GroupSubjectDto, GroupDescriptionDto } from './group.dto';+import {+ ParticipantsDto,+ CreateGroupDto,+ GroupSubjectDto,+ GroupDescriptionDto,+ JoinGroupDto,+ GroupSettingsDto,+} from './group.dto';// Mirror the global ValidationPipe options (src/main.ts): whitelist + forbidNonWhitelisted.const PIPE_OPTS = { whitelist: true, forbidNonWhitelisted: true };@@ -45,4 +52,34 @@ describe('group DTO validation', () => {expect(await errorsFor(GroupDescriptionDto, { description: 'a'.repeat(1024) })).toHaveLength(0);expect((await errorsFor(GroupDescriptionDto, { description: 'a'.repeat(1025) })).length).toBeGreaterThan(0);});++ it('requires a non-empty invite code on JoinGroupDto', async () => {+ expect(await errorsFor(JoinGroupDto, { inviteCode: 'AbCdEfGhIjKl' })).toHaveLength(0);+ expect((await errorsFor(JoinGroupDto, { inviteCode: '' })).length).toBeGreaterThan(0);+ expect((await errorsFor(JoinGroupDto, {})).length).toBeGreaterThan(0);+ });++ it('GroupSettingsDto accepts an empty body and any subset of fields (at-least-one is a service rule)', async () => {+ expect(await errorsFor(GroupSettingsDto, {})).toHaveLength(0);+ expect(await errorsFor(GroupSettingsDto, { announce: true })).toHaveLength(0);+ expect(await errorsFor(GroupSettingsDto, { announce: false, locked: true, ephemeralSeconds: 0 })).toHaveLength(0);+ });++ it('GroupSettingsDto rejects wrong field types and a negative timer', async () => {+ expect((await errorsFor(GroupSettingsDto, { announce: 'yes' })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { locked: 1 })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { ephemeralSeconds: -1 })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { ephemeralSeconds: 1.5 })).length).toBeGreaterThan(0);+ });++ it('GroupSettingsDto rejects an explicit null (400) instead of applying it as a value', async () => {+ expect((await errorsFor(GroupSettingsDto, { announce: null })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { locked: null })).length).toBeGreaterThan(0);+ expect((await errorsFor(GroupSettingsDto, { ephemeralSeconds: null })).length).toBeGreaterThan(0);+ });++ it('GroupSettingsDto still rejects unknown properties (forbidNonWhitelisted intact)', async () => {+ const errors = await errorsFor(GroupSettingsDto, { announce: true, hacker: true });+ expect(errors.some(e => e.property === 'hacker')).toBe(true);+ });});diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex 050719e56..3de22c748 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -1,5 +1,15 @@-import { ApiProperty } from '@nestjs/swagger';-import { IsArray, ArrayNotEmpty, IsString, IsNotEmpty, MaxLength } from 'class-validator';+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import {+ IsArray,+ ArrayNotEmpty,+ IsString,+ IsNotEmpty,+ MaxLength,+ IsBoolean,+ IsInt,+ Min,+ ValidateIf,+} from 'class-validator';export class CreateGroupDto {@ApiProperty({ description: 'Group subject/name', maxLength: 100 })@@ -37,3 +47,42 @@ export class GroupDescriptionDto {@MaxLength(1024)description: string;}++export class JoinGroupDto {+ @ApiProperty({+ description: 'Group invite code (the token from a https://chat.whatsapp.com/<code> link)',+ maxLength: 128,+ })+ @IsString()+ @IsNotEmpty()+ @MaxLength(128)+ inviteCode: string;+}++/**+ * All fields optional, but at least one must be present — enforced in GroupService.updateGroupSettings+ * (a class-validator "at least one of" idiom does not exist; an empty body is a client error, 400).+ * ValidateIf (not @IsOptional) so an explicit `null` fails validation (400) instead of being applied+ * as a value; only `undefined` (absent) skips the field.+ */+export class GroupSettingsDto {+ @ApiPropertyOptional({ description: 'Only admins can send messages (announce group)' })+ @ValidateIf((o: GroupSettingsDto) => o.announce !== undefined)+ @IsBoolean()+ announce?: boolean;++ @ApiPropertyOptional({ description: 'Only admins can edit group info (locked group)' })+ @ValidateIf((o: GroupSettingsDto) => o.locked !== undefined)+ @IsBoolean()+ locked?: boolean;++ @ApiPropertyOptional({+ description:+ 'Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d)',+ minimum: 0,+ })+ @ValidateIf((o: GroupSettingsDto) => o.ephemeralSeconds !== undefined)+ @IsInt()+ @Min(0)+ ephemeralSeconds?: number;+}diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.tsnew file mode 100644index 000000000..5300ef2b9--- /dev/null+++ b/src/modules/group/group.controller.spec.ts@@ -0,0 +1,51 @@+import { GroupController } from './group.controller';+import { GroupService } from './group.service';++describe('GroupController join + settings', () => {+ const build = (service: Partial<Record<keyof GroupService, jest.Mock>>) => {+ const controller = new GroupController(service as unknown as GroupService);+ return { controller, service };+ };++ it('POST join returns the success envelope with the group id', async () => {+ const { controller, service } = build({+ joinGroupViaInviteCode: jest.fn().mockResolvedValue('[email protected]'),+ });+ await expect(controller.join('s1', { inviteCode: 'CODE123' })).resolves.toEqual({+ success: true,+ groupId: '[email protected]',+ });+ expect(service.joinGroupViaInviteCode).toHaveBeenCalledWith('s1', 'CODE123');+ });++ it('GET :groupId/settings delegates to the service (404 mapping lives there)', async () => {+ const { controller, service } = build({+ getGroupSettings: jest.fn().mockResolvedValue({ announce: true, locked: false, ephemeralSeconds: 86400 }),+ });+ await expect(controller.getSettings('s1', 'g1')).resolves.toEqual({+ announce: true,+ locked: false,+ ephemeralSeconds: 86400,+ });+ expect(service.getGroupSettings).toHaveBeenCalledWith('s1', 'g1');+ });++ it('PUT :groupId/settings forwards the patch and returns the success envelope', async () => {+ const { controller, service } = build({ updateGroupSettings: jest.fn().mockResolvedValue(undefined) });+ const dto = { announce: true, ephemeralSeconds: 0 };+ await expect(controller.updateSettings('s1', 'g1', dto)).resolves.toEqual({+ success: true,+ message: 'Group settings updated',+ });+ expect(service.updateGroupSettings).toHaveBeenCalledWith('s1', 'g1', dto);+ });++ it('PUT :groupId/settings propagates a service rejection (empty patch / 501 passthrough)', async () => {+ const { controller } = build({+ updateGroupSettings: jest+ .fn()+ .mockRejectedValue(new Error('At least one of announce, locked, ephemeralSeconds must be provided')),+ });+ await expect(controller.updateSettings('s1', 'g1', {})).rejects.toThrow(/At least one/);+ });+});diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex 60551094a..83af1726a 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -1,7 +1,14 @@import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';import { GroupService } from './group.service';-import { CreateGroupDto, ParticipantsDto, GroupSubjectDto, GroupDescriptionDto } from './dto/group.dto';+import {+ CreateGroupDto,+ ParticipantsDto,+ GroupSubjectDto,+ GroupDescriptionDto,+ JoinGroupDto,+ GroupSettingsDto,+} from './dto/group.dto';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -24,6 +31,46 @@ export class GroupController {return this.groupService.getGroupInfo(sessionId, groupId);}+ @Post('join')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Join a group via invite code' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: JoinGroupDto })+ @ApiResponse({ status: 200, description: 'Joined the group' })+ async join(@Param('sessionId') sessionId: string, @Body() dto: JoinGroupDto) {+ const groupId = await this.groupService.joinGroupViaInviteCode(sessionId, dto.inviteCode);+ return { success: true, groupId };+ }++ @Get(':groupId/settings')+ @ApiOperation({ summary: 'Get group settings (announce / locked / ephemeral timer)' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'groupId', description: 'Group ID' })+ @ApiResponse({ status: 200, description: 'Group settings' })+ @ApiResponse({ status: 404, description: 'Group not found' })+ async getSettings(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {+ return this.groupService.getGroupSettings(sessionId, groupId);+ }++ @Put(':groupId/settings')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Update group settings (announce / locked / ephemeral timer)' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'groupId', description: 'Group ID' })+ @ApiBody({ type: GroupSettingsDto })+ @ApiResponse({ status: 200, description: 'Group settings updated' })+ @ApiResponse({ status: 400, description: 'No setting provided' })+ @ApiResponse({ status: 501, description: 'The active engine does not support a requested setting' })+ async updateSettings(+ @Param('sessionId') sessionId: string,+ @Param('groupId') groupId: string,+ @Body() dto: GroupSettingsDto,+ ) {+ await this.groupService.updateGroupSettings(sessionId, groupId, dto);+ return { success: true, message: 'Group settings updated' };+ }+@Post()@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Create a new group' })diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex 8a84a628a..f59f1996d 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -2,6 +2,7 @@ import { BadRequestException, NotFoundException } from '@nestjs/common';import { GroupService } from './group.service';import { SessionService } from '../session/session.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';describe('GroupService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {@@ -56,4 +57,97 @@ describe('GroupService', () => {await svc.addParticipants('s1', 'g1', ['[email protected]', '[email protected]']);expect(addParticipants).toHaveBeenCalledWith('g1', ['[email protected]', '[email protected]']);});++ it('joinGroupViaInviteCode delegates and returns the group id', async () => {+ const joinGroupViaInviteCode = jest.fn().mockResolvedValue('[email protected]');+ const svc = makeService({ joinGroupViaInviteCode });+ await expect(svc.joinGroupViaInviteCode('s1', 'CODE123')).resolves.toBe('[email protected]');+ expect(joinGroupViaInviteCode).toHaveBeenCalledWith('CODE123');+ });++ describe('getGroupSettings', () => {+ it('maps the settings fields from getGroupInfo', async () => {+ const svc = makeService({+ getGroupInfo: jest.fn().mockResolvedValue({ id: 'g1', announce: true, locked: false, ephemeralSeconds: 86400 }),+ });+ await expect(svc.getGroupSettings('s1', 'g1')).resolves.toEqual({+ announce: true,+ locked: false,+ ephemeralSeconds: 86400,+ });+ });++ it('omits ephemeralSeconds when the engine does not report one', async () => {+ const svc = makeService({+ getGroupInfo: jest.fn().mockResolvedValue({ id: 'g1', announce: true, locked: true }),+ });+ const settings = (await svc.getGroupSettings('s1', 'g1')) as Record<string, unknown>;+ expect(settings).toEqual({ announce: true, locked: true });+ expect('ephemeralSeconds' in settings).toBe(false);+ });++ it('maps an unknown group to 404 (same rule as getGroupInfo)', async () => {+ const svc = makeService({ getGroupInfo: jest.fn().mockResolvedValue(null) });+ await expect(svc.getGroupSettings('s1', 'g404')).rejects.toBeInstanceOf(NotFoundException);+ });+ });++ describe('updateGroupSettings', () => {+ it('rejects an empty patch with 400 (at least one setting required)', async () => {+ const svc = makeService({});+ await expect(svc.updateGroupSettings('s1', 'g1', {})).rejects.toBeInstanceOf(BadRequestException);+ });++ it('invokes only the engine methods for the fields present', async () => {+ const engine = {+ setGroupMessagesAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupInfoAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupEphemeral: jest.fn().mockResolvedValue(undefined),+ };+ const svc = makeService(engine);+ await svc.updateGroupSettings('s1', 'g1', { announce: true });+ expect(engine.setGroupMessagesAdminsOnly).toHaveBeenCalledWith('g1', true);+ expect(engine.setGroupInfoAdminsOnly).not.toHaveBeenCalled();+ expect(engine.setGroupEphemeral).not.toHaveBeenCalled();+ });++ it('applies all three fields when all are present (incl. ephemeral 0 = disable)', async () => {+ const engine = {+ setGroupMessagesAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupInfoAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupEphemeral: jest.fn().mockResolvedValue(undefined),+ };+ const svc = makeService(engine);+ await svc.updateGroupSettings('s1', 'g1', { announce: false, locked: true, ephemeralSeconds: 0 });+ expect(engine.setGroupMessagesAdminsOnly).toHaveBeenCalledWith('g1', false);+ expect(engine.setGroupInfoAdminsOnly).toHaveBeenCalledWith('g1', true);+ expect(engine.setGroupEphemeral).toHaveBeenCalledWith('g1', 0);+ });++ it('lets EngineNotSupportedError propagate (→ 501)', async () => {+ const engine = {+ setGroupEphemeral: jest.fn().mockRejectedValue(new EngineNotSupportedError('setGroupEphemeral')),+ };+ const svc = makeService(engine);+ await expect(svc.updateGroupSettings('s1', 'g1', { ephemeralSeconds: 3600 })).rejects.toBeInstanceOf(+ EngineNotSupportedError,+ );+ });++ it('applies ephemeralSeconds FIRST so a 501 cannot leave announce/locked half-applied (wwjs case)', async () => {+ // wwjs always 501s setGroupEphemeral: a {announce, ephemeralSeconds} patch must fail BEFORE+ // touching announce/locked, not after a silent partial application.+ const engine = {+ setGroupMessagesAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupInfoAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupEphemeral: jest.fn().mockRejectedValue(new EngineNotSupportedError('setGroupEphemeral')),+ };+ const svc = makeService(engine);+ await expect(+ svc.updateGroupSettings('s1', 'g1', { announce: true, locked: true, ephemeralSeconds: 86400 }),+ ).rejects.toBeInstanceOf(EngineNotSupportedError);+ expect(engine.setGroupMessagesAdminsOnly).not.toHaveBeenCalled();+ expect(engine.setGroupInfoAdminsOnly).not.toHaveBeenCalled();+ });+ });});diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex b7d6c89bd..3f3a3679a 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -75,4 +75,48 @@ export class GroupService {revokeGroupInviteCode(sessionId: string, groupId: string) {return this.getEngine(sessionId).revokeGroupInviteCode(groupId);}++ joinGroupViaInviteCode(sessionId: string, inviteCode: string) {+ return this.getEngine(sessionId).joinGroupViaInviteCode(inviteCode);+ }++ /** Read the group's announce/locked/ephemeral settings; 404s (via getGroupInfo) when unknown. */+ async getGroupSettings(sessionId: string, groupId: string) {+ const group = await this.getGroupInfo(sessionId, groupId);+ return {+ announce: group.announce,+ locked: group.locked,+ ...(group.ephemeralSeconds !== undefined ? { ephemeralSeconds: group.ephemeralSeconds } : {}),+ };+ }++ /**+ * Apply the given settings; each present field maps to one engine call, absent fields stay+ * untouched. An empty patch is a client error. EngineNotSupportedError (e.g. ephemeralSeconds on+ * the wwjs engine) propagates as 501.+ *+ * Ordering matters: ephemeralSeconds is applied FIRST because it is the only field with a+ * deterministic per-engine refusal (wwjs always 501s it). Applying announce/locked first would+ * leave a silently half-applied patch behind when the ephemeral call then throws.+ */+ async updateGroupSettings(+ sessionId: string,+ groupId: string,+ settings: { announce?: boolean; locked?: boolean; ephemeralSeconds?: number },+ ) {+ const { announce, locked, ephemeralSeconds } = settings;+ if (announce === undefined && locked === undefined && ephemeralSeconds === undefined) {+ throw new BadRequestException('At least one of announce, locked, ephemeralSeconds must be provided');+ }+ const engine = this.getEngine(sessionId);+ if (ephemeralSeconds !== undefined) {+ await engine.setGroupEphemeral(groupId, ephemeralSeconds);+ }+ if (announce !== undefined) {+ await engine.setGroupMessagesAdminsOnly(groupId, announce);+ }+ if (locked !== undefined) {+ await engine.setGroupInfoAdminsOnly(groupId, locked);+ }+ }}diff --git a/src/modules/message/dto/message-actions.dto.spec.ts b/src/modules/message/dto/message-actions.dto.spec.tsindex 5c43413f0..a438601cd 100644--- a/src/modules/message/dto/message-actions.dto.spec.ts+++ b/src/modules/message/dto/message-actions.dto.spec.ts@@ -6,6 +6,7 @@ import {ReactMessageDto,DeleteMessageDto,ForwardMessageDto,+ EditMessageDto,} from './message-actions.dto';/**@@ -92,4 +93,23 @@ describe('message action DTOs', () => {expect(errs.some(e => e.property === 'toChatId')).toBe(true);expect(errs.some(e => e.property === 'messageId')).toBe(true);});++ it('EditMessageDto: a valid edit passes', async () => {+ expect(await errorsFor(EditMessageDto, { chatId: '[email protected]', messageId: 'm1', body: 'new text' })).toHaveLength(0);+ });++ it('EditMessageDto: an empty body is rejected (an edit needs text)', async () => {+ const errs = await errorsFor(EditMessageDto, { chatId: '[email protected]', messageId: 'm1', body: '' });+ expect(errs.some(e => e.property === 'body')).toBe(true);+ });++ it('EditMessageDto: a body over 4096 chars is rejected (same cap as send-text)', async () => {+ const errs = await errorsFor(EditMessageDto, { chatId: '[email protected]', messageId: 'm1', body: 'x'.repeat(4097) });+ expect(errs.some(e => e.property === 'body')).toBe(true);+ });++ it('EditMessageDto: missing messageId is rejected', async () => {+ const errs = await errorsFor(EditMessageDto, { chatId: '[email protected]', body: 'new text' });+ expect(errs.some(e => e.property === 'messageId')).toBe(true);+ });});diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex 2bc03b330..505f9ad16 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -166,3 +166,22 @@ export class DeleteMessageDto {@IsBoolean()forEveryone?: boolean;}++export class EditMessageDto {+ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ chatId: string;++ @ApiProperty()+ @IsString()+ @IsNotEmpty()+ messageId: string;++ // Same body cap as SendTextMessageDto.text — an edit cannot exceed what a send allows.+ @ApiProperty({ description: 'New text body for the message', maxLength: 4096 })+ @IsString()+ @IsNotEmpty()+ @MaxLength(4096)+ body: string;+}diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 72e659644..6c0467abe 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -13,6 +13,7 @@ import {ForwardMessageDto,ReactMessageDto,DeleteMessageDto,+ EditMessageDto,} from './dto/message-actions.dto';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -362,6 +363,27 @@ export class MessageController {return { success: true };}+ // ========== Edit Message ==========++ @Post('edit')+ @HttpCode(HttpStatus.OK)+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Edit the text of a message sent by this account' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description: 'Message edited',+ type: MessageResponseDto,+ })+ @ApiResponse({+ status: 400,+ description: 'Session not active or invalid request',+ })+ @ApiResponse({ status: 404, description: 'Message not found' })+ async edit(@Param('sessionId') sessionId: string, @Body() dto: EditMessageDto): Promise<MessageResponseDto> {+ return this.messageService.editMessage(sessionId, dto);+ }+// ========== Bulk Messaging ==========@Post('send-bulk')diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex f3a2c59a3..2a3888d41 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -29,6 +29,7 @@ function createMockEngine() {reactToMessage: jest.fn().mockResolvedValue(undefined),getMessageReactions: jest.fn().mockResolvedValue([]),deleteMessage: jest.fn().mockResolvedValue(undefined),+ editMessage: jest.fn().mockResolvedValue(mockEngineResult),getChatHistory: jest.fn().mockResolvedValue([]),sendChatState: jest.fn().mockResolvedValue(undefined),};@@ -68,6 +69,7 @@ describe('MessageService', () => {sessionService = {getEngine: jest.fn().mockReturnValue(mockEngine),findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),+ recordOutboundMessageEdit: jest.fn().mockResolvedValue(undefined),};hookManager = {@@ -995,6 +997,43 @@ describe('MessageService', () => {});});+ describe('editMessage', () => {+ it('edits via the engine, delegates the stored-row update, and returns the engine result', async () => {+ const res = await service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' });++ expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'edited');+ // Persistence is delegated to the session's per-message mutation queue (serialized with the+ // inbound edit path) — the service no longer writes the row directly.+ expect(sessionService.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'edited');+ expect(repository.update).not.toHaveBeenCalled();+ expect(res).toEqual({ messageId: 'wa-msg-1', timestamp: 1706868000 });+ });++ it('still succeeds when the delegated stored-row update is a no-op (the engine edit already happened)', async () => {+ // recordOutboundMessageEdit is best-effort by contract (never rejects); a missing row or a+ // failed write is logged inside the session service, not surfaced here.+ const res = await service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' });++ expect(res).toEqual({ messageId: 'wa-msg-1', timestamp: 1706868000 });+ });++ it('propagates the engine not-found error as-is (MessageNotFoundError → 404)', async () => {+ mockEngine.editMessage.mockRejectedValueOnce(new NotFoundException('Message wa-msg-1 not found'));+ await expect(+ service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' }),+ ).rejects.toBeInstanceOf(NotFoundException);+ expect(sessionService.recordOutboundMessageEdit).not.toHaveBeenCalled();+ });++ it('throws BadRequestException when the session is not started', async () => {+ (sessionService.getEngine as jest.Mock).mockReturnValue(undefined);+ await expect(+ service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' }),+ ).rejects.toBeInstanceOf(BadRequestException);+ expect(mockEngine.editMessage).not.toHaveBeenCalled();+ });+ });+/*** The empty id is the engine's "sent, but I couldn't read the id back" signal (#757). It has to reach* the DB as NULL: UQ_messages_sessionId_waMessageId is NOT partial, so '' collides with the nextdiff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 99692a715..d2022b47a 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -668,6 +668,22 @@ export class MessageService {}}+ // ========== Edit Message ==========++ async editMessage(+ sessionId: string,+ dto: { chatId: string; messageId: string; body: string },+ ): Promise<MessageResponseDto> {+ const engine = this.getEngine(sessionId);+ const result = await engine.editMessage(dto.chatId, dto.messageId, dto.body);++ // Best-effort: reflect the new body in the stored copy (mirrors deleteMessage's revoked flag),+ // serialized with the inbound edit/reaction writers through the session's per-message mutation+ // queue. A missing row must not fail the request — the engine edit already succeeded.+ await this.sessionService.recordOutboundMessageEdit(sessionId, dto.messageId, dto.body);+ return { messageId: result.id, timestamp: result.timestamp };+ }+private getEngine(sessionId: string) {const engine = this.sessionService.getEngine(sessionId);if (!engine) {diff --git a/src/modules/profile/dto/profile.dto.spec.ts b/src/modules/profile/dto/profile.dto.spec.tsnew file mode 100644index 000000000..96d790bd3--- /dev/null+++ b/src/modules/profile/dto/profile.dto.spec.ts@@ -0,0 +1,49 @@+import 'reflect-metadata';+import { validate, ValidationError } from 'class-validator';+import { plainToInstance } from 'class-transformer';+import { SetProfileNameDto, SetProfileStatusDto, SetProfilePictureDto } from './profile.dto';++// Mirror the global ValidationPipe options (src/main.ts): whitelist + forbidNonWhitelisted.+const PIPE_OPTS = { whitelist: true, forbidNonWhitelisted: true };++function errorsFor<T extends object>(cls: new () => T, payload: unknown): Promise<ValidationError[]> {+ return validate(plainToInstance(cls, payload as object), PIPE_OPTS);+}++describe('profile DTO validation', () => {+ it('requires a non-empty name within the WhatsApp limit (25)', async () => {+ expect(await errorsFor(SetProfileNameDto, { name: 'OpenWA Bot' })).toHaveLength(0);+ expect((await errorsFor(SetProfileNameDto, { name: '' })).length).toBeGreaterThan(0);+ expect((await errorsFor(SetProfileNameDto, {})).length).toBeGreaterThan(0);+ expect((await errorsFor(SetProfileNameDto, { name: 'x'.repeat(26) })).length).toBeGreaterThan(0);+ });++ it('allows an empty status (clears the about) and caps it at the WhatsApp limit (139)', async () => {+ expect(await errorsFor(SetProfileStatusDto, { status: '' })).toHaveLength(0);+ expect(await errorsFor(SetProfileStatusDto, { status: 'x'.repeat(139) })).toHaveLength(0);+ expect((await errorsFor(SetProfileStatusDto, { status: 'x'.repeat(140) })).length).toBeGreaterThan(0);+ expect((await errorsFor(SetProfileStatusDto, {})).length).toBeGreaterThan(0);+ });++ it('accepts a picture body with url or base64 (either/or is a service rule)', async () => {+ expect(await errorsFor(SetProfilePictureDto, { url: 'https://example.com/a.jpg' })).toHaveLength(0);+ expect(await errorsFor(SetProfilePictureDto, { base64: 'QUJD', mimetype: 'image/png' })).toHaveLength(0);+ });++ it('rejects a non-URL url and skips the URL check when base64 is present (#670 alignment)', async () => {+ expect((await errorsFor(SetProfilePictureDto, { url: 'not-a-url' })).length).toBeGreaterThan(0);+ expect(await errorsFor(SetProfilePictureDto, { url: 'not-a-url', base64: 'QUJD' })).toHaveLength(0);+ });++ it('rejects a non-image mimetype fast (400) — a profile picture is an image by definition', async () => {+ expect(+ (await errorsFor(SetProfilePictureDto, { base64: 'QUJD', mimetype: 'application/pdf' })).length,+ ).toBeGreaterThan(0);+ expect(await errorsFor(SetProfilePictureDto, { base64: 'QUJD', mimetype: 'image/png' })).toHaveLength(0);+ });++ it('still rejects unknown properties (forbidNonWhitelisted intact)', async () => {+ const errors = await errorsFor(SetProfilePictureDto, { base64: 'QUJD', hacker: true });+ expect(errors.some(e => e.property === 'hacker')).toBe(true);+ });+});diff --git a/src/modules/profile/dto/profile.dto.ts b/src/modules/profile/dto/profile.dto.tsnew file mode 100644index 000000000..f1bae075e--- /dev/null+++ b/src/modules/profile/dto/profile.dto.ts@@ -0,0 +1,54 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsString, IsNotEmpty, MaxLength, IsOptional, IsUrl, Matches, ValidateIf } from 'class-validator';++export class SetProfileNameDto {+ @ApiProperty({ description: 'New display name (WhatsApp limit: 25 characters)', maxLength: 25 })+ @IsString()+ @IsNotEmpty()+ @MaxLength(25)+ name: string;+}++export class SetProfileStatusDto {+ @ApiProperty({+ description: 'New about/status text (may be empty to clear it; WhatsApp limit: 139 characters)',+ maxLength: 139,+ })+ @IsString()+ @MaxLength(139)+ status: string;+}++/**+ * Media arrives as JSON — a public URL (server-fetched, SSRF-guarded) or inline base64 — the same+ * acceptance pattern as the message module's media endpoints (SendMediaMessageDto).+ */+export class SetProfilePictureDto {+ @ApiPropertyOptional({+ description: 'Image URL (http/https)',+ example: 'https://example.com/avatar.jpg',+ })+ @IsOptional()+ @IsUrl()+ @ValidateIf((o: SetProfilePictureDto) => !o.base64)+ url?: string;++ @ApiPropertyOptional({+ description: 'Base64 encoded image data',+ })+ @IsOptional()+ @IsString()+ @ValidateIf((o: SetProfilePictureDto) => !o.url)+ base64?: string;++ @ApiPropertyOptional({+ description: 'Image MIME type (required when using base64)',+ example: 'image/jpeg',+ })+ @IsOptional()+ @IsString()+ // A profile picture is an image by definition — fail non-image mimetypes fast (400) instead of+ // letting the engine reject (or worse, accept) an arbitrary payload.+ @Matches(/^image\//)+ mimetype?: string;+}diff --git a/src/modules/profile/profile.controller.spec.ts b/src/modules/profile/profile.controller.spec.tsnew file mode 100644index 000000000..a9b944930--- /dev/null+++ b/src/modules/profile/profile.controller.spec.ts@@ -0,0 +1,37 @@+import { ProfileController } from './profile.controller';+import { ProfileService } from './profile.service';++describe('ProfileController', () => {+ const build = (service: Partial<Record<keyof ProfileService, jest.Mock>>) => {+ const controller = new ProfileController(service as unknown as ProfileService);+ return { controller, service };+ };++ it('PUT name delegates and returns the success envelope', async () => {+ const { controller, service } = build({ setProfileName: jest.fn().mockResolvedValue(undefined) });+ await expect(controller.setName('s1', { name: 'New Name' })).resolves.toEqual({+ success: true,+ message: 'Profile name updated',+ });+ expect(service.setProfileName).toHaveBeenCalledWith('s1', 'New Name');+ });++ it('PUT status delegates and returns the success envelope', async () => {+ const { controller, service } = build({ setProfileStatus: jest.fn().mockResolvedValue(undefined) });+ await expect(controller.setStatus('s1', { status: 'busy' })).resolves.toEqual({+ success: true,+ message: 'Profile status updated',+ });+ expect(service.setProfileStatus).toHaveBeenCalledWith('s1', 'busy');+ });++ it('PUT picture forwards the media body unchanged and returns the success envelope', async () => {+ const { controller, service } = build({ setProfilePicture: jest.fn().mockResolvedValue(undefined) });+ const dto = { base64: 'QUJD', mimetype: 'image/png' };+ await expect(controller.setPicture('s1', dto)).resolves.toEqual({+ success: true,+ message: 'Profile picture updated',+ });+ expect(service.setProfilePicture).toHaveBeenCalledWith('s1', dto);+ });+});diff --git a/src/modules/profile/profile.controller.ts b/src/modules/profile/profile.controller.tsnew file mode 100644index 000000000..a4ba70c7d--- /dev/null+++ b/src/modules/profile/profile.controller.ts@@ -0,0 +1,46 @@+import { Controller, Put, Param, Body } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';+import { ProfileService } from './profile.service';+import { SetProfileNameDto, SetProfileStatusDto, SetProfilePictureDto } from './dto/profile.dto';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++@ApiTags('profile')+@Controller('sessions/:sessionId/profile')+export class ProfileController {+ constructor(private readonly profileService: ProfileService) {}++ @Put('name')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Set the account display name' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SetProfileNameDto })+ @ApiResponse({ status: 200, description: 'Profile name updated' })+ async setName(@Param('sessionId') sessionId: string, @Body() dto: SetProfileNameDto) {+ await this.profileService.setProfileName(sessionId, dto.name);+ return { success: true, message: 'Profile name updated' };+ }++ @Put('status')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Set the account about/status text' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SetProfileStatusDto })+ @ApiResponse({ status: 200, description: 'Profile status updated' })+ async setStatus(@Param('sessionId') sessionId: string, @Body() dto: SetProfileStatusDto) {+ await this.profileService.setProfileStatus(sessionId, dto.status);+ return { success: true, message: 'Profile status updated' };+ }++ @Put('picture')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Set the account profile picture (URL or base64 image)' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SetProfilePictureDto })+ @ApiResponse({ status: 200, description: 'Profile picture updated' })+ @ApiResponse({ status: 400, description: 'Neither url nor base64 provided, or base64 without mimetype' })+ async setPicture(@Param('sessionId') sessionId: string, @Body() dto: SetProfilePictureDto) {+ await this.profileService.setProfilePicture(sessionId, dto);+ return { success: true, message: 'Profile picture updated' };+ }+}diff --git a/src/modules/profile/profile.module.ts b/src/modules/profile/profile.module.tsnew file mode 100644index 000000000..409aa6e60--- /dev/null+++ b/src/modules/profile/profile.module.ts@@ -0,0 +1,12 @@+import { Module } from '@nestjs/common';+import { ProfileController } from './profile.controller';+import { ProfileService } from './profile.service';+import { SessionModule } from '../session/session.module';++@Module({+ imports: [SessionModule],+ controllers: [ProfileController],+ providers: [ProfileService],+ exports: [ProfileService],+})+export class ProfileModule {}diff --git a/src/modules/profile/profile.service.spec.ts b/src/modules/profile/profile.service.spec.tsnew file mode 100644index 000000000..5d349c203--- /dev/null+++ b/src/modules/profile/profile.service.spec.ts@@ -0,0 +1,70 @@+import { BadRequestException } from '@nestjs/common';+import { ProfileService } from './profile.service';+import { SessionService } from '../session/session.service';+import { IWhatsAppEngine, MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';++describe('ProfileService', () => {+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;+ return new ProfileService(sessionService);+ };++ it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {+ const svc = makeService(undefined);+ expect(() => svc.setProfileName('s1', 'Name')).toThrow(BadRequestException);+ expect(() => svc.setProfileName('s1', 'Name')).toThrow('Session is not started');+ });++ it('setProfileName delegates to the engine', async () => {+ const setProfileName = jest.fn().mockResolvedValue(undefined);+ await makeService({ setProfileName }).setProfileName('s1', 'New Name');+ expect(setProfileName).toHaveBeenCalledWith('New Name');+ });++ it('setProfileStatus delegates to the engine (empty string clears the about)', async () => {+ const setProfileStatus = jest.fn().mockResolvedValue(undefined);+ await makeService({ setProfileStatus }).setProfileStatus('s1', '');+ expect(setProfileStatus).toHaveBeenCalledWith('');+ });++ describe('setProfilePicture', () => {+ it('rejects a body with neither url nor base64 (400)', () => {+ // The guard throws synchronously (the service method is a thin sync pass-through, like GroupService).+ const svc = makeService({ setProfilePicture: jest.fn() });+ expect(() => svc.setProfilePicture('s1', {})).toThrow('Either url or base64 must be provided');+ });++ it('requires mimetype when base64 is used (400)', () => {+ const svc = makeService({ setProfilePicture: jest.fn() });+ expect(() => svc.setProfilePicture('s1', { base64: 'QUJD' })).toThrow(+ 'mimetype is required when using base64 data',+ );+ });++ it('maps a base64 body to a MediaInput (base64 wins over a stale url, #670)', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(undefined);+ await makeService({ setProfilePicture }).setProfilePicture('s1', {+ base64: 'QUJD',+ mimetype: 'image/png',+ url: 'https://example.com/stale.jpg',+ });+ const calls = setProfilePicture.mock.calls as Array<[MediaInput]>;+ expect(calls[0][0]).toEqual({ mimetype: 'image/png', data: 'QUJD' });+ });++ it('maps a url body to a MediaInput with the default image mimetype', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(undefined);+ await makeService({ setProfilePicture }).setProfilePicture('s1', { url: 'https://example.com/a.jpg' });+ expect(setProfilePicture).toHaveBeenCalledWith({ mimetype: 'image/jpeg', data: 'https://example.com/a.jpg' });+ });++ it('accepts a data: URI base64 payload (prefix stripped like the message module)', async () => {+ const setProfilePicture = jest.fn().mockResolvedValue(undefined);+ await makeService({ setProfilePicture }).setProfilePicture('s1', {+ base64: 'data:image/png;base64,QUJD',+ mimetype: 'image/png',+ });+ expect(setProfilePicture).toHaveBeenCalledWith({ mimetype: 'image/png', data: 'QUJD' });+ });+ });+});diff --git a/src/modules/profile/profile.service.ts b/src/modules/profile/profile.service.tsnew file mode 100644index 000000000..846e3c2f6--- /dev/null+++ b/src/modules/profile/profile.service.ts@@ -0,0 +1,48 @@+import { Injectable, BadRequestException } from '@nestjs/common';+import { SessionService } from '../session/session.service';+import { IWhatsAppEngine, MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';+import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';+import { SetProfilePictureDto } from './dto/profile.dto';++/**+ * Owns engine access for own-profile operations. Thin pass-throughs behind the same+ * "session not started" guard as the other session-scoped services (see GroupService).+ */+@Injectable()+export class ProfileService {+ constructor(private readonly sessionService: SessionService) {}++ private getEngine(sessionId: string): IWhatsAppEngine {+ const engine = this.sessionService.getEngine(sessionId);+ if (!engine) {+ throw new BadRequestException('Session is not started');+ }+ return engine;+ }++ setProfileName(sessionId: string, name: string) {+ return this.getEngine(sessionId).setProfileName(name);+ }++ setProfileStatus(sessionId: string, status: string) {+ return this.getEngine(sessionId).setProfileStatus(status);+ }++ /** Map the JSON media body to a MediaInput exactly like the message module's media sends do. */+ setProfilePicture(sessionId: string, dto: SetProfilePictureDto) {+ const base64 = stripBase64DataUri(dto.base64);+ if (!dto.url && !base64) {+ throw new BadRequestException('Either url or base64 must be provided');+ }+ if (base64 && !dto.mimetype) {+ throw new BadRequestException('mimetype is required when using base64 data');+ }+ assertBase64WithinMediaCap(base64);+ const media: MediaInput = {+ mimetype: dto.mimetype || 'image/jpeg',+ // base64 wins over url when both are present (mirrors buildMediaInput, #670).+ data: base64 || dto.url!,+ };+ return this.getEngine(sessionId).setProfilePicture(media);+ }+}diff --git a/src/modules/session/dto/create-session.dto.ts b/src/modules/session/dto/create-session.dto.tsindex 544a7af35..063c4f281 100644--- a/src/modules/session/dto/create-session.dto.ts+++ b/src/modules/session/dto/create-session.dto.ts@@ -17,7 +17,9 @@ export class CreateSessionDto {name: string;@ApiPropertyOptional({- description: 'Session configuration options',+ description:+ 'Session configuration options. Set autoRejectCalls (boolean, default false) to ' ++ 'automatically reject incoming calls — the call.received event is still emitted.',example: { autoReconnect: true },})@IsOptional()diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 70e0867b6..8a50598b7 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -20,7 +20,13 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';-import { IncomingMessage, EngineEventCallbacks, EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import {+ IncomingMessage,+ EngineEventCallbacks,+ EngineStatus,+ GroupEvent,+ IncomingCallEvent,+} from '../../engine/interfaces/whatsapp-engine.interface';import { BaileysSessionStore } from '../../engine/adapters/baileys-session-store';import {getSessionReconnectAttemptsTotal,@@ -112,6 +118,7 @@ describe('SessionService', () => {deleteChat: jest.fn().mockResolvedValue(true),sendChatState: jest.fn().mockResolvedValue(undefined),resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),+ rejectCall: jest.fn().mockResolvedValue(undefined),};engineFactory = {@@ -129,6 +136,10 @@ describe('SessionService', () => {emitMessageRevoked: jest.fn(),emitMessageReaction: jest.fn(),emitMessageEdited: jest.fn(),+ emitGroupJoin: jest.fn(),+ emitGroupLeave: jest.fn(),+ emitGroupUpdate: jest.fn(),+ emitCallReceived: jest.fn(),emitQRCode: jest.fn(),};@@ -3271,6 +3282,273 @@ describe('SessionService', () => {});});+ // ── recordOutboundMessageEdit (REST outbound edit -> the same mutation queue) ──++ describe('recordOutboundMessageEdit', () => {+ const startAndCaptureEditCallback = async (): Promise<NonNullable<EngineEventCallbacks['onMessageEdited']>> => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const initializeCall = mockEngine.initialize.mock.calls[0] as unknown[];+ const callbacks = initializeCall[0] as EngineEventCallbacks;+ return callbacks.onMessageEdited!;+ };++ const inboundEdit = {+ messageId: 'WA_MSG_EDIT_1',+ chatId: '[email protected]',+ body: 'inbound edit',+ senderId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ fromMe: false,+ isGroup: false,+ type: 'text' as const,+ hasMedia: false,+ timestamp: 1700000005,+ };++ it('serializes the outbound write with a queued inbound edit on the same message', async () => {+ const releases: Array<() => void> = [];+ (messageRepository.update as jest.Mock).mockImplementation(+ () =>+ new Promise(resolve => {+ releases.push(() => resolve({ affected: 1 }));+ }),+ );+ const onMessageEdited = await startAndCaptureEditCallback();++ // The inbound edit lands first; the REST outbound edit for the same message must queue BEHIND+ // it instead of racing the row directly (latest-write-wins across both directions).+ onMessageEdited(inboundEdit);+ const outbound = service.recordOutboundMessageEdit('sess-uuid-1', 'WA_MSG_EDIT_1', 'outbound edit');+ await new Promise(resolve => setImmediate(resolve));++ expect(messageRepository.update).toHaveBeenCalledTimes(1); // only the inbound write started++ releases[0]();+ await new Promise(resolve => setImmediate(resolve)); // chain advances to the queued outbound write++ expect(messageRepository.update).toHaveBeenCalledTimes(2);++ releases[1]();+ await outbound; // resolves once its own queued write has run++ const bodies = (messageRepository.update as jest.Mock).mock.calls.map(+ call => (call as [unknown, { body: string }])[1].body,+ );+ expect(bodies).toEqual(['inbound edit', 'outbound edit']);+ });++ it('is best-effort: a missing row / failed write does not reject the request', async () => {+ (messageRepository.update as jest.Mock).mockRejectedValueOnce(new Error('db down'));++ await expect(service.recordOutboundMessageEdit('sess-uuid-1', 'GONE', 'x')).resolves.toBeUndefined();+ });+ });++ // ── onGroupEvent ──────────────────────────────────────────────────++ describe('onGroupEvent callback', () => {+ const startAndCaptureGroupCallback = async (): Promise<NonNullable<EngineEventCallbacks['onGroupEvent']>> => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const initializeCall = mockEngine.initialize.mock.calls[0] as unknown[];+ const callbacks = initializeCall[0] as EngineEventCallbacks;+ return callbacks.onGroupEvent!;+ };++ const groupEvent = (over: Partial<GroupEvent> = {}): GroupEvent => ({+ kind: 'join',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000900,+ ...over,+ });++ it('dispatches a join as group.join to BOTH the webhook stream and the socket room', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();++ onGroupEvent(groupEvent());++ const payload = {+ groupId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000900,+ actorId: '[email protected]',+ };+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'group.join', payload);+ expect(eventsGateway.emitGroupJoin).toHaveBeenCalledWith('sess-uuid-1', payload);+ expect(eventsGateway.emitGroupLeave).not.toHaveBeenCalled();+ expect(eventsGateway.emitGroupUpdate).not.toHaveBeenCalled();+ });++ it('dispatches a leave as group.leave', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();++ onGroupEvent(groupEvent({ kind: 'leave' }));++ expect(webhookService.dispatch).toHaveBeenCalledWith(+ 'sess-uuid-1',+ 'group.leave',+ expect.objectContaining({ groupId: '[email protected]', participantIds: ['[email protected]'] }),+ );+ expect(eventsGateway.emitGroupLeave).toHaveBeenCalledTimes(1);+ expect(eventsGateway.emitGroupJoin).not.toHaveBeenCalled();+ });++ it('dispatches an update as group.update, carrying the changes delta', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();++ onGroupEvent(+ groupEvent({ kind: 'update', participantIds: [], changes: { subject: 'New name', announce: true } }),+ );++ expect(webhookService.dispatch).toHaveBeenCalledWith(+ 'sess-uuid-1',+ 'group.update',+ expect.objectContaining({+ groupId: '[email protected]',+ participantIds: [],+ changes: { subject: 'New name', announce: true },+ timestamp: 1700000900,+ }),+ );+ expect(eventsGateway.emitGroupUpdate).toHaveBeenCalledWith(+ 'sess-uuid-1',+ expect.objectContaining({ changes: { subject: 'New name', announce: true } }),+ );+ expect(eventsGateway.emitGroupJoin).not.toHaveBeenCalled();+ });++ it('omits the actorId/changes keys entirely when the engine did not report them', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();++ onGroupEvent({ kind: 'join', groupId: '[email protected]', participantIds: [], timestamp: 1700000901 });++ const dispatchCalls = (webhookService.dispatch as jest.Mock).mock.calls as Array<+ [string, string, Record<string, unknown>]+ >;+ const dispatched = dispatchCalls.find(call => call[1] === 'group.join')?.[2];+ expect(dispatched).toEqual({ groupId: '[email protected]', participantIds: [], timestamp: 1700000901 });+ // Absent, not explicit-undefined: consumers diffing on key presence see no actor/delta at all.+ expect(Object.keys(dispatched ?? {})).toEqual(['groupId', 'participantIds', 'timestamp']);+ });++ it('drops the event when it arrives from a stale (superseded) engine', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();+ // A newer engine now owns the id (restart/reconnect window): the captured callback is stale.+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;+ engines.set('sess-uuid-1', { marker: 'engine-B' });+ (webhookService.dispatch as jest.Mock).mockClear();++ onGroupEvent(groupEvent());++ expect(webhookService.dispatch).not.toHaveBeenCalled();+ expect(eventsGateway.emitGroupJoin).not.toHaveBeenCalled();+ expect(eventsGateway.emitGroupLeave).not.toHaveBeenCalled();+ expect(eventsGateway.emitGroupUpdate).not.toHaveBeenCalled();+ });+ });++ // ── onCall ────────────────────────────────────────────────────────++ describe('onCall callback', () => {+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));++ const startAndCaptureCallCallback = async (+ config: Record<string, unknown> = {},+ ): Promise<NonNullable<EngineEventCallbacks['onCall']>> => {+ const session = createMockSession({ config });+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const initializeCall = mockEngine.initialize.mock.calls[0] as unknown[];+ const callbacks = initializeCall[0] as EngineEventCallbacks;+ return callbacks.onCall!;+ };++ const callEvent = (over: Partial<IncomingCallEvent> = {}): IncomingCallEvent => ({+ callId: 'CALL1',+ from: '[email protected]',+ isVideo: false,+ isGroup: false,+ timestamp: 1700000900,+ ...over,+ });++ it('dispatches call.received to BOTH the webhook stream and the socket room', async () => {+ const onCall = await startAndCaptureCallCallback();++ onCall(callEvent());++ const payload = {+ callId: 'CALL1',+ from: '[email protected]',+ isVideo: false,+ isGroup: false,+ timestamp: 1700000900,+ };+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'call.received', payload);+ expect(eventsGateway.emitCallReceived).toHaveBeenCalledWith('sess-uuid-1', payload);+ });++ it('auto-rejects via the engine when config.autoRejectCalls is strictly true', async () => {+ const onCall = await startAndCaptureCallCallback({ autoRejectCalls: true });++ onCall(callEvent());+ await flush();++ expect(mockEngine.rejectCall).toHaveBeenCalledWith('CALL1');+ // The event is still emitted — auto-reject never suppresses dispatch.+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'call.received', expect.anything());+ });++ it.each([{ autoRejectCalls: 'yes' }, { autoRejectCalls: 1 }, {}])(+ 'does NOT auto-reject for a truthy non-boolean or absent flag: %o',+ async config => {+ const onCall = await startAndCaptureCallCallback(config);++ onCall(callEvent());+ await flush();++ expect(mockEngine.rejectCall).not.toHaveBeenCalled();+ // Dispatch is unaffected by the flag either way.+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'call.received', expect.anything());+ },+ );++ it('still dispatches the event when the auto-reject itself fails', async () => {+ const onCall = await startAndCaptureCallCallback({ autoRejectCalls: true });+ mockEngine.rejectCall.mockRejectedValue(new Error('call already ended'));++ onCall(callEvent());+ await flush(); // must not produce an unhandled rejection++ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'call.received', expect.anything());+ expect(eventsGateway.emitCallReceived).toHaveBeenCalledTimes(1);+ });++ it('drops the event when it arrives from a stale (superseded) engine', async () => {+ const onCall = await startAndCaptureCallCallback({ autoRejectCalls: true });+ // A newer engine now owns the id (restart/reconnect window): the captured callback is stale.+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;+ engines.set('sess-uuid-1', { marker: 'engine-B' });+ (webhookService.dispatch as jest.Mock).mockClear();++ onCall(callEvent());+ await flush();++ expect(webhookService.dispatch).not.toHaveBeenCalled();+ expect(eventsGateway.emitCallReceived).not.toHaveBeenCalled();+ expect(mockEngine.rejectCall).not.toHaveBeenCalled();+ });+ });+// ── getActiveCount / isActive ─────────────────────────────────────describe('getActiveCount', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex eb6ff3b32..3c90a4d18 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -37,6 +37,8 @@ import {IncomingMessage,ReactionEvent,EditedMessage,+ GroupEvent,+ IncomingCallEvent,} from '../../engine/interfaces/whatsapp-engine.interface';import { createLogger } from '../../common/services/logger.service';import { ShutdownService } from '../../common/services/shutdown.service';@@ -1253,6 +1255,31 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatthis.enqueueMessageMutation(id, message.messageId, () => this.applyMessageEdit(id, message));},+ onGroupEvent: (event): void => {+ if (!this.isLiveEngine(id, engine)) return;+ this.logger.debug(`Group event: ${event.kind} in ${event.groupId}`, {+ sessionId: id,+ groupId: event.groupId,+ kind: event.kind,+ action: 'group_event',+ });+ this.dispatchGroupEvent(id, event);+ },+ onCall: (event: IncomingCallEvent): void => {+ if (!this.isLiveEngine(id, engine)) return;+ this.logger.log(`Incoming call from ${event.from}`, {+ sessionId: id,+ callId: event.callId,+ isVideo: event.isVideo,+ isGroup: event.isGroup,+ action: 'call_received',+ });+ const payload: Record<string, unknown> = { ...event };+ this.eventsGateway.emitCallReceived(id, payload);+ void this.webhookService.dispatch(id, 'call.received', payload);+ // Opt-in auto-reject runs AFTER the dispatch so a reject failure can never eat the event.+ void this.maybeAutoRejectCall(id, engine, event.callId);+ },onDisconnected: (reason: string): void => {if (!this.isLiveEngine(id, engine)) return;// Shared with the liveness watchdog (see handleEngineDisconnected). The handler re-reads the@@ -1461,6 +1488,103 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatvoid this.webhookService.dispatch(id, 'message.edited', editedPayload);}+ /**+ * Reflect an OUTBOUND edit (REST MessageService.editMessage) in the stored row, routed through the+ * same per-message mutation queue as the inbound edit/reaction paths so the two writers cannot+ * interleave (latest-write-wins holds across both directions). Same best-effort semantics as+ * applyMessageEdit: a missing row or a failed write must not fail the request — the engine edit+ * already succeeded. Resolves once the queued write has run.+ */+ async recordOutboundMessageEdit(sessionId: string, messageId: string, body: string): Promise<void> {+ await new Promise<void>(resolve => {+ this.enqueueMessageMutation(sessionId, messageId, async () => {+ try {+ await this.messageRepository.update({ sessionId, waMessageId: messageId }, { body });+ } catch (err) {+ this.logger.warn(`Failed to update stored body of edited message ${messageId}`, { error: String(err) });+ } finally {+ resolve();+ }+ });+ });+ }++ /**+ * Fan a neutral engine GroupEvent out to consumers: the WebSocket room and the webhook stream.+ * The `kind` selects the event name (`group.join` / `group.leave` / `group.update`); the payload+ * is the same plain camelCase shape on both channels, with `kind` itself carried by the name.+ * There is no persistence here — group membership/metadata lives in the engine, not the message+ * store — so unlike message edits there is nothing to apply before notifying.+ */+ private dispatchGroupEvent(id: string, event: GroupEvent): void {+ const payload: Record<string, unknown> = {+ groupId: event.groupId,+ participantIds: event.participantIds,+ timestamp: event.timestamp,+ };+ // Optional fields are added only when present so consumers never see explicit `undefined`s.+ if (event.actorId !== undefined) {+ payload.actorId = event.actorId;+ }+ if (event.changes !== undefined) {+ payload.changes = event.changes;+ }++ switch (event.kind) {+ case 'join':+ this.eventsGateway.emitGroupJoin(id, payload);+ void this.webhookService.dispatch(id, 'group.join', payload);+ break;+ case 'leave':+ this.eventsGateway.emitGroupLeave(id, payload);+ void this.webhookService.dispatch(id, 'group.leave', payload);+ break;+ case 'update':+ this.eventsGateway.emitGroupUpdate(id, payload);+ void this.webhookService.dispatch(id, 'group.update', payload);+ break;+ }+ }++ /**+ * Reject a ringing call when the session opted in via `config.autoRejectCalls`. The session row+ * is re-read here rather than trusting initializeEngine's closure snapshot — a call can arrive+ * long after start, and the row is the only always-current source (mirrors+ * handleEngineDisconnected). `config` is an untyped JSON column: only a strict boolean `true`+ * opts in — truthy strings/numbers are ignored (the coercion discipline of+ * resolveReconnectConfig). Never throws: a reject failure is logged, and the `call.received`+ * dispatch already happened before this ran.+ */+ private async maybeAutoRejectCall(id: string, engine: IWhatsAppEngine, callId: string): Promise<void> {+ let session: Session | null;+ try {+ session = await this.sessionRepository.findOne({ where: { id } });+ } catch (err) {+ this.logger.error('Failed to reload the session for call auto-reject', String(err), {+ sessionId: id,+ action: 'call_auto_reject_error',+ });+ return;+ }+ if (session?.config?.autoRejectCalls !== true) {+ return;+ }+ try {+ await engine.rejectCall(callId);+ this.logger.log('Auto-rejected incoming call', {+ sessionId: id,+ callId,+ action: 'call_auto_rejected',+ });+ } catch (err) {+ this.logger.warn('Failed to auto-reject incoming call', {+ sessionId: id,+ callId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+/*** Shared disconnect handling for BOTH the engine's onDisconnected callback and the liveness* watchdog: notify consumers (webhook + WS + hook), persist DISCONNECTED, then schedule adiff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex ea4f14e55..6d51b0aa3 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -27,10 +27,11 @@ const FILTERS_API_EXAMPLE = {],};-// Reserved: valid webhook subscription targets that are not dispatched yet (no engine-// emit source). Kept in WEBHOOK_EVENTS so existing subscriptions validate; tracked-// separately so the catalog/emitter drift guard can whitelist them as intentional.-export const WEBHOOK_RESERVED_EVENTS = ['group.join', 'group.leave', 'group.update'] as const;+// Reserved: valid webhook subscription targets that are declared but have no engine emit+// source yet. Currently EMPTY — the former occupants (group.join/leave/update) are now+// dispatched by both engines. Kept as a named export so the catalog/emitter drift guard+// can whitelist any future intentionally-undeployed event without changing its imports.+export const WEBHOOK_RESERVED_EVENTS = [] as const;export const WEBHOOK_EVENTS = ['message.received',@@ -45,6 +46,10 @@ export const WEBHOOK_EVENTS = ['session.authenticated','session.disconnected','session.reconnect_loop',+ 'group.join',+ 'group.leave',+ 'group.update',+ 'call.received',...WEBHOOK_RESERVED_EVENTS,] as const;diff --git a/src/modules/webhook/utils/idempotency.util.spec.ts b/src/modules/webhook/utils/idempotency.util.spec.tsindex 92738f8b8..40e1e338f 100644--- a/src/modules/webhook/utils/idempotency.util.spec.ts+++ b/src/modules/webhook/utils/idempotency.util.spec.ts@@ -164,12 +164,71 @@ describe('Idempotency Utils', () => {);});- it('should generate key for group.join', () => {- const key = generateIdempotencyKey('group.join', {- groupId: 'grp_1',- participantId: 'user_1',- });- expect(key).toBe('grp_grp_1_user_1_join');+ it('keys group.join on the group + affected participants (the real participantIds payload)', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const key = generateIdempotencyKey(+ 'group.join',+ { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 },+ at,+ );+ expect(key).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_join_2026-07-20T00:00:00\.000Z$/);+ });++ it('is retry-stable for group.join: the same occurrence regenerates the same key', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };+ expect(generateIdempotencyKey('group.join', data, at)).toBe(generateIdempotencyKey('group.join', data, at));+ });++ it('salts group.join keys so a leave-then-rejoin of the same user stays a distinct event', () => {+ const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };+ const a = generateIdempotencyKey('group.join', data, '2026-07-20T00:00:00.000Z');+ const b = generateIdempotencyKey('group.join', data, '2026-07-20T01:00:00.000Z');+ expect(a).not.toBe(b);+ });++ it('gives different participants distinct group.join keys for the same occurrence', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const a = generateIdempotencyKey('group.join', { groupId: '[email protected]', participantIds: ['[email protected]'] }, at);+ const b = generateIdempotencyKey('group.join', { groupId: '[email protected]', participantIds: ['[email protected]'] }, at);+ expect(a).not.toBe(b);+ });++ it('keys group.leave symmetrically to group.join (and distinct from it)', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const data = { groupId: '[email protected]', participantIds: ['[email protected]'] };+ const join = generateIdempotencyKey('group.join', data, at);+ const leave = generateIdempotencyKey('group.leave', data, at);+ expect(leave).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_leave_/);+ expect(leave).not.toBe(join);+ });++ it('keys group.update on WHAT changed, salted per occurrence', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const data = { groupId: '[email protected]', changes: { subject: 'New name' }, timestamp: 1782000000 };+ const a = generateIdempotencyKey('group.update', data, at);+ expect(a).toMatch(/^grp_123@g\.us_update_[a-f0-9]{12}_2026-07-20T00:00:00\.000Z$/);+ // Retry of the same delivery stays stable...+ expect(generateIdempotencyKey('group.update', data, at)).toBe(a);+ // ...a later identical update is a distinct occurrence...+ expect(generateIdempotencyKey('group.update', data, '2026-07-20T00:05:00.000Z')).not.toBe(a);+ // ...and a different change differs even inside the same dispatch window.+ expect(generateIdempotencyKey('group.update', { groupId: '[email protected]', changes: { announce: true } }, at)).not.toBe(+ a,+ );+ });++ it('keys call.received on the session + call id (unique per call, no occurrence salt needed)', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const data = { sessionId: 'A', callId: 'CALL1', from: '[email protected]', timestamp: 1782000000 };+ const key = generateIdempotencyKey('call.received', data, at);+ expect(key).toBe('call_A_CALL1');+ // Retry of the same dispatch regenerates the same key — occurredAt is ignored by design...+ expect(generateIdempotencyKey('call.received', data, '2026-07-20T01:00:00.000Z')).toBe(key);+ // ...while a distinct call (a new occurrence, always a new call id) gets a distinct key.+ expect(generateIdempotencyKey('call.received', { ...data, callId: 'CALL2' }, at)).not.toBe(key);+ // Scoped by session like the message keys: the same call id on another session must not dedupe.+ expect(generateIdempotencyKey('call.received', { ...data, sessionId: 'B' }, at)).not.toBe(key);});it('should generate fallback key for unknown events', () => {diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex 6ee08d9c7..591b1a39d 100644--- a/src/modules/webhook/utils/idempotency.util.ts+++ b/src/modules/webhook/utils/idempotency.util.ts@@ -89,14 +89,28 @@ export function generateIdempotencyKey(event: string, data: Record<string, unknoreturn `disc_${toStr(data.sessionId)}_${hashData({ reason: data.reason })}${occurrence}`;case 'group.join':- return `grp_${toStr(data.groupId)}_${toStr(data.participantId)}_join`;+ // A membership change carries no unique id and repeats with identical content (the same user+ // leaves and rejoins the same group). Key on the affected participants and salt with+ // occurredAt (captured once per dispatch, reused across retries) so a genuine re-join is not+ // deduped onto the earlier delivery.+ return `grp_${toStr(data.groupId)}_${hashData({ participants: data.participantIds })}_join${occurrence}`;case 'group.leave':- return `grp_${toStr(data.groupId)}_${toStr(data.participantId)}_leave`;+ // Same recurring-occurrence treatment as group.join.+ return `grp_${toStr(data.groupId)}_${hashData({ participants: data.participantIds })}_leave${occurrence}`;case 'group.update':- // Include what changed for uniqueness- return `grp_${toStr(data.groupId)}_update_${hashData(data)}`;+ // Key on WHAT changed (a subject set to "X" twice is one logical change; announce toggling+ // back and forth is several), salted per occurrence so identical repeat updates stay distinct.+ // `changes` is pre-stringified: hashData's allowlist replacer only keeps TOP-LEVEL keys, so a+ // nested object would serialize as {} and hash every distinct change identically.+ return `grp_${toStr(data.groupId)}_update_${hashData({ changes: JSON.stringify(data.changes ?? null) })}${occurrence}`;++ case 'call.received':+ // A call id is unique per call, so keying on (session, callId) gives each occurrence a+ // distinct key with no occurredAt salt, while retries of the same dispatch regenerate the+ // same key (same stability contract as the message.* keys). Scoped by sessionId like `msg_`.+ return `call_${toStr(data.sessionId)}_${toStr(data.callId)}`;default:// Fallback: hash entire payload for determinism