Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(channel): demote a channel admin back to a subscriber (Baileys)
Yudhi Armyndharis7f018fc5072d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54d11a51b..b2d1110c2 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/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.- `engine-inventory-parity.spec.ts` fails when a `docs/29` exposure or event mark no longer matches the adapters: a symbol marked as used must appear in adapter code rather than only in a comment, and an event marked consumed must have a listener behind it.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 29d4a702f..9c2b36b0f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3580,6 +3580,33 @@ soft unsubscribe.**Errors:** `400` validation, or session not started · `401` · `403` · `422` the engine refused+#### POST /api/sessions/:sessionId/channels/:channelId/admins/demote++Demote a channel admin back to a plain subscriber. **Baileys only** — the whatsapp-web.js engine+answers `501`.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped++Requires this account to own the channel. There is **no promote counterpart**, and that is an+upstream limit rather than a gap here: neither engine library exposes one, so an admin is promoted+from the WhatsApp app and can then be demoted through this endpoint.++`whatsapp-web.js` declares `Client.demoteChannelAdmin`, but its page body calls a WhatsApp Web+module (`WAWebDemoteNewsletterAdminAction`) that no longer exports the function, so every call+fails. Rather than ship a route that always errors on that engine, it answers `501` there.++**Request body** — `DemoteChannelAdminDto`++| Field | Type | Required | Description |+| -------- | ------ | -------- | -------------------------------------------- |+| `userId` | string | Yes | WhatsApp ID of the admin, e.g. `[email protected]` |++**Response** `200` — `{ "success": true }`++**Errors:** `400` validation, or session not started · `401` · `403` the engine refused — not the+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/subscribeSubscribe to a channel using its invite code.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 73cbece5a..4559d9473 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** throughits adapter layer and REST API — including which "supported" cells only work because OpenWA patches-the installed library. Coverage is total: all 110 `IWhatsAppEngine` methods (29.4), **all 152+the installed library. Coverage is total: all 111 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all5 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 110 `IWhatsAppEngine` methods; use it to see+- **29.4 — the OpenWA contract view.** Rows are the 111 `IWhatsAppEngine` methods; use it to seewhat 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 architectureOpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine-instance behind the neutral `IWhatsAppEngine` interface (110 methods ++instance behind the neutral `IWhatsAppEngine` interface (111 methods +`EngineEventCallbacks`), and all modules go through it:```mermaidflowchart LRsubgraph OpenWA["OpenWA"]API["REST API controllers"] --> SVC["Modules / services"]- SVC --> IF["IWhatsAppEngine - 110 methods"]+ SVC --> IF["IWhatsAppEngine - 111 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: `initiarests on the column-wide 🔧¹ (wwjs) and 🔧⁵ (baileys) — no row runs on stock library code on bothsides.-## 29.4 Full capability matrix — the OpenWA contract view (110 methods)+## 29.4 Full capability matrix — the OpenWA contract view (111 methods)Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide@@ -284,6 +284,7 @@ socket is caught by the transport instead. No REST route: the session watchdog p| `createChannel` | ✅ | ✅ | ✅ || `deleteChannel` | ✅ | ✅ | ✅ || `muteChannel` | ✅ | ✅ | ✅ |+| `demoteChannelAdmin` | ✅ | ❌ lib | ⚠️ baileys only || `getChannelById` | ✅ | ✅ | ✅ || `getChannelMessages` | ❌ gap | ✅ | ⚠️ wwjs only || `getSubscribedChannels` | ❌ lib | ✅ | ⚠️ wwjs only |@@ -346,9 +347,9 @@ answers 501.| `rejectCall` | ✅ | ✅ | ✅ || `createCallLink` | ✅ | ✅ | ✅ |-**Totals:** 110 methods → 220 adapter cells: **198 ✅, 22 ❌** (2 adapter-gaps, 20-library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **91** methods-work on any engine (89 fully supported + 2 store-backed status reads), **9** are Baileys-only,+**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,**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@@ -461,7 +462,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| `newsletterChangeOwner` | ❌ **not exposed** || `newsletterCreate` | ✅ `createChannel` || `newsletterDelete` | ✅ `deleteChannel` |-| `newsletterDemote` | ❌ **not exposed** |+| `newsletterDemote` | ✅ `demoteChannelAdmin` || `newsletterFetchMessages` | ❌ **not exposed** — adapter-gap #1 (29.6.1) || `newsletterFollow` | ✅ `subscribeToChannel` || `newsletterMetadata` | ✅ `getChannelById`, `subscribeToChannel` |@@ -648,7 +649,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| `acceptChannelAdminInvite` | ❌ **not exposed** || `createChannel` | ✅ `createChannel` || `deleteChannel` | ✅ `deleteChannel`, `deleteChat` |-| `demoteChannelAdmin` | ❌ **not exposed** |+| `demoteChannelAdmin` | ❌ **not exposed** — page function gone, see 29.4 || `getChannelByInviteCode` | ❌ **not exposed** — the invite→channel bridge adapter-gap #2 needs (29.6.2) || `getChannels` | ✅ `getSubscribedChannels`, `getChannelMessages` || `revokeChannelAdminInvite` | ❌ **not exposed** |@@ -723,10 +724,9 @@ The highest-value backlog: capabilities with first-class symbols on **both** engnew `IWhatsAppEngine` method wires both adapters at once. All cross-checked against the installed`.d.ts` files.-| Capability | Baileys symbol | wwjs symbol | Note |-| -------------------------- | ----------------------------------------------------- | -------------------------- | ------------------------------------------- |-| Channel admin demote | `newsletterDemote` (`Socket/newsletter.d.ts:25`) | `demoteChannelAdmin` | pair with the ❌-exposed invite flows below |-| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |+| Capability | Baileys symbol | wwjs symbol | Note |+| -------------------------- | ----------------------------------------------------- | -------------------------- | ---- |+| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |Near-misses (both libraries have the area, but the symbol sets only partially overlap — stillworth 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 22 not-available cells in detail+## 29.6 The 23 not-available cells in detailEvery ❌ 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,20 +806,21 @@ 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 (10 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. |-| `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 (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.7 Caveats on supported rows@@ -876,24 +877,24 @@ adapter boundary — none silently stubs.Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of theadapter sources — re-derive the same way when anything changes:-- **110** interface methods → **220** adapter cells: **198 ✅** / **22 ❌** (2 adapter-gaps, 20- library-limitations, 0 uncertain), spanning **21** methods.-- Of the 198 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,+- **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,1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync) and the whole wwjs column additionallydepends 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), **9** Baileys-only,+- REST caller's view: **91** engine-neutral (89 + 2 store-backed status reads), **10** 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 — 47 wired into interface methods, 5 internal wiring, 29 plumbing, **71 ❌ not+ socket methods — 48 wired into interface methods, 5 internal wiring, 29 plumbing, **70 ❌ notexposed** (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 + 8session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minusthose 8 settings; 🔩 plumbing is correctly never exposed.- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).-- **2** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the- cheapest backlog: channel admin demote, channel ownership transfer. (Four of the original six are- now wired — see `muteChat`, `pinChat`, `createCallLink` and `deleteProfilePicture`.)+- **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`.)- **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.jsonindex 0be438f06..baf8aabce 100644--- a/openapi.json+++ b/openapi.json@@ -6874,6 +6874,73 @@]}},+ "/api/sessions/{sessionId}/channels/{channelId}/admins/demote": {+ "post": {+ "description": "Requires this account to own the channel. There is no promote counterpart: neither engine library exposes one, so an admin is promoted from the WhatsApp app and demoted here.",+ "operationId": "ChannelController_demoteAdmin",+ "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/DemoteChannelAdminDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Admin demoted",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelAckResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session not started, or validation failed"+ },+ "403": {+ "description": "The engine refused — not the owner, or the user is not an admin"+ },+ "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: the WhatsApp Web module its library method targets no longer exports the function. Use the Baileys engine."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."+ }+ },+ "summary": "Demote a channel admin back to a subscriber",+ "tags": [+ "channels"+ ]+ }+ },"/api/sessions/{sessionId}/channels/subscribe": {"post": {"operationId": "ChannelController_subscribe",@@ -13590,6 +13657,19 @@"mute"]},+ "DemoteChannelAdminDto": {+ "type": "object",+ "properties": {+ "userId": {+ "type": "string",+ "description": "WhatsApp ID of the admin to demote back to a subscriber.",+ "example": "[email protected]"+ }+ },+ "required": [+ "userId"+ ]+ },"OverviewSessionsDto": {"type": "object","properties": {diff --git a/src/engine/adapters/baileys-channels.spec.ts b/src/engine/adapters/baileys-channels.spec.tsindex f06d088e6..d8a11dd11 100644--- a/src/engine/adapters/baileys-channels.spec.ts+++ b/src/engine/adapters/baileys-channels.spec.ts@@ -23,6 +23,7 @@ function channels(sock: Record<string, jest.Mock>, budgetMs: number): BaileysChaconst host = {ensureReady: () => undefined,getSocket: () => sock as unknown as WASocket,+ toEngineJid: (jid: string) => jid,} as unknown as BaileysChannelsHost;return new BaileysChannels(host, budgetMs);}@@ -37,6 +38,11 @@ describe('channel operations report an unanswered query instead of a bare 500',['muteChannel', 'newsletterMute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', true)],['unmuteChannel', 'newsletterUnmute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', false)],['unsubscribeFromChannel', 'newsletterUnfollow', (c: BaileysChannels) => c.unsubscribeFromChannel('120363@n')],+ [+ 'demoteChannelAdmin',+ 'newsletterDemote',+ (c: BaileysChannels) => c.demoteChannelAdmin('120363@n', '[email protected]'),+ ],])('%s', async (_name, sockMethod, call) => {await expect(call(channels({ [sockMethod]: jest.fn(never) }, 15))).rejects.toBeInstanceOf(EngineTransportError);});diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.tsindex 52a4e8d75..3f999545a 100644--- a/src/engine/adapters/baileys-channels.ts+++ b/src/engine/adapters/baileys-channels.ts@@ -13,6 +13,11 @@ export interface BaileysChannelsHost {ensureReady(): void;/** Post-ensureReady socket handle — call host.ensureReady() first. */getSocket(): WASocket;+ /**+ * Neutral → engine jid dialect. Channel ids need no mapping (`@newsletter` in both), but the+ * admin writes take a USER jid, which does.+ */+ toEngineJid(jid: string): string;}/**@@ -92,6 +97,25 @@ export class BaileysChannels {return this.toChannel(meta);}+ /**+ * Demote a channel admin back to a plain subscriber. `userId` arrives in the NEUTRAL dialect and+ * is mapped here, the way the contact and messaging delegates map theirs.+ *+ * There is no promote counterpart to pair this with, and that is upstream rather than ours:+ * Baileys exposes `newsletterDemote`, `newsletterChangeOwner` and `newsletterAdminCount` but no+ * promote, and whatsapp-web.js has no `promoteChannelAdmin` at all. An admin is promoted from the+ * WhatsApp app and can then be demoted through this API.+ */+ async demoteChannelAdmin(channelId: string, userId: string): Promise<void> {+ this.host.ensureReady();+ const userJid = this.host.toEngineJid(userId);+ await mapServerRefusal(+ 'Demoting the channel admin',+ () => this.bounded(this.sock().newsletterDemote(channelId, userJid), 'the channel admin demotion'),+ 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.tsindex b5fa4e862..11cb286df 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -189,6 +189,7 @@ export class BaileysAdapter implements IWhatsAppEngine {this.channels = new BaileysChannels({ensureReady: () => this.ensureReady(),getSocket: () => this.sock!,+ toEngineJid: jid => this.sessionStore.toEngineJid(jid),});this.catalog = new BaileysCatalog({ensureReady: () => this.ensureReady(),@@ -686,6 +687,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.channels.muteChannel(channelId, mute);}+ demoteChannelAdmin(channelId: string, userId: string): Promise<void> {+ return this.channels.demoteChannelAdmin(channelId, userId);+ }+getSubscribedChannels(): Promise<Channel[]> {return this.unsupported('getSubscribedChannels');}diff --git a/src/engine/adapters/channel-admin-demote.spec.ts b/src/engine/adapters/channel-admin-demote.spec.tsnew file mode 100644index 000000000..0c8a20737--- /dev/null+++ b/src/engine/adapters/channel-admin-demote.spec.ts@@ -0,0 +1,105 @@+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';++/**+ * Demote a channel admin back to a subscriber — the fifth of the 29.5.3 backlog.+ *+ * **There is no promote counterpart to pair this with, on either library.** Baileys exposes+ * `newsletterDemote`, `newsletterChangeOwner` and `newsletterAdminCount` but no promote, and+ * whatsapp-web.js has no `promoteChannelAdmin` at all. So the demote-only surface is the complete+ * upstream capability rather than a half-wired one: an admin is promoted from the WhatsApp app and+ * can then be demoted through this API.+ *+ * **Only Baileys can actually deliver it.** `Client.demoteChannelAdmin` exists and is typed+ * `Promise<boolean>`, but its page body calls+ * `window.require('WAWebDemoteNewsletterAdminAction').demoteNewsletterAdmin` — an export WhatsApp+ * Web no longer provides. Measured live on Web `2.3000.1044824727-alpha` (unpinned): a `TypeError`+ * reaching the caller as a bare 500, while `muteChannel` answered 200 twice on the same session, so+ * the page and its module registry were healthy. The wwjs adapter therefore answers 501 rather than+ * wiring a call that cannot work — see the matrix note on phantom support.+ *+ * Baileys resolves `void` through `executeWMexQuery`, so a refusal arrives as a Boom on the w:mex+ * channel and a silent socket arrives as nothing at all. Both get the same treatment the other+ * channel writes already have.+ */++const logger = createLogger('channel-admin-demote.spec');+const CHANNEL = '120363000000000000@newsletter';+const USER = '[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);+}++/** `toEngineJid` mirrors the real session store: neutral `@c.us` becomes engine `@s.whatsapp.net`. */+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.demoteChannelAdmin', () => {+ it('answers 501 rather than calling a library method whose page module is gone', async () => {+ const demoteChannelAdmin = jest.fn();+ await expect(wwebjs({ demoteChannelAdmin }).demoteChannelAdmin(CHANNEL, USER)).rejects.toBeInstanceOf(+ EngineNotSupportedError,+ );+ });++ // The load-bearing half: wiring the call would produce a phantom-support row — the matrix claiming+ // the capability while every request failed with a bare 500 (`TypeError: window.require(...)+ // .demoteNewsletterAdmin is not a function`, measured live on Web 2.3000.1044824727-alpha).+ it('does not reach the library at all, so a caller gets a verdict instead of a crash', async () => {+ const demoteChannelAdmin = jest.fn();+ await expect(wwebjs({ demoteChannelAdmin }).demoteChannelAdmin(CHANNEL, USER)).rejects.toThrow();+ expect(demoteChannelAdmin).not.toHaveBeenCalled();+ });+});++describe('BaileysChannels.demoteChannelAdmin', () => {+ // The channel id needs no mapping — `@newsletter` in both dialects — but the USER jid does, which+ // is why this delegate gained a mapper the other channel writes never needed.+ it('maps the user id to the engine dialect and leaves the channel id alone', async () => {+ const newsletterDemote = jest.fn().mockResolvedValue(undefined);+ await expect(baileys({ newsletterDemote }).demoteChannelAdmin(CHANNEL, USER)).resolves.toBeUndefined();+ expect(newsletterDemote).toHaveBeenCalledWith(CHANNEL, '[email protected]');+ });++ // The shape executeWMexQuery really throws: `Boom(msg, { statusCode: errorCode, data: firstError })`+ // where `firstError` is the GraphQL error NODE — an OBJECT. A numeric `data` is the IQ channel's+ // shape and would exercise a different branch of wmexRefusalCode than this path can reach.+ it('maps a w:mex refusal to a refusal', async () => {+ const newsletterDemote = jest.fn().mockRejectedValue(+ new Boom('GraphQL server error: not-authorized', {+ statusCode: 403,+ data: { message: 'not-authorized', error_code: 403 },+ }),+ );+ await expect(baileys({ newsletterDemote }).demoteChannelAdmin(CHANNEL, USER)).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('reports an unanswered query instead of a bare 500', async () => {+ await expect(+ baileys({ newsletterDemote: jest.fn(never) }, 15).demoteChannelAdmin(CHANNEL, USER),+ ).rejects.toBeInstanceOf(EngineTransportError);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex ee2ddfa1e..49efc66cc 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -867,6 +867,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.channels.muteChannel(channelId, mute);}+ demoteChannelAdmin(channelId: string, userId: string): Promise<void> {+ return this.channels.demoteChannelAdmin(channelId, userId);+ }+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.tsindex efb81c1ad..021d66ef9 100644--- a/src/engine/adapters/wwebjs-channels.ts+++ b/src/engine/adapters/wwebjs-channels.ts@@ -71,6 +71,34 @@ export class WwebjsChannels {};}+ /**+ * Not available on this engine, despite `Client.demoteChannelAdmin` existing and being typed+ * `Promise<boolean>` (`index.d.ts:35`).+ *+ * The page body calls `window.require('WAWebDemoteNewsletterAdminAction').demoteNewsletterAdmin`+ * (`Client.js:1907-1925`), and WhatsApp Web no longer provides that function. Measured against a+ * live session on Web `2.3000.1044824727-alpha` with no version pin: the call rejects with+ * `TypeError: window.require(...).demoteNewsletterAdmin is not a function`, which reached the+ * caller as a bare 500.+ *+ * A module-existence probe run in the same page narrows it further — **the module still resolves;+ * the function is gone**: `WAWebDemoteNewsletterAdminAction` → `demoteNewsletterAdmin: undefined`,+ * and the second demote path whatsapp-web.js uses elsewhere is equally dead+ * (`WAWebNewsletterDemoteAdminJob` → `demoteNewsletterAdminAction: undefined`). So there is no+ * sibling module to retarget, and `muteChannel` answered 200 twice on that session, so the page+ * and its registry were healthy throughout.+ *+ * Wiring it anyway would be a phantom-support row: the matrix would claim the capability while+ * every call failed. A 501 states the truth. Re-enable by restoring the call here and flipping+ * the matrix cell once whatsapp-web.js targets a module WhatsApp Web actually exports; the+ * Baileys engine serves this capability in the meantime.+ */+ /* eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */+ async demoteChannelAdmin(_channelId: string, _userId: string): Promise<void> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('demoteChannelAdmin');+ }+/** 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.tsindex bcfdd1973..b74418dfa 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' } },+ demoteChannelAdmin: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'supported' },+ evidence:+ 'baileys newsletterDemote(jid, userJid) → void via executeWMexQuery QueryIds.DEMOTE (Socket/newsletter.d.ts:25; newsletter.js:173-175). wwjs Client.demoteChannelAdmin exists and is typed Promise<boolean> (index.d.ts:35) but its page body calls window.require("WAWebDemoteNewsletterAdminAction").demoteNewsletterAdmin (Client.js:1907-1925), a function WhatsApp Web no longer provides — measured live on Web 2.3000.1044824727-alpha (unpinned): TypeError "demoteNewsletterAdmin is not a function", while muteChannel answered 200 on the same session. A module probe in that page shows the module still resolves and only the function is missing, and the alternative path (WAWebNewsletterDemoteAdminJob.demoteNewsletterAdminAction) is undefined too, so there is no sibling module to retarget. Neither library exposes a promote counterpart',+ },muteChat: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 8d6ff7932..c99fece4a 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -1064,6 +1064,14 @@ export interface IWhatsAppEngine {deleteChannel(channelId: string): Promise<void>;/** Mute or unmute a channel's notifications for this account. Does not affect subscription. */muteChannel(channelId: string, mute: boolean): Promise<void>;+ /**+ * Demote a channel admin back to a plain subscriber. Requires this account to own the channel.+ *+ * There is deliberately no promote counterpart: neither library has one — Baileys exposes no+ * `newsletterPromote` and whatsapp-web.js no `promoteChannelAdmin` — so an admin is promoted from+ * the WhatsApp app and can then be demoted here.+ */+ demoteChannelAdmin(channelId: string, userId: 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.tsindex 5b8e5a1f7..6366e72fb 100644--- a/src/modules/channel/channel.controller.spec.ts+++ b/src/modules/channel/channel.controller.spec.ts@@ -26,3 +26,22 @@ describe('ChannelController.getMessages limit parsing', () => {expect(service.getChannelMessages).toHaveBeenCalledWith('s1', 'ch1@newsletter', undefined);});});++describe('ChannelController.demoteAdmin', () => {+ it('forwards the path params and the body field in the right order', async () => {+ // The argument order is the whole risk here: sessionId, channelId and userId are all strings,+ // so a swap compiles, type-checks and would demote the wrong party in the wrong channel.+ const service = { demoteChannelAdmin: jest.fn().mockResolvedValue(undefined) };+ const controller = new ChannelController(service as unknown as ChannelService);+ await expect(controller.demoteAdmin('s1', 'ch1@newsletter', { userId: '[email protected]' })).resolves.toEqual({+ success: true,+ });+ expect(service.demoteChannelAdmin).toHaveBeenCalledWith('s1', 'ch1@newsletter', '[email protected]');+ });++ it('lets an engine refusal propagate instead of answering success', async () => {+ const service = { demoteChannelAdmin: jest.fn().mockRejectedValue(new Error('refused')) };+ const controller = new ChannelController(service as unknown as ChannelService);+ await expect(controller.demoteAdmin('s1', 'ch1@newsletter', { userId: '[email protected]' })).rejects.toThrow('refused');+ });+});diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.tsindex 2110fe230..282dd0454 100644--- a/src/modules/channel/channel.controller.ts+++ b/src/modules/channel/channel.controller.ts@@ -5,6 +5,7 @@ import { ChannelService } from './channel.service';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 { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import {@@ -151,6 +152,41 @@ export class ChannelController {return { success: true };}+ @Post(':channelId/admins/demote')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Demote a channel admin back to a subscriber',+ description:+ 'Requires this account to own the channel. There is no promote counterpart: neither engine ' ++ 'library exposes one, so an admin is promoted from the WhatsApp app and demoted here.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'channelId', description: 'Channel ID' })+ @ApiBody({ type: DemoteChannelAdminDto })+ @ApiResponse({ status: 200, description: 'Admin demoted', type: ChannelAckResponseDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })+ @ApiResponse({ status: 400, description: 'Session not started, or validation failed' })+ @ApiResponse({ status: 403, description: 'The engine refused — not the owner, or the user is not an admin' })+ @ApiResponse({+ status: 501,+ description:+ 'The whatsapp-web.js engine cannot perform this: the WhatsApp Web module its library method ' ++ 'targets no longer exports the function. Use the Baileys engine.',+ })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ async demoteAdmin(+ @Param('sessionId') sessionId: string,+ @Param('channelId') channelId: string,+ @Body() dto: DemoteChannelAdminDto,+ ): Promise<{ success: boolean }> {+ await this.channelService.demoteChannelAdmin(sessionId, channelId, dto.userId);+ 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.tsindex b43193976..d5916153a 100644--- a/src/modules/channel/channel.service.spec.ts+++ b/src/modules/channel/channel.service.spec.ts@@ -43,4 +43,16 @@ describe('ChannelService', () => {await makeService({ getChannelMessages }).getChannelMessages('s1', 'ch1', input);expect(getChannelMessages).toHaveBeenCalledWith('ch1', expected);});++ it('demoteChannelAdmin forwards the channel and user to the engine, dropping the sessionId', async () => {+ const demoteChannelAdmin = jest.fn().mockResolvedValue(undefined);+ await makeService({ demoteChannelAdmin }).demoteChannelAdmin('s1', 'ch1@newsletter', '[email protected]');+ expect(demoteChannelAdmin).toHaveBeenCalledWith('ch1@newsletter', '[email protected]');+ });++ it('demoteChannelAdmin throws 400 when the session is not started', () => {+ expect(() => makeService(undefined).demoteChannelAdmin('s1', 'ch1@newsletter', '[email protected]')).toThrow(+ BadRequestException,+ );+ });});diff --git a/src/modules/channel/channel.service.ts b/src/modules/channel/channel.service.tsindex c7ab3c953..7e66d1138 100644--- a/src/modules/channel/channel.service.ts+++ b/src/modules/channel/channel.service.ts@@ -56,6 +56,11 @@ export class ChannelService {return this.getEngine(sessionId).muteChannel(channelId, mute);}+ /** Demote a channel admin back to a subscriber. There is no promote counterpart on either engine. */+ demoteChannelAdmin(sessionId: string, channelId: string, userId: string) {+ return this.getEngine(sessionId).demoteChannelAdmin(channelId, userId);+ }+subscribeToChannel(sessionId: string, inviteCode: string) {return this.getEngine(sessionId).subscribeToChannel(inviteCode);}diff --git a/src/modules/channel/dto/demote-channel-admin.dto.ts b/src/modules/channel/dto/demote-channel-admin.dto.tsnew file mode 100644index 000000000..655f17921--- /dev/null+++ b/src/modules/channel/dto/demote-channel-admin.dto.ts@@ -0,0 +1,12 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsNotEmpty, IsString } from 'class-validator';++export class DemoteChannelAdminDto {+ @ApiProperty({+ description: 'WhatsApp ID of the admin to demote back to a subscriber.',+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ userId!: string;+}