Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(contacts): report a dead page as 503, not 500
Yudhi Armyndharis89b7d65caeae
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24e844d89..08dae8661 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -81,6 +81,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `STORAGE_TYPE=s3` missing `S3_ACCESS_KEY_ID` or `S3_SECRET_ACCESS_KEY` now warns at startup and namesthe one that is unset, instead of silently writing every file to local disk and leaving the bucketempty. Thanks @onepay-ye.+- Six whatsapp-web.js contact operations answer the `503` their routes document when the browser page+ dies mid-request, instead of a bare `500` that tells a client not to retry: blocked contacts, number+ lookup, addressbook save and delete, and block and unblock. The list and single-contact reads in the+ same file already made that split ([#1476](https://github.com/rmyndharis/OpenWA/issues/1476)).+ Thanks @onepay-ye.### Dependenciesdiff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.tsindex 75f1624de..180c780ad 100644--- a/src/engine/adapters/wwebjs-channels.ts+++ b/src/engine/adapters/wwebjs-channels.ts@@ -3,9 +3,8 @@ 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';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** Channel/Newsletter operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public@@ -20,21 +19,9 @@ 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;- }+ /** See {@link withPage} for what a dead page answers here. */+ private withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ return withPage(this.host, context, op);}async getSubscribedChannels(): Promise<Channel[]> {diff --git a/src/engine/adapters/wwebjs-contact-transport-death.spec.ts b/src/engine/adapters/wwebjs-contact-transport-death.spec.tsnew file mode 100644index 000000000..31c1e3b4d--- /dev/null+++ b/src/engine/adapters/wwebjs-contact-transport-death.spec.ts@@ -0,0 +1,76 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsContacts } from './wwebjs-contacts';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Six contact operations reported a dead page and then rethrew the raw Puppeteer error, so the+ * caller got HTTP 500 while every one of those routes documents 503 (contact.controller.ts:78,+ * :117, :182, :207, :230, :252). A user hit it on GET /contacts/blocked when the renderer crashed+ * mid-read: the route promises "retry shortly" and answered the one status that says the opposite.+ *+ * The sibling reads in the same file (getContacts, getContactById, getProfilePicture) already made+ * the split, which is why the file answered two different statuses for one kind of failure.+ */+const logger = createLogger('wwebjs-contact-transport-death.spec');++describe('contact operations distinguish a dead page from an ordinary failure', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');++ function makeContacts(reject: unknown): {+ contacts: WwebjsContacts;+ reportIfPageTransportError: jest.Mock;+ } {+ const contact = {+ block: jest.fn().mockRejectedValue(reject),+ unblock: jest.fn().mockRejectedValue(reject),+ };+ const client = {+ getNumberId: jest.fn().mockRejectedValue(reject),+ getBlockedContacts: jest.fn().mockRejectedValue(reject),+ saveOrEditAddressbookContact: jest.fn().mockRejectedValue(reject),+ deleteAddressbookContact: jest.fn().mockRejectedValue(reject),+ getContactById: jest.fn().mockResolvedValue(contact),+ };+ const reportIfPageTransportError = jest.fn();+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: (error: unknown) => error === transportError,+ reportIfPageTransportError,+ logger,+ } as unknown as WwebjsEngineHost;+ return { contacts: new WwebjsContacts(host), reportIfPageTransportError };+ }++ const call = (contacts: WwebjsContacts, op: string): Promise<unknown> =>+ ({+ getNumberId: () => contacts.getNumberId('628123'),+ getBlockedContacts: () => contacts.getBlockedContacts(),+ upsertContact: () => contacts.upsertContact('[email protected]', 'Ada'),+ deleteContact: () => contacts.deleteContact('[email protected]'),+ blockContact: () => contacts.blockContact('[email protected]'),+ unblockContact: () => contacts.unblockContact('[email protected]'),+ })[op]!();++ const OPS = ['getNumberId', 'getBlockedContacts', 'upsertContact', 'deleteContact', 'blockContact', 'unblockContact'];++ it.each(OPS)('%s answers a dead page with the 503 its route documents', async op => {+ const { contacts, reportIfPageTransportError } = makeContacts(transportError);++ await expect(call(contacts, op)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ // Negative twin: an ordinary page-side failure must still surface untouched. Without this the fix+ // could simply relabel every failure as a 503, which would tell a caller to retry a request that+ // WhatsApp genuinely refused.+ it.each(OPS)('%s still propagates an ordinary failure unchanged', async op => {+ const refusal = new Error('Evaluation failed: contact not found');+ const { contacts, reportIfPageTransportError } = makeContacts(refusal);++ await expect(call(contacts, op)).rejects.toBe(refusal);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex bbeea6944..2ec4b54c7 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -3,7 +3,7 @@ import { Contact } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { userPart } from '../identity/wa-id';import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';-import { type WwebjsEngineHost } from './wwebjs-host';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/** The raw whatsapp-web.js contact element type, kept local so the wwebjs `Contact` type never leaks. */type RawWwebjsContact = Awaited<ReturnType<Client['getContacts']>>[number];@@ -97,15 +97,10 @@ export class WwebjsContacts {async getNumberId(number: string): Promise<string | null> {this.host.ensureReady();- try {- const numberId = await this.client().getNumberId(number);- // Read both property names: a WA Web build that renamed `_serialized` would otherwise make- // every number look unregistered — and checkNumberExists below reports exactly that.- return readWid(numberId) ?? null;- } catch (error) {- this.host.reportIfPageTransportError(error, 'getNumberId');- throw error;- }+ const numberId = await withPage(this.host, 'getNumberId', () => this.client().getNumberId(number));+ // Read both property names: a WA Web build that renamed `_serialized` would otherwise make+ // every number look unregistered — and checkNumberExists below reports exactly that.+ return readWid(numberId) ?? null;}async checkNumberExists(number: string): Promise<boolean> {@@ -133,20 +128,24 @@ export class WwebjsContacts {// undefined, which would land in the page-side payload as the literal string "undefined".// syncToAddressbook is left at its default (false): writing to the device addressbook is a// heavier, separately-consented action than saving the WhatsApp contact.- await this.client().saveOrEditAddressbookContact(userPart(contactId), firstName, lastName);+ await withPage(this.host, 'upsertContact', () =>+ this.client().saveOrEditAddressbookContact(userPart(contactId), firstName, lastName),+ );this.host.logger.log(`Saved addressbook contact ${contactId}`);}async deleteContact(contactId: string): Promise<void> {this.host.ensureReady();- await this.client().deleteAddressbookContact(userPart(contactId));+ await withPage(this.host, 'deleteContact', () => this.client().deleteAddressbookContact(userPart(contactId)));this.host.logger.log(`Deleted addressbook contact ${contactId}`);}async blockContact(contactId: string): Promise<void> {this.host.ensureReady();- const contact = await this.client().getContactById(contactId);- await contact.block();+ await withPage(this.host, 'blockContact', async () => {+ const contact = await this.client().getContactById(contactId);+ await contact.block();+ });this.host.logger.log(`Blocked contact ${contactId}`);}@@ -157,19 +156,16 @@ export class WwebjsContacts {*/async getBlockedContacts(): Promise<string[]> {this.host.ensureReady();- try {- const contacts = await this.client().getBlockedContacts();- return contacts.map(c => readWid(c.id as unknown as SerializedWid)).filter((id): id is string => Boolean(id));- } catch (error) {- this.host.reportIfPageTransportError(error, 'getBlockedContacts');- throw error;- }+ const contacts = await withPage(this.host, 'getBlockedContacts', () => this.client().getBlockedContacts());+ return contacts.map(c => readWid(c.id as unknown as SerializedWid)).filter((id): id is string => Boolean(id));}async unblockContact(contactId: string): Promise<void> {this.host.ensureReady();- const contact = await this.client().getContactById(contactId);- await contact.unblock();+ await withPage(this.host, 'unblockContact', async () => {+ const contact = await this.client().getContactById(contactId);+ await contact.unblock();+ });this.host.logger.log(`Unblocked contact ${contactId}`);}diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.tsindex 7d9315c42..adad473df 100644--- a/src/engine/adapters/wwebjs-host.ts+++ b/src/engine/adapters/wwebjs-host.ts@@ -1,6 +1,7 @@import { type Client, type Message } from 'whatsapp-web.js';import { type EngineEventCallbacks, type IncomingMessage } from '../interfaces/whatsapp-engine.interface';import { type createLogger } from '../../common/services/logger.service';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';/**@@ -25,3 +26,23 @@ export interface WwebjsEngineHost {/** Own account wid, or undefined while no client exists (late events during teardown). */getSelfWid(): string | undefined;}++/**+ * 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.+ *+ * Lives here rather than per delegate: ./wwebjs-channels, ./wwebjs-profile and ./wwebjs-status each+ * held a byte-identical private copy, and ./wwebjs-contacts needed a fourth.+ */+export async function withPage<T>(host: WwebjsEngineHost, context: string, op: () => Promise<T>): Promise<T> {+ try {+ return await op();+ } catch (error) {+ if (host.isPageTransportError(error)) {+ host.reportIfPageTransportError(error, context);+ throw new EngineTransportError(`Transport died during ${context}`);+ }+ throw error;+ }+}diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsindex 0ea4dfaf6..858eaaf6b 100644--- a/src/engine/adapters/wwebjs-profile.ts+++ b/src/engine/adapters/wwebjs-profile.ts@@ -1,9 +1,8 @@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';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** Own-account profile operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public@@ -18,21 +17,9 @@ 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;- }+ /** See {@link withPage} for what a dead page answers here. */+ private withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ return withPage(this.host, context, op);}async createCallLink(type: CallLinkType, startTime: number): Promise<string> {diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.tsindex 63a81b6a3..3e26eaae6 100644--- a/src/engine/adapters/wwebjs-status.ts+++ b/src/engine/adapters/wwebjs-status.ts@@ -9,8 +9,7 @@ import {} from '../interfaces/whatsapp-engine.interface';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';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a@@ -59,21 +58,9 @@ 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;- }+ /** See {@link withPage} for what a dead page answers here. */+ private withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ return withPage(this.host, context, op);}async getContactStatuses(): Promise<Status[]> {