Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(channel): transfer channel ownership to another account (Baileys)

Yudhi Armyndharis69f3c12ddeab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2d1110c2..6796fab16 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- `POST /sessions/:sessionId/channels/:channelId/owner/transfer` hands a channel to a new owner on the Baileys engine. It is irreversible: the account stops being the owner and cannot take the channel back. The whatsapp-web.js engine answers `501` — its page function is present but rejects every call locally, against a subscriber list the library has no working path to repopulate, so wiring it would have produced a route that always failed.
- `POST /sessions/:sessionId/channels/:channelId/admins/demote` demotes a channel admin back to a subscriber on the Baileys engine. There is no promote counterpart because neither engine library has one, so an admin is promoted from the WhatsApp app and demoted here. The whatsapp-web.js engine answers `501`: it declares the method, but the WhatsApp Web module its page body calls no longer exports the function, so wiring it would have produced a route that always failed.
- `POST /sessions/:id/chats/pin` pins a chat to the top of the list or unpins it, on both engines; `success: false` reports WhatsApp's three-pin cap, which only the whatsapp-web.js engine can observe.
- `POST /sessions/:id/chats/mute` mutes a chat until an epoch-milliseconds timestamp or unmutes it with an explicit `null`, on both engines; unlike `chats/archive` it has no declined outcome, since the change is not keyed to the chat's last message.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 9c2b36b0f..1f626a156 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3607,6 +3607,37 @@ fails. Rather than ship a route that always errors on that engine, it answers `5
owner, or the user is not an admin · `501` the whatsapp-web.js engine cannot perform this ·
`503` WhatsApp did not answer within the request budget
+#### POST /api/sessions/:sessionId/channels/:channelId/owner/transfer
+
+Hand a channel this account owns to a new owner. **Baileys only** — the whatsapp-web.js engine
+answers `501`.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+> **Irreversible.** Once the transfer lands, this session is no longer the owner and cannot take the
+> channel back through this API.
+
+The upstream option to also dismiss yourself as an admin in the same call is **not exposed**: the
+WhatsApp Web function it depends on no longer exists, and it sits inside a branch that swallows its
+own errors, so it would fail silently instead of refusing.
+
+`whatsapp-web.js` declares `Client.transferChannelOwnership` and its page function is present, but on
+current WhatsApp Web it rejects every call **locally** — measured at 4-9ms against a 352-531ms
+known-server baseline in the same page — against a subscriber list the library has no working path to
+repopulate. Rather than ship a route that always fails on that engine, it answers `501` there.
+
+**Request body** — `TransferChannelOwnershipDto`
+
+| Field | Type | Required | Description |
+| ------------ | ------ | -------- | ------------------------------------------------ |
+| `newOwnerId` | string | Yes | WhatsApp ID of the new owner, e.g. `[email protected]` |
+
+**Response** `200` — `{ "success": true }`
+
+**Errors:** `400` validation, or session not started · `401` · `403` WhatsApp refused the transfer ·
+`501` the whatsapp-web.js engine cannot perform this · `503` WhatsApp did not answer within the
+request budget, and the transfer may or may not have applied
+
#### POST /api/sessions/:sessionId/channels/subscribe
Subscribe to a channel using its invite code.
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 4559d9473..05ab2ff49 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -3,7 +3,7 @@
Three-way comparison of every capability: the **Baileys library** (`@whiskeysockets/baileys`
7.0.0-rc13), the **whatsapp-web.js library** (1.34.7), and what **OpenWA actually exposes** through
its adapter layer and REST API — including which "supported" cells only work because OpenWA patches
-the installed library. Coverage is total: all 111 `IWhatsAppEngine` methods (29.4), **all 152
+the installed library. Coverage is total: all 112 `IWhatsAppEngine` methods (29.4), **all 152
Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all
5 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
@@ -24,7 +24,7 @@ Statuses used in the tables:
Two complementary views:
-- **29.4 — the OpenWA contract view.** Rows are the 111 `IWhatsAppEngine` methods; use it to see
+- **29.4 — the OpenWA contract view.** Rows are the 112 `IWhatsAppEngine` methods; use it to see
what a REST caller gets per engine. Source of truth: `src/engine/engine-capability-matrix.ts`
(per-cell `evidence` strings cite the exact library `file:symbol` inspected).
- **29.5 — the full engine inventory.** Rows are **every method the installed libraries expose**,
@@ -36,14 +36,14 @@ Two complementary views:
## 29.2 Adapter architecture
OpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine
-instance behind the neutral `IWhatsAppEngine` interface (111 methods +
+instance behind the neutral `IWhatsAppEngine` interface (112 methods +
`EngineEventCallbacks`), and all modules go through it:
```mermaid
flowchart LR
subgraph OpenWA["OpenWA"]
API["REST API controllers"] --> SVC["Modules / services"]
- SVC --> IF["IWhatsAppEngine - 111 methods"]
+ SVC --> IF["IWhatsAppEngine - 112 methods"]
IF --> WA["WwebjsAdapter"]
IF --> BA["BaileysAdapter"]
SVC --> STORE["OpenWA-side stores"]
@@ -156,7 +156,7 @@ Rows that are ✅ on **both** engines where one side is patch-dependent: `initia
rests on the column-wide 🔧¹ (wwjs) and 🔧⁵ (baileys) — no row runs on stock library code on both
sides.
-## 29.4 Full capability matrix — the OpenWA contract view (111 methods)
+## 29.4 Full capability matrix — the OpenWA contract view (112 methods)
Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·
**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide
@@ -279,17 +279,18 @@ socket is caught by the transport instead. No REST route: the session watchdog p
### 29.4.7 Channels
-| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ ⁴ | OpenWA REST |
-| ------------------------ | ------------------- | ------------------ | --------------- |
-| `createChannel` | ✅ | ✅ | ✅ |
-| `deleteChannel` | ✅ | ✅ | ✅ |
-| `muteChannel` | ✅ | ✅ | ✅ |
-| `demoteChannelAdmin` | ✅ | ❌ lib | ⚠️ baileys only |
-| `getChannelById` | ✅ | ✅ | ✅ |
-| `getChannelMessages` | ❌ gap | ✅ | ⚠️ wwjs only |
-| `getSubscribedChannels` | ❌ lib | ✅ | ⚠️ wwjs only |
-| `subscribeToChannel` | ✅ | ❌ gap | ⚠️ baileys only |
-| `unsubscribeFromChannel` | ✅ | ✅ | ✅ |
+| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ ⁴ | OpenWA REST |
+| -------------------------- | ------------------- | ------------------ | --------------- |
+| `createChannel` | ✅ | ✅ | ✅ |
+| `deleteChannel` | ✅ | ✅ | ✅ |
+| `muteChannel` | ✅ | ✅ | ✅ |
+| `demoteChannelAdmin` | ✅ | ❌ lib | ⚠️ baileys only |
+| `transferChannelOwnership` | ✅ | ❌ lib | ⚠️ baileys only |
+| `getChannelById` | ✅ | ✅ | ✅ |
+| `getChannelMessages` | ❌ gap | ✅ | ⚠️ wwjs only |
+| `getSubscribedChannels` | ❌ lib | ✅ | ⚠️ wwjs only |
+| `subscribeToChannel` | ✅ | ❌ gap | ⚠️ baileys only |
+| `unsubscribeFromChannel` | ✅ | ✅ | ✅ |
### 29.4.8 Status / stories
@@ -347,9 +348,9 @@ answers 501.
| `rejectCall` | ✅ | ✅ | ✅ |
| `createCallLink` | ✅ | ✅ | ✅ |
-**Totals:** 111 methods → 222 adapter cells: **199 ✅, 23 ❌** (2 adapter-gaps, 21
-library-limitations, 0 uncertain) across 22 methods. From the REST caller's side: **91** methods
-work on any engine (89 fully supported + 2 store-backed status reads), **10** are Baileys-only,
+**Totals:** 112 methods → 224 adapter cells: **200 ✅, 24 ❌** (2 adapter-gaps, 22
+library-limitations, 0 uncertain) across 23 methods. From the REST caller's side: **91** methods
+work on any engine (89 fully supported + 2 store-backed status reads), **11** are Baileys-only,
**9** are wwjs-only (the 2 store-backed rows excluded), **1** (`sendCatalog`) is 501 on both.
## 29.5 Full engine method inventory — every library method, mapped to OpenWA
@@ -459,7 +460,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| Library method | OpenWA exposure |
| ----------------------------- | -------------------------------------------- |
| `newsletterAdminCount` | ❌ **not exposed** |
-| `newsletterChangeOwner` | ❌ **not exposed** |
+| `newsletterChangeOwner` | ✅ `transferChannelOwnership` |
| `newsletterCreate` | ✅ `createChannel` |
| `newsletterDelete` | ✅ `deleteChannel` |
| `newsletterDemote` | ✅ `demoteChannelAdmin` |
@@ -656,7 +657,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| `searchChannels` | ❌ **not exposed** |
| `sendChannelAdminInvite` | ❌ **not exposed** |
| `subscribeToChannel` | ❌ **not exposed** — adapter-gap #2; the delegate throws pending a verified two-step wiring (29.6.2) |
-| `transferChannelOwnership` | ❌ **not exposed** |
+| `transferChannelOwnership` | ❌ **not exposed** — page rejects locally, see 29.4 |
| `unsubscribeFromChannel` | ✅ `unsubscribeFromChannel` |
**Labels** (5)
@@ -724,9 +725,8 @@ The highest-value backlog: capabilities with first-class symbols on **both** eng
new `IWhatsAppEngine` method wires both adapters at once. All cross-checked against the installed
`.d.ts` files.
-| Capability | Baileys symbol | wwjs symbol | Note |
-| -------------------------- | ----------------------------------------------------- | -------------------------- | ---- |
-| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |
+| Capability | Baileys symbol | wwjs symbol | Note |
+| ---------- | -------------- | ----------- | ---- |
Near-misses (both libraries have the area, but the symbol sets only partially overlap — still
worth an interface method): **channel admin invites** (wwjs
@@ -783,7 +783,7 @@ OpenWA consumes events by normalizing them into `EngineEventCallbacks`; anything
| `group_leave` | ✅ | | `group_update` | ✅ |
| `group_membership_request` | ✅ | | | |
-## 29.6 The 23 not-available cells in detail
+## 29.6 The 24 not-available cells in detail
Every ❌ in 29.4, with the exact library symbol inspected (full evidence strings:
`engine-capability-matrix.ts`). All of these throw `EngineNotSupportedError` → HTTP 501 at the
@@ -806,21 +806,22 @@ adapter boundary — none silently stubs.
| `sendCatalog` | lib | `AnyMessageContent` (`Types/Message.d.ts:166-210`) has only `{product}` (single product); the catalog CRUD nodes (`Socket/business.js:294-362`) mutate the catalog, they don't send it. |
| `votePoll` | lib | No vote-send helper at all; the library only _decrypts incoming_ votes (`decryptPollVote`). Sending needs a hand-built `proto.Message.PollUpdateMessage` with HMAC-SHA256 encryption keyed by the poll creation's `messageSecret`. |
-### 29.6.2 wwjs adapter (11 cells)
-
-| Method | Cause | What's missing (evidence) |
-| --------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `subscribeToChannel` | gap | `Client.subscribeToChannel(channelId)` (`Client.js:2542`) takes a channel **id** and resolves a boolean — it cannot satisfy the subscribe-by-invite-code contract alone. Correct wiring is two-step: `getChannelByInviteCode(inviteCode)` (`Client.js:1716`) → `subscribeToChannel(channel.id)`, unverified against a live session (the previous one-step call was a phantom success). The one remaining wwjs adapter-gap. |
-| `demoteChannelAdmin` | lib | `Client.demoteChannelAdmin` exists (`index.d.ts:35`) but its page body calls `window.require('WAWebDemoteNewsletterAdminAction').demoteNewsletterAdmin` (`Client.js:1907-1925`), and a module probe on a live session (Web `2.3000.1044824727-alpha`, unpinned) returned that module resolving with `demoteNewsletterAdmin: undefined`. The sibling path used inside `transferChannelOwnership` (`WAWebNewsletterDemoteAdminJob.demoteNewsletterAdminAction`) is undefined too, so there is nothing to retarget. Baileys serves this capability. |
-| `upsertLabel` | lib | 1.34.7 reads labels and assigns them (`getLabels`, `getLabelById`, `getChatLabels`, `getChatsByLabelId`, `addOrRemoveLabels`, `index.d.ts:129-154`) but exposes nothing that creates/edits a label definition. |
-| `deleteLabel` | lib | Same as above. |
-| `subscribeToPresence` | lib | Only `sendPresenceAvailable`/`sendPresenceUnavailable` (`index.d.ts:230,233`), which publish the _account's own_ presence; no subscribe call and no presence event is emitted. |
-| `getCatalog` | lib | No `Client.getCatalog` in `index.d.ts` (0 hits); `Product`/`Order` are inbound-only parsers. |
-| `getProducts` | lib | Same as above. |
-| `getProduct` | lib | Only page-internal `getProductMetadata` (`Utils.js:1290`), not a public Client fn. |
-| `sendProduct` | lib | No outbound product content type. |
-| `sendCatalog` | lib | No `Client.sendCatalog` in `index.d.ts` (0 hits). |
-| `setGroupEphemeral` | lib | No disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); only the create-time `messageTimer` option (`Client.js:2328`). |
+### 29.6.2 wwjs adapter (12 cells)
+
+| Method | Cause | What's missing (evidence) |
+| -------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `subscribeToChannel` | gap | `Client.subscribeToChannel(channelId)` (`Client.js:2542`) takes a channel **id** and resolves a boolean — it cannot satisfy the subscribe-by-invite-code contract alone. Correct wiring is two-step: `getChannelByInviteCode(inviteCode)` (`Client.js:1716`) → `subscribeToChannel(channel.id)`, unverified against a live session (the previous one-step call was a phantom success). The one remaining wwjs adapter-gap. |
+| `demoteChannelAdmin` | lib | `Client.demoteChannelAdmin` exists (`index.d.ts:35`) but its page body calls `window.require('WAWebDemoteNewsletterAdminAction').demoteNewsletterAdmin` (`Client.js:1907-1925`), and a module probe on a live session (Web `2.3000.1044824727-alpha`, unpinned) returned that module resolving with `demoteNewsletterAdmin: undefined`. The sibling path used inside `transferChannelOwnership` (`WAWebNewsletterDemoteAdminJob.demoteNewsletterAdminAction`) is undefined too, so there is nothing to retarget. Baileys serves this capability. |
+| `transferChannelOwnership` | lib | `Client.transferChannelOwnership` exists (`index.d.ts:375`) and its page function `WAWebChangeNewsletterOwnerAction.changeNewsletterOwnerAction` is present, but on Web `2.3000.1044824727-alpha` it rejects every call **locally** with `contact-not-found-in-newsletter-subscriber-list` — 4-9ms against a 352-531ms known-server baseline measured in the same page, so it never reaches WhatsApp. Unchanged by subscribing the target, promoting it to admin, or restarting the session; the only repopulation path, `WAWebCollections.NewsletterMetadataCollection.update`, is `undefined`. Baileys serves this capability. |
+| `upsertLabel` | lib | 1.34.7 reads labels and assigns them (`getLabels`, `getLabelById`, `getChatLabels`, `getChatsByLabelId`, `addOrRemoveLabels`, `index.d.ts:129-154`) but exposes nothing that creates/edits a label definition. |
+| `deleteLabel` | lib | Same as above. |
+| `subscribeToPresence` | lib | Only `sendPresenceAvailable`/`sendPresenceUnavailable` (`index.d.ts:230,233`), which publish the _account's own_ presence; no subscribe call and no presence event is emitted. |
+| `getCatalog` | lib | No `Client.getCatalog` in `index.d.ts` (0 hits); `Product`/`Order` are inbound-only parsers. |
+| `getProducts` | lib | Same as above. |
+| `getProduct` | lib | Only page-internal `getProductMetadata` (`Utils.js:1290`), not a public Client fn. |
+| `sendProduct` | lib | No outbound product content type. |
+| `sendCatalog` | lib | No `Client.sendCatalog` in `index.d.ts` (0 hits). |
+| `setGroupEphemeral` | lib | No disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); only the create-time `messageTimer` option (`Client.js:2328`). |
## 29.7 Caveats on supported rows
@@ -877,24 +878,28 @@ adapter boundary — none silently stubs.
Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of the
adapter sources — re-derive the same way when anything changes:
-- **111** interface methods → **222** adapter cells: **199 ✅** / **23 ❌** (2 adapter-gaps, 21
- library-limitations, 0 uncertain), spanning **22** methods.
-- Of the 199 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
+- **112** interface methods → **224** adapter cells: **200 ✅** / **24 ❌** (2 adapter-gaps, 22
+ library-limitations, 0 uncertain), spanning **23** methods.
+- Of the 200 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync) and the whole wwjs column additionally
depends on 🔧¹, the whole Baileys column on 🔧⁵ — so every row rests on a patch on each side,
even though no row carries a row-level mark on both.
-- REST caller's view: **91** engine-neutral (89 + 2 store-backed status reads), **10** Baileys-only,
+- REST caller's view: **91** engine-neutral (89 + 2 store-backed status reads), **11** Baileys-only,
**9** wwjs-only, **1** unavailable on both (`sendCatalog`).
- Full engine inventory (29.5), split by the exposure legend rather than lumped: Baileys **152**
- socket methods — 48 wired into interface methods, 5 internal wiring, 29 plumbing, **70 ❌ not
+ socket methods — 49 wired into interface methods, 5 internal wiring, 29 plumbing, **69 ❌ not
exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 47 wired,
2 internal wiring, 1 class plumbing, **31 ❌ not exposed** (23 real capabilities + 8
session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minus
those 8 settings; 🔩 plumbing is correctly never exposed.
- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).
-- **1** capability is supported by **both** libraries and missing only in OpenWA (29.5.3): channel
- ownership transfer. (Five of the original six are now wired — see `muteChat`, `pinChat`,
- `createCallLink`, `deleteProfilePicture` and `demoteChannelAdmin`.)
+- **0** capabilities remain in 29.5.3: every capability with first-class symbols on both libraries
+ is now either wired or classified with evidence. The six that opened this backlog were `muteChat`,
+ `pinChat`, `createCallLink`, `deleteProfilePicture`, `demoteChannelAdmin` and
+ `transferChannelOwnership`. **Two of the six do not work on whatsapp-web.js and only a live session
+ showed it** — `demoteChannelAdmin`'s page function is gone, and `transferChannelOwnership`'s page
+ function rejects locally against a list it cannot repopulate (both in 29.6.2). Both are Baileys-only
+ and both are 501 on wwjs. `.d.ts` presence is not capability.
- **5** install-time patches (4 whatsapp-web.js + 1 Baileys), all exact and self-disabling.
- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.
- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —
diff --git a/openapi.json b/openapi.json
index baf8aabce..4fc0ea237 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6941,6 +6941,73 @@
]
}
},
+ "/api/sessions/{sessionId}/channels/{channelId}/owner/transfer": {
+ "post": {
+ "description": "IRREVERSIBLE. Once the transfer lands, this session is no longer the owner and cannot take the channel back through this API. Requires this account to currently own the channel. The upstream option to also dismiss yourself as an admin in the same call is not exposed, because the WhatsApp Web function it depends on no longer exists and the branch swallows its own errors, so it would fail silently.",
+ "operationId": "ChannelController_transferOwnership",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "channelId",
+ "required": true,
+ "in": "path",
+ "description": "Channel ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TransferChannelOwnershipDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Ownership transferred",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChannelAckResponseDto"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Session not started, or validation failed"
+ },
+ "403": {
+ "description": "The engine did not transfer the channel. On whatsapp-web.js this is the only outcome a failure can produce: the page swallows every error into a plain false, so the cause is not reported."
+ },
+ "409": {
+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."
+ },
+ "501": {
+ "description": "The whatsapp-web.js engine cannot perform this: its page function rejects every call locally against a subscriber list the page cannot repopulate. Use the Baileys engine."
+ },
+ "503": {
+ "description": "WhatsApp did not answer within the request budget — the transfer may or may not have applied."
+ }
+ },
+ "summary": "Transfer channel ownership to another account",
+ "tags": [
+ "channels"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/channels/subscribe": {
"post": {
"operationId": "ChannelController_subscribe",
@@ -13670,6 +13737,19 @@
"userId"
]
},
+ "TransferChannelOwnershipDto": {
+ "type": "object",
+ "properties": {
+ "newOwnerId": {
+ "type": "string",
+ "description": "WhatsApp ID of the account that becomes the new owner. This is irreversible: once the transfer lands, this session can no longer take the channel back.",
+ "example": "[email protected]"
+ }
+ },
+ "required": [
+ "newOwnerId"
+ ]
+ },
"OverviewSessionsDto": {
"type": "object",
"properties": {
diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.ts
index 3f999545a..0b95ff9f5 100644
--- a/src/engine/adapters/baileys-channels.ts
+++ b/src/engine/adapters/baileys-channels.ts
@@ -116,6 +116,25 @@ export class BaileysChannels {
);
}
+ /**
+ * Hand the channel to a new owner. IRREVERSIBLE: the account stops being the owner and cannot
+ * take it back through this API.
+ *
+ * Bounded, unlike `createChannel` above. That one stays unbounded because a retried create leaves
+ * a duplicate channel behind; here a retry after a transfer that actually landed is refused, since
+ * the account no longer owns the channel. So the deadline costs an ambiguous 503 ("may or may not
+ * have applied") and buys a request that ends.
+ */
+ async transferChannelOwnership(channelId: string, newOwnerId: string): Promise<void> {
+ this.host.ensureReady();
+ const newOwnerJid = this.host.toEngineJid(newOwnerId);
+ await mapServerRefusal(
+ 'Transferring the channel ownership',
+ () => this.bounded(this.sock().newsletterChangeOwner(channelId, newOwnerJid), 'the channel ownership transfer'),
+ wmexRefusalCode,
+ );
+ }
+
async deleteChannel(channelId: string): Promise<void> {
this.host.ensureReady();
await mapServerRefusal(
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 11cb286df..6cc88dd7d 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -691,6 +691,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.channels.demoteChannelAdmin(channelId, userId);
}
+ transferChannelOwnership(channelId: string, newOwnerId: string): Promise<void> {
+ return this.channels.transferChannelOwnership(channelId, newOwnerId);
+ }
+
getSubscribedChannels(): Promise<Channel[]> {
return this.unsupported('getSubscribedChannels');
}
diff --git a/src/engine/adapters/channel-ownership-transfer.spec.ts b/src/engine/adapters/channel-ownership-transfer.spec.ts
new file mode 100644
index 000000000..c9834232a
--- /dev/null
+++ b/src/engine/adapters/channel-ownership-transfer.spec.ts
@@ -0,0 +1,108 @@
+import { Boom } from '@hapi/boom';
+import type { Client } from 'whatsapp-web.js';
+import type { WASocket } from '@whiskeysockets/baileys';
+import { BaileysChannels, type BaileysChannelsHost } from './baileys-channels';
+import { WwebjsChannels } from './wwebjs-channels';
+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
+import { EngineRefusedError } from '../../common/errors/engine-refused.error';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+
+/**
+ * Hand a channel to a new owner — the last of the 29.5.3 backlog, and the only irreversible one.
+ * Once it lands the account is no longer the owner and cannot take the channel back.
+ *
+ * **Only Baileys can deliver it.** `Client.transferChannelOwnership` exists and its page function is
+ * present, but on Web `2.3000.1044824727-alpha` it rejects every call LOCALLY with
+ * `contact-not-found-in-newsletter-subscriber-list` — 4-9ms against a 352-531ms known-server
+ * baseline taken in the same page, so it never asks WhatsApp. Subscribing the target, promoting it
+ * to admin, and restarting the session all left it unchanged, and the only list-repopulation path
+ * (`NewsletterMetadataCollection.update`) is `undefined` in this Web version. The library discards
+ * that reason into a bare `false`, so the wwjs adapter answers 501 instead of claiming support.
+ *
+ * **`shouldDismissSelfAsAdmin` is deliberately not exposed.** That branch calls
+ * `window.require('WAWebContactCollection').getMeContact()`, and a module probe against a live
+ * session on Web `2.3000.1044824727-alpha` returned `getMeContact: undefined`. Since the branch sits
+ * inside the same swallowing try, passing the option would throw, be caught, and surface as a plain
+ * `false` — a silent failure dressed as a refusal. Not offering it beats offering one that lies.
+ *
+ * Baileys resolves `void` through `executeWMexQuery`, so a refusal is a Boom on the w:mex channel.
+ * Unlike `createChannel` this call IS bounded: a retry after a transfer that actually succeeded is
+ * refused (the account no longer owns the channel), whereas a retried create leaves a duplicate
+ * channel behind — so the argument that keeps `createChannel` unbounded does not apply here, and a
+ * `503` saying "may or may not have applied" beats a request that hangs.
+ */
+
+const logger = createLogger('channel-ownership-transfer.spec');
+const CHANNEL = '120363000000000000@newsletter';
+const NEW_OWNER = '[email protected]';
+const never = (): Promise<never> => new Promise<never>(() => undefined);
+
+function wwebjs(client: Record<string, jest.Mock>): WwebjsChannels {
+ const host = {
+ ensureReady: jest.fn(),
+ getClient: () => client as unknown as Client,
+ logger,
+ } as unknown as WwebjsEngineHost;
+ return new WwebjsChannels(host);
+}
+
+function baileys(sock: Record<string, jest.Mock>, budgetMs = 500): BaileysChannels {
+ const host = {
+ ensureReady: () => undefined,
+ getSocket: () => sock as unknown as WASocket,
+ toEngineJid: (jid: string) => jid.replace('@c.us', '@s.whatsapp.net'),
+ } as unknown as BaileysChannelsHost;
+ return new BaileysChannels(host, budgetMs);
+}
+
+describe('WwebjsChannels.transferChannelOwnership', () => {
+ it('answers 501 rather than calling a library method the page refuses locally', async () => {
+ const transferChannelOwnership = jest.fn();
+ await expect(
+ wwebjs({ transferChannelOwnership }).transferChannelOwnership(CHANNEL, NEW_OWNER),
+ ).rejects.toBeInstanceOf(EngineNotSupportedError);
+ });
+
+ // Wiring it would be a phantom-support row. The page rejects every call in 4-9ms with
+ // `contact-not-found-in-newsletter-subscriber-list` — measured against a 352-531ms known-server
+ // baseline in the same page, so it never reaches WhatsApp — and the library then discards that
+ // reason into a bare `false`.
+ it('does not reach the library at all, so a caller gets a verdict instead of a silent false', async () => {
+ const transferChannelOwnership = jest.fn();
+ await expect(wwebjs({ transferChannelOwnership }).transferChannelOwnership(CHANNEL, NEW_OWNER)).rejects.toThrow();
+ expect(transferChannelOwnership).not.toHaveBeenCalled();
+ });
+});
+
+describe('BaileysChannels.transferChannelOwnership', () => {
+ it('maps the new owner to the engine dialect and leaves the channel id alone', async () => {
+ const newsletterChangeOwner = jest.fn().mockResolvedValue(undefined);
+ await expect(
+ baileys({ newsletterChangeOwner }).transferChannelOwnership(CHANNEL, NEW_OWNER),
+ ).resolves.toBeUndefined();
+ expect(newsletterChangeOwner).toHaveBeenCalledWith(CHANNEL, '[email protected]');
+ });
+
+ // executeWMexQuery throws `Boom(msg, { statusCode: errorCode, data: firstError })` with the GraphQL
+ // error NODE as `data` — an object. A numeric `data` is the IQ channel's shape and would exercise a
+ // branch of wmexRefusalCode this path cannot reach.
+ it('maps a w:mex refusal to a refusal', async () => {
+ const newsletterChangeOwner = jest.fn().mockRejectedValue(
+ new Boom('GraphQL server error: not-authorized', {
+ statusCode: 403,
+ data: { message: 'not-authorized', error_code: 403 },
+ }),
+ );
+ await expect(
+ baileys({ newsletterChangeOwner }).transferChannelOwnership(CHANNEL, NEW_OWNER),
+ ).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
+ it('reports an unanswered query instead of a bare 500', async () => {
+ await expect(
+ baileys({ newsletterChangeOwner: jest.fn(never) }, 15).transferChannelOwnership(CHANNEL, NEW_OWNER),
+ ).rejects.toBeInstanceOf(EngineTransportError);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 49efc66cc..43c95cb33 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -871,6 +871,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.channels.demoteChannelAdmin(channelId, userId);
}
+ transferChannelOwnership(channelId: string, newOwnerId: string): Promise<void> {
+ return this.channels.transferChannelOwnership(channelId, newOwnerId);
+ }
+
getChatsByLabel(labelId: string): Promise<ChatSummary[]> {
return this.labels.getChatsByLabel(labelId);
}
diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.ts
index 021d66ef9..c7e9b5c4a 100644
--- a/src/engine/adapters/wwebjs-channels.ts
+++ b/src/engine/adapters/wwebjs-channels.ts
@@ -99,6 +99,34 @@ export class WwebjsChannels {
throw new EngineNotSupportedError('demoteChannelAdmin');
}
+ /**
+ * Not available on this engine, despite `Client.transferChannelOwnership` existing and being typed
+ * `Promise<boolean>` (`index.d.ts:375`).
+ *
+ * `WAWebChangeNewsletterOwnerAction.changeNewsletterOwnerAction` is present — unlike the demote
+ * path — but on WhatsApp Web `2.3000.1044824727-alpha` it rejects every call with
+ * `contact-not-found-in-newsletter-subscriber-list` **without contacting the server**. Measured in
+ * the page against a known-server call taken at the same moment: the transfer threw in **4-9ms**
+ * while `requestProfilePicFromServer` on the same chat took **352-531ms**. So it is a local check
+ * against a subscriber list the page holds, not a WhatsApp business rule we could satisfy.
+ *
+ * It is not a stale cache either: the target had subscribed (`subscribeToChannel` → 201), the
+ * operator could promote it to admin from the app, and a full session restart — a fresh page, a
+ * fresh cache — produced the identical 4ms refusal. The one path that could repopulate that list,
+ * `WAWebCollections.NewsletterMetadataCollection.update`, is `undefined` in this Web version, and
+ * it is the same line `Client.transferChannelOwnership` itself calls when a channel has no cached
+ * metadata — so an uncached channel throws there before the transfer is even attempted.
+ *
+ * Wiring it would be a phantom-support row: a claimed capability whose every call fails, locally,
+ * with a reason the library then discards into a bare `false`. A 501 states the truth. Baileys
+ * serves this capability — its refusal is a genuine server round trip (418ms, WhatsApp code named).
+ */
+ /* eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */
+ async transferChannelOwnership(_channelId: string, _newOwnerId: string): Promise<void> {
+ this.host.ensureReady();
+ throw new EngineNotSupportedError('transferChannelOwnership');
+ }
+
/** Delete a channel. `false` means the channel was not found or the server refused. */
async deleteChannel(channelId: string): Promise<void> {
this.host.ensureReady();
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index b74418dfa..5d578ee12 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -147,6 +147,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
createChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
muteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ transferChannelOwnership: {
+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'baileys newsletterChangeOwner(jid, newOwnerJid) → void via executeWMexQuery QueryIds.CHANGE_OWNER (Socket/newsletter.d.ts:24; newsletter.js:170-172) — refusal verified live as a server round trip (418ms, WhatsApp code named). wwjs Client.transferChannelOwnership exists and is typed Promise<boolean> (index.d.ts:375), and its page function WAWebChangeNewsletterOwnerAction.changeNewsletterOwnerAction is present, but on Web 2.3000.1044824727-alpha it rejects LOCALLY with contact-not-found-in-newsletter-subscriber-list: 4-9ms against a 352-531ms known-server baseline taken in the same page, unchanged by subscribing the target, promoting it to admin, or restarting the session. WAWebCollections.NewsletterMetadataCollection.update — the only repopulation path, and the line transferChannelOwnership itself calls for an uncached channel — is undefined',
+ },
demoteChannelAdmin: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
baileys: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index c99fece4a..e94a1097b 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1072,6 +1072,15 @@ export interface IWhatsAppEngine {
* the WhatsApp app and can then be demoted here.
*/
demoteChannelAdmin(channelId: string, userId: string): Promise<void>;
+ /**
+ * Hand a channel this account owns to a new owner. **Irreversible** — the account stops being the
+ * owner and cannot take it back through this API.
+ *
+ * The whatsapp-web.js option to also dismiss yourself as admin in the same call is not exposed:
+ * the page function it relies on no longer exists, and it sits inside a branch that swallows its
+ * own errors, so it would fail silently rather than refusing.
+ */
+ transferChannelOwnership(channelId: string, newOwnerId: string): Promise<void>;
upsertLabel(label: LabelInput): Promise<void>;
/** Delete a label. It disappears from every chat it was on. */
deleteLabel(labelId: string): Promise<void>;
diff --git a/src/modules/channel/channel.controller.spec.ts b/src/modules/channel/channel.controller.spec.ts
index 6366e72fb..8b6131789 100644
--- a/src/modules/channel/channel.controller.spec.ts
+++ b/src/modules/channel/channel.controller.spec.ts
@@ -45,3 +45,24 @@ describe('ChannelController.demoteAdmin', () => {
await expect(controller.demoteAdmin('s1', 'ch1@newsletter', { userId: '[email protected]' })).rejects.toThrow('refused');
});
});
+
+describe('ChannelController.transferOwnership', () => {
+ it('forwards the path params and the body field in the right order', async () => {
+ // sessionId, channelId and newOwnerId are all strings, so a swap compiles and type-checks —
+ // and this operation is irreversible, which makes the wrong target unrecoverable.
+ const service = { transferChannelOwnership: jest.fn().mockResolvedValue(undefined) };
+ const controller = new ChannelController(service as unknown as ChannelService);
+ await expect(controller.transferOwnership('s1', 'ch1@newsletter', { newOwnerId: '[email protected]' })).resolves.toEqual({
+ success: true,
+ });
+ expect(service.transferChannelOwnership).toHaveBeenCalledWith('s1', 'ch1@newsletter', '[email protected]');
+ });
+
+ it('lets an engine refusal propagate instead of answering success', async () => {
+ const service = { transferChannelOwnership: jest.fn().mockRejectedValue(new Error('refused')) };
+ const controller = new ChannelController(service as unknown as ChannelService);
+ await expect(controller.transferOwnership('s1', 'ch1@newsletter', { newOwnerId: '[email protected]' })).rejects.toThrow(
+ 'refused',
+ );
+ });
+});
diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.ts
index 282dd0454..7c841a36a 100644
--- a/src/modules/channel/channel.controller.ts
+++ b/src/modules/channel/channel.controller.ts
@@ -6,6 +6,7 @@ import { SubscribeChannelDto } from './dto/subscribe-channel.dto';
import { CreateChannelDto } from './dto/create-channel.dto';
import { MuteChannelDto } from './dto/mute-channel.dto';
import { DemoteChannelAdminDto } from './dto/demote-channel-admin.dto';
+import { TransferChannelOwnershipDto } from './dto/transfer-channel-ownership.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
import {
@@ -187,6 +188,50 @@ export class ChannelController {
return { success: true };
}
+ @Post(':channelId/owner/transfer')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @HttpCode(HttpStatus.OK)
+ @ApiOperation({
+ summary: 'Transfer channel ownership to another account',
+ description:
+ 'IRREVERSIBLE. Once the transfer lands, this session is no longer the owner and cannot take ' +
+ 'the channel back through this API. Requires this account to currently own the channel. The ' +
+ 'upstream option to also dismiss yourself as an admin in the same call is not exposed, ' +
+ 'because the WhatsApp Web function it depends on no longer exists and the branch swallows ' +
+ 'its own errors, so it would fail silently.',
+ })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiParam({ name: 'channelId', description: 'Channel ID' })
+ @ApiBody({ type: TransferChannelOwnershipDto })
+ @ApiResponse({ status: 200, description: 'Ownership transferred', type: ChannelAckResponseDto })
+ @ApiResponse({
+ status: 503,
+ description: 'WhatsApp did not answer within the request budget — the transfer may or may not have applied.',
+ })
+ @ApiResponse({ status: 400, description: 'Session not started, or validation failed' })
+ @ApiResponse({
+ status: 403,
+ description:
+ 'The engine did not transfer the channel. On whatsapp-web.js this is the only outcome a ' +
+ 'failure can produce: the page swallows every error into a plain false, so the cause is not ' +
+ 'reported.',
+ })
+ @ApiResponse({
+ status: 501,
+ description:
+ 'The whatsapp-web.js engine cannot perform this: its page function rejects every call locally ' +
+ 'against a subscriber list the page cannot repopulate. Use the Baileys engine.',
+ })
+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
+ async transferOwnership(
+ @Param('sessionId') sessionId: string,
+ @Param('channelId') channelId: string,
+ @Body() dto: TransferChannelOwnershipDto,
+ ): Promise<{ success: boolean }> {
+ await this.channelService.transferChannelOwnership(sessionId, channelId, dto.newOwnerId);
+ return { success: true };
+ }
+
@Post('subscribe')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Subscribe to a channel using invite code' })
diff --git a/src/modules/channel/channel.service.spec.ts b/src/modules/channel/channel.service.spec.ts
index d5916153a..7121bea32 100644
--- a/src/modules/channel/channel.service.spec.ts
+++ b/src/modules/channel/channel.service.spec.ts
@@ -55,4 +55,16 @@ describe('ChannelService', () => {
BadRequestException,
);
});
+
+ it('transferChannelOwnership forwards the channel and new owner, dropping the sessionId', async () => {
+ const transferChannelOwnership = jest.fn().mockResolvedValue(undefined);
+ await makeService({ transferChannelOwnership }).transferChannelOwnership('s1', 'ch1@newsletter', '[email protected]');
+ expect(transferChannelOwnership).toHaveBeenCalledWith('ch1@newsletter', '[email protected]');
+ });
+
+ it('transferChannelOwnership throws 400 when the session is not started', () => {
+ expect(() => makeService(undefined).transferChannelOwnership('s1', 'ch1@newsletter', '[email protected]')).toThrow(
+ BadRequestException,
+ );
+ });
});
diff --git a/src/modules/channel/channel.service.ts b/src/modules/channel/channel.service.ts
index 7e66d1138..75ae179e5 100644
--- a/src/modules/channel/channel.service.ts
+++ b/src/modules/channel/channel.service.ts
@@ -61,6 +61,11 @@ export class ChannelService {
return this.getEngine(sessionId).demoteChannelAdmin(channelId, userId);
}
+ /** Hand the channel to a new owner. Irreversible — the account stops being the owner. */
+ transferChannelOwnership(sessionId: string, channelId: string, newOwnerId: string) {
+ return this.getEngine(sessionId).transferChannelOwnership(channelId, newOwnerId);
+ }
+
subscribeToChannel(sessionId: string, inviteCode: string) {
return this.getEngine(sessionId).subscribeToChannel(inviteCode);
}
diff --git a/src/modules/channel/dto/transfer-channel-ownership.dto.ts b/src/modules/channel/dto/transfer-channel-ownership.dto.ts
new file mode 100644
index 000000000..7ed382e85
--- /dev/null
+++ b/src/modules/channel/dto/transfer-channel-ownership.dto.ts
@@ -0,0 +1,14 @@
+import { ApiProperty } from '@nestjs/swagger';
+import { IsNotEmpty, IsString } from 'class-validator';
+
+export class TransferChannelOwnershipDto {
+ @ApiProperty({
+ description:
+ 'WhatsApp ID of the account that becomes the new owner. This is irreversible: once the ' +
+ 'transfer lands, this session can no longer take the channel back.',
+ example: '[email protected]',
+ })
+ @IsString()
+ @IsNotEmpty()
+ newOwnerId!: string;
+}