Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): stop answering 503 where a replay would post twice

Yudhi Armyndharis6c08d1d6ca89
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 9c5148a88..10d4946d7 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4337,7 +4337,12 @@ Delete one of the session's own posted statuses.
The service returns `void`; the controller returns a fixed success object. DELETE default status is `200`.
-**Errors:** `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` `Session {id} not found or not connected` · `409` conflict or engine not ready (retryable)
+**Errors:** `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` `Session {id} not found or not connected` · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request, so the revoke did not complete
+
+Safe to retry: revoking an already-revoked status converges. The status POST routes deliberately do
+NOT answer `503` for the same failure, because whatsapp-web.js can throw after the request is on the
+wire and a client replaying on `503` would publish the status a second time. They answer an opaque
+`500` there, exactly as the message sends do.
### 6.4.8 Webhooks (management)
diff --git a/openapi.json b/openapi.json
index 5f9f316f4..fe31a86c5 100644
--- a/openapi.json
+++ b/openapi.json
@@ -7647,6 +7647,9 @@
},
"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": "The whatsapp-web.js page connection died mid-request, so the revoke did not complete. Safe to retry: revoking an already-revoked status converges. The status POST routes deliberately do NOT answer this, because a replayed post would publish the status a second time."
}
},
"summary": "Delete own status",
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 8abf45b0b..80ee6f968 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -6280,7 +6280,6 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
['setProfilePicture', (a: WhatsAppWebJsAdapter) => a.setProfilePicture({ mimetype: 'image/png', data: 'aGk=' })],
['deleteProfilePicture', (a: WhatsAppWebJsAdapter) => a.deleteProfilePicture()],
['getContactStatuses', (a: WhatsAppWebJsAdapter) => a.getContactStatuses()],
- ['postTextStatus', (a: WhatsAppWebJsAdapter) => a.postTextStatus('hello', {})],
['deleteStatus', (a: WhatsAppWebJsAdapter) => a.deleteStatus('status@broadcast')],
['getSubscribedChannels', (a: WhatsAppWebJsAdapter) => a.getSubscribedChannels()],
// The channel WRITES take the same path: deleteChannel reached the client directly, so a dead
@@ -6304,6 +6303,39 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
await expect(call(adapter)).rejects.toBeInstanceOf(EngineTransportError);
});
+ /**
+ * The non-idempotent writes are the exception, and deliberately so.
+ *
+ * whatsapp-web.js can throw AFTER the request is on the wire, so a transport failure here does
+ * not prove the status was not posted or the channel not created. `503` is the one status the
+ * clients read as "the gateway declined before acting", and the Go client replays a POST on it,
+ * so answering it would have a retrying caller publish the status twice. These report the death
+ * like everything else, then rethrow untouched, which is what the message sends already do.
+ */
+ it.each([
+ ['postTextStatus', (a: WhatsAppWebJsAdapter) => a.postTextStatus('hello', {})],
+ // The three media variants all land on the same postMediaStatus delegate.
+ ['postImageStatus', (a: WhatsAppWebJsAdapter) => a.postImageStatus({ mimetype: 'image/png', data: 'aGk=' }, {})],
+ ['postVideoStatus', (a: WhatsAppWebJsAdapter) => a.postVideoStatus({ mimetype: 'video/mp4', data: 'aGk=' }, {})],
+ ['postVoiceStatus', (a: WhatsAppWebJsAdapter) => a.postVoiceStatus({ mimetype: 'audio/ogg', data: 'aGk=' }, {})],
+ ['createChannel', (a: WhatsAppWebJsAdapter) => a.createChannel('name')],
+ ])('%s reports the death but keeps its own error, so a replay cannot duplicate', async (_name, call) => {
+ const adapter = readyAdapter({
+ sendMessage: jest.fn().mockRejectedValue(transportError()),
+ createChannel: jest.fn().mockRejectedValue(transportError()),
+ });
+ const thrown = await call(adapter).catch((error: unknown) => error);
+
+ expect(thrown).toBeInstanceOf(Error);
+ expect(thrown).not.toBeInstanceOf(EngineTransportError);
+ expect((thrown as Error).message).toContain('Target closed');
+ });
+
+ it('deleteStatus keeps the 503: revoking an already-revoked status converges, so a replay is safe', async () => {
+ const adapter = readyAdapter({ revokeStatusMessage: jest.fn().mockRejectedValue(transportError()) });
+ await expect(adapter.deleteStatus('status@broadcast')).rejects.toBeInstanceOf(EngineTransportError);
+ });
+
it('setProfilePicture classifies a dead page even when the media conversion itself fails on the dying transport', async () => {
// toMessageMedia with an http URL fetches through the page; on a dead transport that fetch
// dies first. The conversion stays OUTSIDE withPage by design (a bad URL is a 400-class
diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.ts
index 180c780ad..45a342561 100644
--- a/src/engine/adapters/wwebjs-channels.ts
+++ b/src/engine/adapters/wwebjs-channels.ts
@@ -4,7 +4,7 @@ import { BusinessClient, WwjsChannelData } from '../types/whatsapp-web-js.types'
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
-import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { type WwebjsEngineHost, withPage, reportPageDeath } from './wwebjs-host';
/**
* Channel/Newsletter operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public
@@ -54,7 +54,9 @@ export class WwebjsChannels {
*/
async createChannel(name: string, description?: string): Promise<Channel> {
this.host.ensureReady();
- const result = await this.withPage('createChannel', () =>
+ // Non-idempotent, matching ./baileys-channels, which leaves this unbounded for the same
+ // reason: a replayed create leaves a duplicate channel behind. See reportPageDeath.
+ const result = await reportPageDeath(this.host, 'createChannel', () =>
(this.client() as unknown as BusinessClient).createChannel(
name,
description === undefined ? {} : { description },
diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.ts
index adad473df..9fe4ff84a 100644
--- a/src/engine/adapters/wwebjs-host.ts
+++ b/src/engine/adapters/wwebjs-host.ts
@@ -46,3 +46,26 @@ export async function withPage<T>(host: WwebjsEngineHost, context: string, op: (
throw error;
}
}
+
+/**
+ * The NON-IDEMPOTENT counterpart of {@link withPage}: report a dead page as the same early death
+ * signal, then rethrow the error untouched so the caller's status is unchanged.
+ *
+ * whatsapp-web.js can throw AFTER the request is already on the wire (see `sendResolved` in
+ * ./wwebjs-messaging, which reports and rethrows for exactly this reason), so a transport failure
+ * here does NOT prove the status was not posted or the channel not created. `503` is the one status
+ * the clients read as proof the gateway declined before acting, and the Go client replays a POST on
+ * it, so answering it would have a retrying caller publish the status twice.
+ *
+ * ./baileys-channels leaves `createChannel` unbounded on the same reasoning, and the message sends
+ * keep their opaque `500`. Use {@link withPage} for reads and for operations that converge when
+ * repeated, including DELETE.
+ */
+export async function reportPageDeath<T>(host: WwebjsEngineHost, context: string, op: () => Promise<T>): Promise<T> {
+ try {
+ return await op();
+ } catch (error) {
+ host.reportIfPageTransportError(error, context);
+ throw error;
+ }
+}
diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.ts
index 3e26eaae6..87ef5f272 100644
--- a/src/engine/adapters/wwebjs-status.ts
+++ b/src/engine/adapters/wwebjs-status.ts
@@ -9,7 +9,7 @@ import {
} from '../interfaces/whatsapp-engine.interface';
import { SerializedWid } from '../types/whatsapp-web-js.types';
import { toMessageMedia } from './wwebjs-messaging';
-import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { type WwebjsEngineHost, withPage, reportPageDeath } from './wwebjs-host';
/**
* The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a
@@ -146,7 +146,8 @@ export class WwebjsStatus {
// whatsapp-web.js posts a text status by messaging status@broadcast with styling in `extra`
// (Client.js maps options.extra → page extraOptions → sendStatusTextMsgAction in Utils.js).
// backgroundColor is a #RRGGBB hex; font is the fontStyle index 0-7.
- const msg = await this.withPage('postTextStatus', () =>
+ // Non-idempotent: report a dead page, but keep the error as thrown. See reportPageDeath.
+ const msg = await reportPageDeath(this.host, 'postTextStatus', () =>
this.client().sendMessage('status@broadcast', text, {
extra: {
...(options.backgroundColor !== undefined ? { backgroundColor: options.backgroundColor } : {}),
@@ -180,7 +181,8 @@ export class WwebjsStatus {
this.host.ensureReady();
this.warnStatusRecipientsOnce(options);
const messageMedia = await toMessageMedia(media);
- const msg = await this.withPage('postMediaStatus', () =>
+ // Non-idempotent: a replayed post would publish the status twice. See reportPageDeath.
+ const msg = await reportPageDeath(this.host, 'postMediaStatus', () =>
this.client().sendMessage('status@broadcast', messageMedia, {
...(options.caption !== undefined ? { caption: options.caption } : {}),
...extra,
diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.ts
index 88ce9e8bc..6b2d5ca3f 100644
--- a/src/modules/status/status.controller.ts
+++ b/src/modules/status/status.controller.ts
@@ -165,6 +165,13 @@ export class StatusController {
@ApiResponse({ status: 200, description: 'Status deleted.', type: StatusDeletedResponseDto })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiResponse({ status: 404, description: SESSION_NOT_STARTED_404 })
+ @ApiResponse({
+ status: 503,
+ description:
+ 'The whatsapp-web.js page connection died mid-request, so the revoke did not complete. Safe ' +
+ 'to retry: revoking an already-revoked status converges. The status POST routes deliberately ' +
+ 'do NOT answer this, because a replayed post would publish the status a second time.',
+ })
async deleteStatus(@Param('sessionId') sessionId: string, @Param('id') statusId: string) {
await this.statusService.deleteStatus(sessionId, statusId);
return { message: 'Status deleted successfully' };