Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(profile): remove the account's own profile picture
Yudhi Armyndharisd91736678991
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94e84814f..132a278ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `npm run check:sdk-events` compares each typed SDK's webhook event list to the contract, so an event the gateway accepts can no longer be missing from the SDKs.- `npm run check:sdk-docs` compares the SDK design doc and the coverage tables to the shipped client surface, so a client method can no longer ship undocumented.- `POST /sessions/:sessionId/calls/link` generates a shareable WhatsApp call link on both engines, returning the finished `https://call.whatsapp.com/…` URL; a WhatsApp-side failure answers `403` rather than a success carrying an empty link.+- `DELETE /sessions/:sessionId/profile/picture` removes the account profile picture on both engines; removing one that is already absent is a no-op answering `200`, so the call is safe to repeat.- `docs-29-counts.spec.ts` binds every count-shaped claim in `docs/29` to the capability matrix, so a figure restated in the intro, the architecture prose, a mermaid node or a section heading cannot drift from the source it restates.### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex a2098ee0e..207f43759 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6022,6 +6022,21 @@ or**Errors:** `400` neither `url` nor `base64` provided / base64 without `mimetype` · `401` · `403` · `500` engine refused the change+#### DELETE /api/sessions/:sessionId/profile/picture++Remove the account profile picture, leaving the account with WhatsApp's default avatar.++**Auth:** API key (OPERATOR)++No request body.++**Response** `200` — `{ "success": true, "message": "Profile picture removed" }`++Removing a picture that is already absent is a no-op and also answers `200`, so the call is safe to+repeat.++**Errors:** `400` session is not started · `401` · `403` · `500` engine refused the removal+### 6.4.14 CallsIncoming-call management. A `call.received` webhook/socket event (§6.6) announces an incoming ringing call and carries the `callId` used below.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 75d914bd1..73cbece5a 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 109 `IWhatsAppEngine` methods (29.4), **all 152+the installed library. Coverage is total: all 110 `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 109 `IWhatsAppEngine` methods; use it to see+- **29.4 — the OpenWA contract view.** Rows are the 110 `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 (109 methods ++instance behind the neutral `IWhatsAppEngine` interface (110 methods +`EngineEventCallbacks`), and all modules go through it:```mermaidflowchart LRsubgraph OpenWA["OpenWA"]API["REST API controllers"] --> SVC["Modules / services"]- SVC --> IF["IWhatsAppEngine - 109 methods"]+ SVC --> IF["IWhatsAppEngine - 110 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 (109 methods)+## 29.4 Full capability matrix — the OpenWA contract view (110 methods)Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide@@ -330,12 +330,13 @@ answers 501.### 29.4.11 Own profile & presence-| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ ⁴ | OpenWA REST |-| ------------------- | ------------------- | ------------------ | ----------- |-| `setProfileName` | ✅ | ✅ | ✅ |-| `setProfilePicture` | ✅ | ✅ | ✅ |-| `setProfileStatus` | ✅ | ✅ | ✅ |-| `setOnlinePresence` | ✅ | ✅ | ✅ |+| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ ⁴ | OpenWA REST |+| ---------------------- | ------------------- | ------------------ | ----------- |+| `setProfileName` | ✅ | ✅ | ✅ |+| `setProfilePicture` | ✅ | ✅ | ✅ |+| `deleteProfilePicture` | ✅ | ✅ | ✅ |+| `setProfileStatus` | ✅ | ✅ | ✅ |+| `setOnlinePresence` | ✅ | ✅ | ✅ |### 29.4.12 Presence & calls@@ -345,9 +346,9 @@ answers 501.| `rejectCall` | ✅ | ✅ | ✅ || `createCallLink` | ✅ | ✅ | ✅ |-**Totals:** 109 methods → 218 adapter cells: **196 ✅, 22 ❌** (2 adapter-gaps, 20-library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **90** methods-work on any engine (87 fully supported + 2 store-backed status reads), **9** are Baileys-only,+**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,**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@@ -537,20 +538,20 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at**Profile, contacts & presence** (12)-| Library method | OpenWA exposure |-| ------------------------ | ----------------------------------------- |-| `addOrEditContact` | ✅ `upsertContact` |-| `createCallLink` | ✅ `createCallLink` |-| `presenceSubscribe` | ✅ `subscribeToPresence` |-| `removeContact` | ✅ `deleteContact` |-| `removeCoverPhoto` | ❌ **not exposed** |-| `removeProfilePicture` | ✅ `deleteGroupPicture` |-| `star` | ✅ `starMessage` |-| `updateCoverPhoto` | ❌ **not exposed** |-| `updateProfileName` | ✅ `setProfileName` |-| `updateProfilePicture` | ✅ `setProfilePicture`, `setGroupPicture` |-| `updateProfileStatus` | ✅ `setProfileStatus` |-| `updateServerTimeOffset` | 🔩 plumbing |+| Library method | OpenWA exposure |+| ------------------------ | ----------------------------------------------- |+| `addOrEditContact` | ✅ `upsertContact` |+| `createCallLink` | ✅ `createCallLink` |+| `presenceSubscribe` | ✅ `subscribeToPresence` |+| `removeContact` | ✅ `deleteContact` |+| `removeCoverPhoto` | ❌ **not exposed** |+| `removeProfilePicture` | ✅ `deleteGroupPicture`, `deleteProfilePicture` |+| `star` | ✅ `starMessage` |+| `updateCoverPhoto` | ❌ **not exposed** |+| `updateProfileName` | ✅ `setProfileName` |+| `updateProfilePicture` | ✅ `setProfilePicture`, `setGroupPicture` |+| `updateProfileStatus` | ✅ `setProfileStatus` |+| `updateServerTimeOffset` | 🔩 plumbing |**Socket, session & plumbing** (21)@@ -702,7 +703,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| Library method | OpenWA exposure || ------------------------- | ----------------------------------------- |-| `deleteProfilePicture` | ❌ **not exposed** |+| `deleteProfilePicture` | ✅ `deleteProfilePicture` || `getProfilePicUrl` | ✅ `getProfilePicture` || `sendPresenceAvailable` | ✅ `setOnlinePresence` || `sendPresenceUnavailable` | ✅ `setOnlinePresence` |@@ -722,11 +723,10 @@ 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 |-| -------------------------- | -------------------------------------------------------- | -------------------------- | ------------------------------------------------------------ |-| Delete own profile picture | `removeProfilePicture(ownJid)` (`Socket/groups.d.ts:83`) | `deleteProfilePicture` | the Baileys symbol is already wired for `deleteGroupPicture` |-| 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 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` | |Near-misses (both libraries have the area, but the symbol sets only partially overlap — stillworth an interface method): **channel admin invites** (wwjs@@ -876,25 +876,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:-- **109** interface methods → **218** adapter cells: **196 ✅** / **22 ❌** (2 adapter-gaps, 20+- **110** interface methods → **220** adapter cells: **198 ✅** / **22 ❌** (2 adapter-gaps, 20library-limitations, 0 uncertain), spanning **21** methods.-- Of the 196 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,+- Of the 198 ✅ 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: **90** engine-neutral (88 + 2 store-backed status reads), **9** Baileys-only,+- REST caller's view: **91** engine-neutral (89 + 2 store-backed status reads), **9** 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- exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 46 wired,- 2 internal wiring, 1 class plumbing, **32 ❌ not exposed** (24 real capabilities + 8+ 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 + 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).-- **3** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the- cheapest backlog: delete-own-profile-picture, channel admin demote, channel ownership transfer.- (Chat mute/unmute, chat pin/unpin and create-call-link were three of the six; all three are now- wired — see `muteChat`, `pinChat` and `createCallLink`.)+- **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`.)- **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 c1276478e..0be438f06 100644--- a/openapi.json+++ b/openapi.json@@ -5901,6 +5901,48 @@"tags": ["profile"]+ },+ "delete": {+ "operationId": "ProfileController_deletePicture",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Profile picture removed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProfileAckResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session is not started"+ },+ "403": {+ "description": "The engine refused the picture removal"+ },+ "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."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came."+ }+ },+ "summary": "Remove the account's profile picture",+ "tags": [+ "profile"+ ]}},"/api/sessions/{sessionId}/calls/link": {diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex a56bdba9d..68ab0ec9e 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -144,6 +144,19 @@ export class BaileysContacts {await this.confirmed(this.sock().updateProfilePicture(selfJid, data), 'the profile picture change');}+ async deleteProfilePicture(): Promise<void> {+ this.host.ensureReady();+ const selfJid = this.host.normalizedSelfJid();+ if (!selfJid) {+ // Same guard as setProfilePicture: an empty jid would send the removal at nothing while the+ // endpoint reported success.+ throw new Error('cannot delete the profile picture: the own JID is not known yet');+ }+ // The same socket call `deleteGroupPicture` already uses, addressed at the account instead of a+ // group. Baileys resolves void either way, so an acknowledged write is the only signal there is.+ await this.confirmed(this.sock().removeProfilePicture(selfJid), 'the profile picture removal');+ }+// eslint-disable-next-line @typescript-eslint/require-awaitasync getContacts(): Promise<Contact[]> {this.host.ensureReady();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex b353a185a..b5fa4e862 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -512,6 +512,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.contacts.setProfileStatus(status);}+ async deleteProfilePicture(): Promise<void> {+ return this.contacts.deleteProfilePicture();+ }+async setProfilePicture(media: MediaInput): Promise<void> {return this.contacts.setProfilePicture(media);}diff --git a/src/engine/adapters/delete-profile-picture.spec.ts b/src/engine/adapters/delete-profile-picture.spec.tsnew file mode 100644index 000000000..727c96322--- /dev/null+++ b/src/engine/adapters/delete-profile-picture.spec.ts@@ -0,0 +1,108 @@+import type { WASocket } from '@whiskeysockets/baileys';+import type { Client } from 'whatsapp-web.js';+import { BaileysContacts, type BaileysContactsHost } from './baileys-contacts';+import { WwebjsProfile } from './wwebjs-profile';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Delete the account's OWN profile picture — the fourth of the §29.5.3 backlog.+ *+ * The declared type lies about the outcomes. `Client.deleteProfilePicture(): Promise<boolean>`+ * forwards `WWebJS.deletePicture`, which has THREE exits (`Injected/Utils.js:1404-1418`):+ * `undefined` — `collection.canDelete()` was false, so nothing was attempted+ * `true` — the delete request came back HTTP 200+ * `false` — a `ServerStatusCodeError`, i.e. WhatsApp refused+ * `undefined` is falsy, so a naive `if (!ok) throw` collapses "there was nothing to delete" into+ * "WhatsApp refused" and makes a repeat delete fail with a 403.+ *+ * The contract therefore treats `undefined` as success — deleting an absent picture is a no-op, not+ * an error — and `false` as a refusal, matching how `setProfileName` reports whatsapp-web.js's+ * falsy return. **That split is a decision, not a measurement**: `canDelete()` could equally be a+ * permission check, in which case a genuine refusal would arrive as `undefined` and be swallowed.+ * It is pinned here so the live probe can contradict it visibly rather than silently.+ *+ * Baileys resolves `void` and has no refusal signal at all, so it reports success whenever the+ * write is acknowledged. Its `removeProfilePicture` takes a JID and is already wired for+ * `deleteGroupPicture` — the own-account call is the same symbol with the self JID, which is why+ * an unknown self JID has to fail loudly rather than silently target nothing.+ */++const logger = createLogger('delete-profile-picture.spec');++describe('WwebjsProfile.deleteProfilePicture', () => {+ function makeProfile(client: Record<string, jest.Mock>): WwebjsProfile {+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ } as unknown as WwebjsEngineHost;+ return new WwebjsProfile(host);+ }++ it('a confirmed delete resolves', async () => {+ const deleteProfilePicture = jest.fn().mockResolvedValue(true);+ await expect(makeProfile({ deleteProfilePicture }).deleteProfilePicture()).resolves.toBeUndefined();+ expect(deleteProfilePicture).toHaveBeenCalledTimes(1);+ });++ // The distinction the declared `Promise<boolean>` hides.+ it('treats undefined as "nothing to delete" rather than a refusal, so a repeat delete is a no-op', async () => {+ const deleteProfilePicture = jest.fn().mockResolvedValue(undefined);+ await expect(makeProfile({ deleteProfilePicture }).deleteProfilePicture()).resolves.toBeUndefined();+ });++ it('reports an explicit false as a refusal', async () => {+ const deleteProfilePicture = jest.fn().mockResolvedValue(false);+ await expect(makeProfile({ deleteProfilePicture }).deleteProfilePicture()).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });+});++describe('BaileysContacts.deleteProfilePicture', () => {+ const never = (): Promise<never> => new Promise<never>(() => undefined);++ function makeContacts(+ sock: Record<string, jest.Mock>,+ opts: { selfJid?: string; budgetMs?: number } = {},+ ): BaileysContacts {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ logger,+ normalizedSelfJid: () => (opts.selfJid === undefined ? '[email protected]' : opts.selfJid),+ listContacts: () => [],+ findContact: () => null,+ resolvePhone: () => null,+ listChats: () => [],+ lastMessage: () => null,+ toEngineJid: (j: string) => j,+ toNeutralJid: (j: string) => j,+ } as unknown as BaileysContactsHost;+ return new BaileysContacts(host, opts.budgetMs ?? 500);+ }++ it("removes the picture for the account's OWN jid", async () => {+ const removeProfilePicture = jest.fn().mockResolvedValue(undefined);+ await expect(makeContacts({ removeProfilePicture }).deleteProfilePicture()).resolves.toBeUndefined();+ expect(removeProfilePicture).toHaveBeenCalledWith('[email protected]');+ });++ // Mirrors setProfilePicture: an unknown self JID must fail loudly. Passing an empty string would+ // send the removal at nothing while the endpoint reported success.+ it('fails loudly when the own JID is not known yet', async () => {+ const removeProfilePicture = jest.fn().mockResolvedValue(undefined);+ await expect(makeContacts({ removeProfilePicture }, { selfJid: '' }).deleteProfilePicture()).rejects.toThrow(+ /own JID/i,+ );+ expect(removeProfilePicture).not.toHaveBeenCalled();+ });++ it('reports an unconfirmed write rather than resolving on a silent socket', async () => {+ const contacts = makeContacts({ removeProfilePicture: jest.fn(never) }, { budgetMs: 15 });+ await expect(contacts.deleteProfilePicture()).rejects.toBeInstanceOf(EngineTransportError);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 32b3ed317..976411eb5 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -2002,6 +2002,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.profile.setProfileStatus(status);}+ deleteProfilePicture(): Promise<void> {+ return this.profile.deleteProfilePicture();+ }+setProfilePicture(media: MediaInput): Promise<void> {return this.profile.setProfilePicture(media);}diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsindex 0cb538348..15b0d46dd 100644--- a/src/engine/adapters/wwebjs-profile.ts+++ b/src/engine/adapters/wwebjs-profile.ts@@ -31,6 +31,20 @@ export class WwebjsProfile {return link;}+ async deleteProfilePicture(): Promise<void> {+ this.host.ensureReady();+ // `Promise<boolean>` understates this. `WWebJS.deletePicture` has three exits+ // (Injected/Utils.js:1404-1418): `undefined` when `canDelete()` was false and nothing was+ // attempted, `true` on an HTTP 200, `false` on a ServerStatusCodeError. `undefined` is falsy, so+ // the usual `if (!ok) throw` would report "there was nothing to delete" as a refusal and turn a+ // repeat delete into a 403. Only an explicit `false` is WhatsApp saying no.+ const result = await this.client().deleteProfilePicture();+ if (result === false) {+ throw new EngineRefusedError('the engine rejected the profile picture removal');+ }+ this.host.logger.log('Deleted profile picture');+ }+async setProfileName(name: string): Promise<void> {this.host.ensureReady();// setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex f4440f973..bcfdd1973 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -395,6 +395,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:'wwjs Client.setDisplayName(displayName) → boolean (index.d.ts:251; false → adapter throws); baileys updateProfileName(name) (Socket/chats.d.ts:50)',},+ deleteProfilePicture: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'baileys removeProfilePicture(ownJid) (Socket/groups.d.ts:83), the same symbol deleteGroupPicture already uses, resolving void; wwjs Client.deleteProfilePicture() (index.d.ts:339) forwards WWebJS.deletePicture, which returns undefined when canDelete() is false, true on HTTP 200 and false on a ServerStatusCodeError (Injected/Utils.js:1404-1418)',+ },setProfilePicture: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 56e9c67af..8d6ff7932 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -1034,6 +1034,16 @@ export interface IWhatsAppEngine {setProfileStatus(status: string): Promise<void>;/** Set the account's profile picture (a URL payload is fetched server-side). */setProfilePicture(media: MediaInput): Promise<void>;+ /**+ * Remove the account's own profile picture. Resolves when the removal is acknowledged; deleting a+ * picture that is not there is a no-op rather than an error, so the call is idempotent.+ *+ * Only whatsapp-web.js can report a refusal, and only as an explicit `false` — its page helper+ * also returns `undefined` when it did not attempt the delete at all, which is NOT a refusal.+ * Baileys resolves void and has no refusal signal, so it reports success for any acknowledged+ * write.+ */+ deleteProfilePicture(): Promise<void>;// Labels (Phase 3) - WhatsApp Business onlygetLabels(): Promise<Label[]>;diff --git a/src/modules/profile/profile.controller.spec.ts b/src/modules/profile/profile.controller.spec.tsindex a9b944930..d9ee8c85d 100644--- a/src/modules/profile/profile.controller.spec.ts+++ b/src/modules/profile/profile.controller.spec.ts@@ -1,5 +1,6 @@import { ProfileController } from './profile.controller';import { ProfileService } from './profile.service';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';describe('ProfileController', () => {const build = (service: Partial<Record<keyof ProfileService, jest.Mock>>) => {@@ -7,6 +8,24 @@ describe('ProfileController', () => {return { controller, service };};+ it('DELETE picture delegates and returns its own message', async () => {+ const { controller, service } = build({ deleteProfilePicture: jest.fn().mockResolvedValue(undefined) });+ await expect(controller.deletePicture('s1')).resolves.toEqual({+ success: true,+ message: 'Profile picture removed',+ });+ expect(service.deleteProfilePicture).toHaveBeenCalledWith('s1');+ });++ // A refusal must reach the caller. Answering the success envelope anyway would report a picture+ // as removed while it is still on the account.+ it('DELETE picture propagates a refusal rather than answering success', async () => {+ const { controller } = build({+ deleteProfilePicture: jest.fn().mockRejectedValue(new EngineRefusedError('refused')),+ });+ await expect(controller.deletePicture('s1')).rejects.toBeInstanceOf(EngineRefusedError);+ });+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({diff --git a/src/modules/profile/profile.controller.ts b/src/modules/profile/profile.controller.tsindex a9c35fdc7..10cccd733 100644--- a/src/modules/profile/profile.controller.ts+++ b/src/modules/profile/profile.controller.ts@@ -1,4 +1,4 @@-import { Controller, Put, Param, Body } from '@nestjs/common';+import { Controller, Put, Delete, Param, Body } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';import { ProfileAckResponseDto } from './dto/profile-response.dto';import { ProfileService } from './profile.service';@@ -74,4 +74,23 @@ export class ProfileController {await this.profileService.setProfilePicture(sessionId, dto);return { success: true, message: 'Profile picture updated' };}++ @Delete('picture')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: "Remove the account's profile picture" })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'Profile picture removed', type: ProfileAckResponseDto })+ @ApiResponse({ status: 400, description: 'Session is not started' })+ @ApiResponse({ status: 403, description: 'The engine refused the picture removal' })+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer within the request budget. The change may or may not have been applied — ' ++ 'the gateway stopped waiting for a confirmation that never came.',+ })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ async deletePicture(@Param('sessionId') sessionId: string) {+ await this.profileService.deleteProfilePicture(sessionId);+ return { success: true, message: 'Profile picture removed' };+ }}diff --git a/src/modules/profile/profile.service.spec.ts b/src/modules/profile/profile.service.spec.tsindex 160e2ed58..2cb55acd2 100644--- a/src/modules/profile/profile.service.spec.ts+++ b/src/modules/profile/profile.service.spec.ts@@ -28,6 +28,20 @@ describe('ProfileService', () => {expect(setProfileStatus).toHaveBeenCalledWith('');});+ it('deleteProfilePicture delegates to the engine with no arguments (the account is implicit)', async () => {+ const deleteProfilePicture = jest.fn().mockResolvedValue(undefined);+ await makeService({ deleteProfilePicture }).deleteProfilePicture('s1');+ // Called with nothing: the engine removes the picture of the account it is already bound to, so+ // forwarding the sessionId here would be a jid the adapter never asked for.+ expect(deleteProfilePicture).toHaveBeenCalledWith();+ });++ it('deleteProfilePicture throws 400 when the engine is missing', () => {+ // The route carries no body, so this guard is the only pre-check standing between the caller and+ // the adapter.+ expect(() => makeService(undefined).deleteProfilePicture('s1')).toThrow(BadRequestException);+ });+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).diff --git a/src/modules/profile/profile.service.ts b/src/modules/profile/profile.service.tsindex ae605cd1f..2149225f9 100644--- a/src/modules/profile/profile.service.ts+++ b/src/modules/profile/profile.service.ts@@ -25,6 +25,11 @@ export class ProfileService {return this.getEngine(sessionId).setProfileStatus(status);}+ /** Remove the account's own picture. Idempotent: no picture to remove is a no-op, not an error. */+ deleteProfilePicture(sessionId: string) {+ return this.getEngine(sessionId).deleteProfilePicture();+ }+/** 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);