Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): classify a dead page on the wwjs profile, status and channel routes
Yudhi Armyndharised59b0a77a53
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca82f3fc6..117f362f4 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### Fixed+- whatsapp-web.js profile, status and channel operations classify a dead browser page as the documented `503` plus an early death signal instead of an opaque `500` while the session still reports READY, matching the split the chat operations already made.- docs/06 repair pass over the Errors lines: the ingress `401` is the signature failure (not an API-key error), label writes have no `404`, the catalog product lookup answers `200` empty (not `404`), search's `501` names the no-provider case, multi-line Errors blocks were re-joined (no severed sentences, duplicate codes, or `· ·` separators), and the gate now reads wrapped blocks.- docs/14 corrects four hazard-table release labels (instance-config is 0.18.0, the reload `409` is 0.15.0, the group-summary retypes are 0.14.6, Baileys 5xx is 0.14.5), docs/03 drops a duplicated `health/`, and docs/10's scaling note matches docs/13's "still deploy replicas: 1" stance.- docs/06's audit section scopes the always-null columns correctly (`userAgent`/`statusCode` always null; `method`/`path` populated on auth-failure, key-lifecycle and queue-board rows), the Chats quote box renders identically under system-dark and explicit dark, and the Logs empty state gives server-filter guidance when only the severity filter is active (13 locales).diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 50281c637..16d48a0d6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -6035,6 +6035,43 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBeInstanceOf(EngineTransportError);});+ // The profile/status/channel delegates gained the same split the chats reads already had:+ // a dead page is the documented 503 plus an early death signal, not an opaque 500.+ // Adapter-level signatures (no sessionId: that is the service layer's argument).+ it.each([+ ['setProfileName', (a: WhatsAppWebJsAdapter) => a.setProfileName('New Name')],+ ['setProfileStatus', (a: WhatsAppWebJsAdapter) => a.setProfileStatus('Busy')],+ ['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()],+ ])('%s answers EngineTransportError (503) on a dead page', async (_name, call) => {+ const adapter = readyAdapter({+ setDisplayName: jest.fn().mockRejectedValue(transportError()),+ setStatus: jest.fn().mockRejectedValue(transportError()),+ setProfilePicture: jest.fn().mockRejectedValue(transportError()),+ deleteProfilePicture: jest.fn().mockRejectedValue(transportError()),+ getBroadcasts: jest.fn().mockRejectedValue(transportError()),+ sendMessage: jest.fn().mockRejectedValue(transportError()),+ revokeStatusMessage: jest.fn().mockRejectedValue(transportError()),+ getChannels: jest.fn().mockRejectedValue(transportError()),+ });+ await expect(call(adapter)).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+ // failure, not a transport death), so this case asserts the rejection is the raw TypeError+ // from the mock - documenting the boundary rather than forcing it into the 503 class.+ const adapter = readyAdapter({ setProfilePicture: jest.fn() });+ await expect(+ adapter.setProfilePicture({ mimetype: 'image/png', data: 'http://dead.lan/x.png' }),+ ).rejects.toBeInstanceOf(Error);+ });+it('joinGroupViaInviteCode still maps a refused invite to InvalidInviteCodeError (400)', async () => {const adapter = readyAdapter({acceptInvite: jest.fn().mockRejectedValue(new Error('Evaluation failed: Error: 404')),diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.tsindex c7e9b5c4a..d9703ac59 100644--- a/src/engine/adapters/wwebjs-channels.ts+++ b/src/engine/adapters/wwebjs-channels.ts@@ -3,6 +3,7 @@ import { Channel, ChannelMessage } from '../interfaces/whatsapp-engine.interfaceimport { 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 { EngineTransportError } from '../../common/errors/engine-transport.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { type WwebjsEngineHost } from './wwebjs-host';@@ -19,9 +20,28 @@ export class WwebjsChannels {return this.host.getClient();}+ /**+ * Run a client operation, classifying a dead page/transport as the documented 503 plus an early+ * death signal instead of an opaque 500 under a status that still says READY - the split every+ * chats read already makes (#1081). Other errors propagate unchanged.+ */+ private async withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ try {+ return await op();+ } catch (error) {+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, context);+ throw new EngineTransportError(`Transport died during ${context}`);+ }+ throw error;+ }+ }+async getSubscribedChannels(): Promise<Channel[]> {this.host.ensureReady();- const channels = await (this.client() as unknown as BusinessClient).getChannels();+ const channels = await this.withPage('getSubscribedChannels', () =>+ (this.client() as unknown as BusinessClient).getChannels(),+ );if (!channels) {return [];}@@ -47,9 +67,11 @@ export class WwebjsChannels {*/async createChannel(name: string, description?: string): Promise<Channel> {this.host.ensureReady();- const result = await (this.client() as unknown as BusinessClient).createChannel(- name,- description === undefined ? {} : { description },+ const result = await this.withPage('createChannel', () =>+ (this.client() as unknown as BusinessClient).createChannel(+ name,+ description === undefined ? {} : { description },+ ),);if (typeof result === 'string' || !result?.nid) {throw new EngineRefusedError(typeof result === 'string' ? result : `Failed to create the channel '${name}'`);@@ -149,7 +171,7 @@ export class WwebjsChannels {if (!channelId.endsWith('@newsletter')) {throw new ChannelNotFoundError(channelId);}- const chat = (await this.client().getChatById(channelId)) as unknown as {+ const chat = (await this.withPage('muteChannel', () => this.client().getChatById(channelId))) as unknown as {mute?: () => Promise<boolean>;unmute?: () => Promise<boolean>;} | null;@@ -157,7 +179,7 @@ export class WwebjsChannels {if (!act) {throw new ChannelNotFoundError(channelId);}- const ok = await act.call(chat);+ const ok = await this.withPage('muteChannel', () => act.call(chat));if (!ok) {throw new EngineRefusedError(`Failed to ${mute ? 'mute' : 'unmute'} channel ${channelId}`);}@@ -187,7 +209,9 @@ export class WwebjsChannels {this.host.ensureReady();// Resolves false instead of throwing when the unsubscription did not complete (Client.js:2556)// — surface the refusal rather than reporting a false success.- const ok = await (this.client() as unknown as BusinessClient).unsubscribeFromChannel(channelId);+ const ok = await this.withPage('unsubscribeFromChannel', () =>+ (this.client() as unknown as BusinessClient).unsubscribeFromChannel(channelId),+ );if (!ok) {throw new EngineRefusedError(`Failed to unsubscribe from channel ${channelId}`);}@@ -201,7 +225,9 @@ export class WwebjsChannels {// so resolve the channel from that list and read its messages. A missing channel surfaces as a// ChannelNotFoundError (→ 404, like getChannelById) so callers can tell "no messages" apart from// "wrong/unsubscribed channel" instead of getting a silent [].- const channels = await (this.client() as unknown as BusinessClient).getChannels();+ const channels = await this.withPage('getChannelMessages', () =>+ (this.client() as unknown as BusinessClient).getChannels(),+ );const channel = channels?.find(c => (typeof c.id === 'object' ? c.id._serialized : c.id) === channelId);if (!channel) {throw new ChannelNotFoundError(channelId);@@ -210,7 +236,7 @@ export class WwebjsChannels {// splice are both gated on `searchOptions.limit > 0` (Channel.js:352), so a 0/negative/NaN// limit fails OPEN and returns every loaded message. Substitute the default instead.const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 50;- const messages = await channel.fetchMessages({ limit: safeLimit });+ const messages = await this.withPage('getChannelMessages', () => channel.fetchMessages({ limit: safeLimit }));return (messages ?? []).map(msg => ({// Read `$1` before the sentinel (#747), and don't `String()` the object branch: that turned an// unreadable id into the literal "undefined" rather than the empty sentinel every other pathdiff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsindex 15b0d46dd..0ea4dfaf6 100644--- a/src/engine/adapters/wwebjs-profile.ts+++ b/src/engine/adapters/wwebjs-profile.ts@@ -1,6 +1,7 @@import { type Client } from 'whatsapp-web.js';import { CallLinkType, MediaInput } from '../interfaces/whatsapp-engine.interface';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { toMessageMedia } from './wwebjs-messaging';import { type WwebjsEngineHost } from './wwebjs-host';@@ -17,12 +18,31 @@ export class WwebjsProfile {return this.host.getClient();}+ /**+ * Run a client operation, classifying a dead page/transport as the documented 503 plus an early+ * death signal instead of an opaque 500 under a status that still says READY - the split every+ * chats read already makes (#1081). Detection only for other errors: they propagate unchanged.+ */+ private async withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ try {+ return await op();+ } catch (error) {+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, context);+ throw new EngineTransportError(`Transport died during ${context}`);+ }+ throw error;+ }+ }+async createCallLink(type: CallLinkType, startTime: number): Promise<string> {this.host.ensureReady();// whatsapp-web.js rejects any callType outside 'voice' | 'video', so the neutral 'audio' maps// here. It floors the Date to seconds itself, so the epoch-milliseconds the contract takes goes// straight into the Date.- const link = await this.client().createCallLink(new Date(startTime), type === 'video' ? 'video' : 'voice');+ const link = await this.withPage('createCallLink', () =>+ this.client().createCallLink(new Date(startTime), type === 'video' ? 'video' : 'voice'),+ );if (!link) {// Documented as "the link, or an empty string if a generation failed" — returning that empty// string would hand the caller a success with nothing in it.@@ -38,7 +58,7 @@ export class WwebjsProfile {// 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();+ const result = await this.withPage('deleteProfilePicture', () => this.client().deleteProfilePicture());if (result === false) {throw new EngineRefusedError('the engine rejected the profile picture removal');}@@ -48,7 +68,7 @@ export class WwebjsProfile {async setProfileName(name: string): Promise<void> {this.host.ensureReady();// setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.- const ok = await this.client().setDisplayName(name);+ const ok = await this.withPage('setProfileName', () => this.client().setDisplayName(name));if (!ok) {throw new EngineRefusedError('the engine rejected the profile name change');}@@ -57,7 +77,7 @@ export class WwebjsProfile {async setProfileStatus(status: string): Promise<void> {this.host.ensureReady();- await this.client().setStatus(status);+ await this.withPage('setProfileStatus', () => this.client().setStatus(status));this.host.logger.log('Updated profile status');}@@ -65,7 +85,7 @@ export class WwebjsProfile {this.host.ensureReady();const messageMedia = await toMessageMedia(media);// setProfilePicture resolves false (rather than throwing) when the upload is refused.- const ok = await this.client().setProfilePicture(messageMedia);+ const ok = await this.withPage('setProfilePicture', () => this.client().setProfilePicture(messageMedia));if (!ok) {throw new EngineRefusedError('the engine rejected the profile picture change');}diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.tsindex 0ffadd919..63a81b6a3 100644--- a/src/engine/adapters/wwebjs-status.ts+++ b/src/engine/adapters/wwebjs-status.ts@@ -10,6 +10,7 @@ import {import { SerializedWid } from '../types/whatsapp-web-js.types';import { toMessageMedia } from './wwebjs-messaging';import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';/*** The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a@@ -58,9 +59,26 @@ export class WwebjsStatus {return this.host.getClient();}+ /**+ * Run a client operation, classifying a dead page/transport as the documented 503 plus an early+ * death signal instead of an opaque 500 under a status that still says READY - the split every+ * chats read already makes (#1081). Other errors propagate unchanged.+ */+ private async withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ try {+ return await op();+ } catch (error) {+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, context);+ throw new EngineTransportError(`Transport died during ${context}`);+ }+ throw error;+ }+ }+async getContactStatuses(): Promise<Status[]> {this.host.ensureReady();- return this.collectStatuses(await this.client().getBroadcasts());+ return this.collectStatuses(await this.withPage('getContactStatuses', () => this.client().getBroadcasts()));}async getContactStatus(contactId: string): Promise<Status[]> {@@ -68,7 +86,7 @@ export class WwebjsStatus {// A contact with no active 24h story resolves to an "empty" Broadcast (id/msgs/getContact// undefined — Broadcast._patch only runs when data is truthy). That is the common case, so guard// it: return [] rather than dereferencing undefined inside collectStatuses (→ 500).- const broadcast = await this.client().getBroadcastById(contactId);+ const broadcast = await this.withPage('getContactStatus', () => this.client().getBroadcastById(contactId));return broadcast?.msgs?.length ? this.collectStatuses([broadcast]) : [];}@@ -141,12 +159,14 @@ 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.client().sendMessage('status@broadcast', text, {- extra: {- ...(options.backgroundColor !== undefined ? { backgroundColor: options.backgroundColor } : {}),- ...(options.font !== undefined ? { fontStyle: options.font } : {}),- },- });+ const msg = await this.withPage('postTextStatus', () =>+ this.client().sendMessage('status@broadcast', text, {+ extra: {+ ...(options.backgroundColor !== undefined ? { backgroundColor: options.backgroundColor } : {}),+ ...(options.font !== undefined ? { fontStyle: options.font } : {}),+ },+ }),+ );return toStatusResult(msg);}@@ -173,10 +193,12 @@ export class WwebjsStatus {this.host.ensureReady();this.warnStatusRecipientsOnce(options);const messageMedia = await toMessageMedia(media);- const msg = await this.client().sendMessage('status@broadcast', messageMedia, {- ...(options.caption !== undefined ? { caption: options.caption } : {}),- ...extra,- });+ const msg = await this.withPage('postMediaStatus', () =>+ this.client().sendMessage('status@broadcast', messageMedia, {+ ...(options.caption !== undefined ? { caption: options.caption } : {}),+ ...extra,+ }),+ );return toStatusResult(msg);}@@ -194,6 +216,6 @@ export class WwebjsStatus {// Revokes the caller's own status post. revokeStatusMessage resolves the message by id and// throws if it isn't fromMe/isn't a status — the statusId returned by postText/Image/VideoStatus// (msg.id._serialized) is the id it expects.- await this.client().revokeStatusMessage(statusId);+ await this.withPage('deleteStatus', () => this.client().revokeStatusMessage(statusId));}}