Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): answer a protocol timeout on group and label reads with 503

Yudhi Armyndharis4c7d87a5f895
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index b0f391755..71ade78b0 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -19,6 +19,7 @@ import { GroupNotFoundError } from '../../common/errors/group-not-found.error';
import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';
import { toMessageMedia } from './wwebjs-messaging';
import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { isProtocolTimeout } from './wwebjs-lifecycle';
/**
* Extracts the JID of the parent community a group is linked to, if any.
@@ -151,6 +152,10 @@ export class WwebjsGroups {
this.host.reportIfPageTransportError(error, 'getGroupInfo');
throw new EngineTransportError(`Transport died while reading group ${groupId}`);
}
+ // A command that outran the protocol budget got no answer either way: a 503, but no death.
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError(`WhatsApp Web did not answer the read of group ${groupId} in time`);
+ }
this.host.logger.warn(`Failed to get group: ${groupId}`, { error: String(error) });
return null;
}
@@ -388,6 +393,9 @@ export class WwebjsGroups {
this.host.reportIfPageTransportError(error, 'getGroupJoinInfo');
throw new EngineTransportError(`Transport died while previewing invite ${inviteCode}`);
}
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError(`WhatsApp Web did not answer the preview of invite ${inviteCode} in time`);
+ }
this.host.logger.debug('getInviteInfo rejected; treating the invite as not found', {
error: error instanceof Error ? error.message : String(error),
});
@@ -432,6 +440,11 @@ export class WwebjsGroups {
this.host.reportIfPageTransportError(error, 'joinGroupViaInviteCode');
throw new EngineTransportError('Transport died while accepting the group invite');
}
+ // The join may still land WhatsApp-side, so this is the route's "may or may not have been
+ // applied" 503, never "invalid invite".
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError('WhatsApp Web did not answer the group invite acceptance in time');
+ }
this.host.logger.warn(`Failed to accept group invite: ${String(error)}`);
groupId = undefined;
}
diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.ts
index b74d6f8a6..ba9d36008 100644
--- a/src/engine/adapters/wwebjs-labels.ts
+++ b/src/engine/adapters/wwebjs-labels.ts
@@ -6,6 +6,7 @@ import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsu
import { LabelNotFoundError } from '../../common/errors/label-not-found.error';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
import { type WwebjsEngineHost, withPage } from './wwebjs-host';
+import { isProtocolTimeout } from './wwebjs-lifecycle';
/**
* Chat-label operations (WhatsApp Business only) extracted from WhatsAppWebJsAdapter. The adapter
@@ -56,6 +57,10 @@ export class WwebjsLabels {
this.host.reportIfPageTransportError(error, 'getChatsByLabel');
throw new EngineTransportError(`Transport died while listing chats for label ${labelId}`);
}
+ // Nor is a command that outran the protocol budget: no answer is not "no such label".
+ if (isProtocolTimeout(error)) {
+ throw new EngineTransportError(`WhatsApp Web did not answer the chat list for label ${labelId} in time`);
+ }
this.host.logger.debug('getChatsByLabelId rejected; treating the label as not found', {
labelId,
error: error instanceof Error ? error.message : String(error),
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 7261aaf1e..8f83b36fb 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -48,6 +48,25 @@ function isNavigationShapedInitRejection(reason: string): boolean {
return isExecutionContextDestroyedError(reason) || /window\.require is not a function/i.test(reason);
}
+/**
+ * A per-command CDP timeout is NOT a death: the renderer is merely slower than the budget, and
+ * the next command may succeed. On Puppeteer 24.38.0 this message carries none of the dead-page
+ * signatures, so isPageTransportError's carve-out changes no current behaviour: it pins the intent.
+ * It is still no answer from WhatsApp, so a caller must not read it as "no such resource" either.
+ *
+ * Matched on the FULL puppeteer phrase, not a bare `timed out`: a broad exclusion would also
+ * swallow a genuine death whose message happens to mention a timeout.
+ */
+const PROTOCOL_TIMEOUT_PATTERN = /timed out\. increase the 'protocoltimeout'/i;
+
+/** Whether the error is Puppeteer's per-command protocolTimeout expiring (never an HttpException). */
+export function isProtocolTimeout(error: unknown): boolean {
+ if (error instanceof HttpException) {
+ return false;
+ }
+ return PROTOCOL_TIMEOUT_PATTERN.test(error instanceof Error ? error.message : String(error));
+}
+
/**
* requestPairingCode retry budget. WhatsApp Web reloads the QR page while UNPAIRED, so a pairing
* request can land mid-navigation and either reject fast ("Execution context was destroyed") or hang
@@ -694,16 +713,6 @@ export class WwebjsLifecycle {
private static readonly PAGE_TRANSPORT_ERROR_PATTERN =
/protocol error|target closed|targetclosederror|detached frame|session closed|connection closed/i;
- /**
- * A per-command CDP timeout is NOT a death: the renderer is merely slower than the budget, and
- * the next command may succeed. On Puppeteer 24.38.0 this message carries none of the signatures
- * above, so the guard changes no current behaviour — it pins the intent.
- *
- * Matched on the FULL puppeteer phrase, not a bare `timed out`: a broad exclusion would also
- * swallow a genuine death whose message happens to mention a timeout.
- */
- private static readonly PROTOCOL_TIMEOUT_PATTERN = /timed out\. increase the 'protocoltimeout'/i;
-
/** Whether the error carries a dead page/transport signature (see PAGE_TRANSPORT_ERROR_PATTERN). */
isPageTransportError(error: unknown): boolean {
// An HttpException is never a dead page. It is an error THIS application constructed, and its
@@ -723,10 +732,10 @@ export class WwebjsLifecycle {
if (error instanceof HttpException) {
return false;
}
- const message = error instanceof Error ? error.message : String(error);
- if (WwebjsLifecycle.PROTOCOL_TIMEOUT_PATTERN.test(message)) {
+ if (isProtocolTimeout(error)) {
return false;
}
+ const message = error instanceof Error ? error.message : String(error);
return WwebjsLifecycle.PAGE_TRANSPORT_ERROR_PATTERN.test(message);
}
diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
index b53aa0f35..a65eec51a 100644
--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
@@ -3,6 +3,32 @@ import { Client } from 'whatsapp-web.js';
import configuration, { MAX_TIMER_MS } from '../../config/configuration';
import { validateEnv } from '../../config/env.validation';
import { WhatsAppWebJsAdapter } from './whatsapp-web-js.adapter';
+import { WwebjsLifecycle } from './wwebjs-lifecycle';
+import { WwebjsGroups } from './wwebjs-groups';
+import { WwebjsLabels } from './wwebjs-labels';
+import { type WwebjsEngineHost } from './wwebjs-host';
+import { createLogger } from '../../common/services/logger.service';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';
+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';
+import { LabelNotFoundError } from '../../common/errors/label-not-found.error';
+
+/**
+ * Provoked from the INSTALLED puppeteer-core rather than copied from it. The guard exists to
+ * survive a message the library may reshape on a version bump, so a hand-written literal would
+ * keep passing while the real string drifted out from under it — the one drift this test is
+ * here to catch. Driving the real `Callback` is also what shows the label is the bare CDP
+ * method name, with no `Protocol error (...)` prefix for the death pattern to match.
+ */
+const puppeteerProtocolTimeoutMessage = async (): Promise<string> => {
+ const callback = new Callback(1, 'Runtime.callFunctionOn', 1);
+ try {
+ await callback.promise;
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ throw new Error('puppeteer-core did not reject on an expired protocolTimeout');
+};
/**
* The per-CDP-command budget handed to Puppeteer, and the one error it produces.
@@ -120,23 +146,6 @@ describe('whatsapp-web.js protocol timeout', () => {
);
};
- /**
- * Provoked from the INSTALLED puppeteer-core rather than copied from it. The guard exists to
- * survive a message the library may reshape on a version bump, so a hand-written literal would
- * keep passing while the real string drifted out from under it — the one drift this test is
- * here to catch. Driving the real `Callback` is also what shows the label is the bare CDP
- * method name, with no `Protocol error (...)` prefix for the death pattern to match.
- */
- const puppeteerProtocolTimeoutMessage = async (): Promise<string> => {
- const callback = new Callback(1, 'Runtime.callFunctionOn', 1);
- try {
- await callback.promise;
- } catch (error) {
- return error instanceof Error ? error.message : String(error);
- }
- throw new Error('puppeteer-core did not reject on an expired protocolTimeout');
- };
-
it('does not treat a protocol timeout as a dead page', async () => {
const message = await puppeteerProtocolTimeoutMessage();
@@ -158,3 +167,58 @@ describe('whatsapp-web.js protocol timeout', () => {
});
});
});
+
+/**
+ * A timed-out command got no answer at all, so the verdict branches that read a rejection as "no such
+ * group" (404), "no such invite" (404), "invalid invite" (400) or "no such label" (404) must not see
+ * it. It is the 503 those routes document for a query that never came back, and it is not a death:
+ * the session must not be torn down for a slow renderer.
+ */
+describe('a protocol timeout is a 503, never a not-found verdict', () => {
+ const makeHost = (
+ client: Record<string, jest.Mock>,
+ ): { host: WwebjsEngineHost; reportIfPageTransportError: jest.Mock } => {
+ const reportIfPageTransportError = jest.fn();
+ const host = {
+ ensureReady: jest.fn(),
+ getClient: () => client as unknown as Client,
+ isPageTransportError: (error: unknown) => WwebjsLifecycle.prototype.isPageTransportError.call({}, error),
+ reportIfPageTransportError,
+ logger: createLogger('wwebjs-protocol-timeout.spec'),
+ } as unknown as WwebjsEngineHost;
+ return { host, reportIfPageTransportError };
+ };
+
+ const OPS: Record<string, [string, (host: WwebjsEngineHost) => Promise<unknown>]> = {
+ getGroupInfo: ['getChatById', host => new WwebjsGroups(host).getGroupInfo('[email protected]')],
+ getGroupJoinInfo: ['getInviteInfo', host => new WwebjsGroups(host).getGroupJoinInfo('AbCdEf')],
+ joinGroupViaInviteCode: ['acceptInvite', host => new WwebjsGroups(host).joinGroupViaInviteCode('AbCdEf')],
+ getChatsByLabel: ['getChatsByLabelId', host => new WwebjsLabels(host).getChatsByLabel('7')],
+ };
+
+ it.each(Object.keys(OPS))('%s answers an expired protocolTimeout with a 503 and reports no death', async op => {
+ const [method, call] = OPS[op];
+ const timeout = new Error(await puppeteerProtocolTimeoutMessage());
+ const { host, reportIfPageTransportError } = makeHost({ [method]: jest.fn().mockRejectedValue(timeout) });
+
+ await expect(call(host)).rejects.toBeInstanceOf(EngineTransportError);
+ expect(reportIfPageTransportError).not.toHaveBeenCalled();
+ });
+
+ // Negative twin: an ordinary page-side refusal keeps its not-found verdict.
+ it.each([
+ ['getGroupInfo', undefined],
+ ['getGroupJoinInfo', GroupNotFoundError],
+ ['joinGroupViaInviteCode', InvalidInviteCodeError],
+ ['getChatsByLabel', LabelNotFoundError],
+ ])('%s keeps its verdict for an ordinary refusal', async (op, verdict) => {
+ const [method, call] = OPS[op];
+ const { host } = makeHost({ [method]: jest.fn().mockRejectedValue(new Error('Evaluation failed: not found')) });
+
+ if (verdict) {
+ await expect(call(host)).rejects.toBeInstanceOf(verdict);
+ } else {
+ await expect(call(host)).resolves.toBeNull();
+ }
+ });
+});