Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): never read a domain error as a dead page
Yudhi Armyndharisb16b8029e6a7
diff --git a/src/engine/adapters/wwebjs-domain-error-classification.spec.ts b/src/engine/adapters/wwebjs-domain-error-classification.spec.tsnew file mode 100644index 000000000..0badaae14--- /dev/null+++ b/src/engine/adapters/wwebjs-domain-error-classification.spec.ts@@ -0,0 +1,87 @@+import { BadRequestException, HttpException, NotFoundException } from '@nestjs/common';+import { WwebjsLifecycle } from './wwebjs-lifecycle';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * The dead-page classifier must never read an error this application constructed.+ *+ * Its domain errors interpolate caller-supplied identifiers verbatim, so matching a message pattern+ * against one hands the CALLER the classifier. A request naming a messageId of "Target closed" made+ * its own 404 look like a transport death: the session was torn down and reconnected, spurious+ * session.disconnected events went out to every consumer, inbound delivery paused for the+ * reconnect, and the honest 404 came back as a 503 that the Go client replays. The reactions read+ * carries no role requirement, so the lowest-privilege key could do it on demand, repeatedly.+ *+ * The classifier is the one funnel: `withPage` and every open-coded guard in the chats, contacts,+ * groups, labels and messaging delegates route through it, so one exclusion covers them all.+ */+describe('isPageTransportError', () => {+ // The method reads only static patterns, so a bare prototype call is enough and avoids standing+ // up a Client, a logger and an auth path that have nothing to do with the classification.+ const classify = (error: unknown): boolean => WwebjsLifecycle.prototype.isPageTransportError.call({}, error);++ describe('an error the application constructed is never a dead page', () => {+ it.each([+ ['Target closed', undefined],+ ['protocol error', '[email protected]'],+ ['Session closed', '[email protected]'],+ ['detached frame', '[email protected]'],+ ['connection closed', '[email protected]'],+ ['TargetCloseError', '[email protected]'],+ ])('a messageId of %p does not classify as one', (messageId, chatId) => {+ const error = new MessageNotFoundError(messageId, chatId);++ // The poisoned text really is in the message; the guard is what stops it mattering.+ expect(error.message).toContain(messageId);+ expect(classify(error)).toBe(false);+ });++ it('covers the sibling domain errors that carry caller text the same way', () => {+ expect(classify(new GroupNotFoundError('Target closed'))).toBe(false);+ expect(classify(new NotFoundException('Target closed'))).toBe(false);+ expect(classify(new BadRequestException('protocol error'))).toBe(false);+ });++ /**+ * An EngineTransportError extends ServiceUnavailableException, so it is excluded too. That is+ * correct rather than a gap: every site that builds one has already reported the death, and the+ * teardown latches on status, so a second report would change nothing.+ */+ it('does not re-classify an EngineTransportError from an inner catch', () => {+ const error = new EngineTransportError('Transport died during getChatById');++ expect(error).toBeInstanceOf(HttpException);+ expect(classify(error)).toBe(false);+ });+ });++ describe('a real transport death still classifies', () => {+ it.each([+ 'Protocol error (Runtime.callFunctionOn): Target closed',+ 'Protocol error (Page.navigate): Session closed. Most likely the page has been closed.',+ "Attempted to use detached Frame 'ABC'.",+ 'Execution context is not available in detached frame or worker "x" (are you using frame.evaluate after navigation?)',+ 'Connection closed',+ ])('%p', message => {+ expect(classify(new Error(message))).toBe(true);+ });++ it('still classifies a non-Error thrown value carrying the signature', () => {+ expect(classify('Target closed')).toBe(true);+ });++ // The one message-shaped exclusion that predates this: a per-command budget overrun is the+ // renderer being slow, not gone, and the next command may well succeed.+ it('still refuses a puppeteer protocol timeout', () => {+ expect(+ classify(+ new Error(+ "Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.",+ ),+ ),+ ).toBe(false);+ });+ });+});diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex 9ff25c745..9746ad7aa 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -1,5 +1,6 @@import * as qrcode from 'qrcode';import * as path from 'path';+import { HttpException } from '@nestjs/common';import { Client, LocalAuth, WAState } from 'whatsapp-web.js';import {type AccountRestriction,@@ -682,6 +683,23 @@ export class WwebjsLifecycle {/** 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+ // message carries caller-supplied text verbatim: MessageNotFoundError reads+ // `Message ${messageId} not found in chat ${chatId}`, and GroupNotFoundError, LabelNotFoundError,+ // ChannelNotFoundError and CallNotFoundError have the same shape. Matching the pattern against+ // one of those hands the CALLER the classifier. A request naming a messageId of "Target closed"+ // made its own 404 read as a transport death: the session was torn down and reconnected, and the+ // caller got a 503. The reactions read needs no role at all, so the lowest-privilege key could+ // do it at will.+ //+ // Excluding the class loses no real signal. Puppeteer and whatsapp-web.js throw plain Errors,+ // and a page-side throw arrives as one too (puppeteer-core rebuilds it in cdp/utils.js+ // createEvaluationError). It also settles the nested case: an EngineTransportError arriving from+ // an inner catch was already reported where it was built, and handlePuppeteerDeath latches on+ // status, so re-reporting would be a no-op regardless.+ if (error instanceof HttpException) {+ return false;+ }const message = error instanceof Error ? error.message : String(error);if (WwebjsLifecycle.PROTOCOL_TIMEOUT_PATTERN.test(message)) {return false;diff --git a/src/engine/adapters/wwebjs-lookup-failure.spec.ts b/src/engine/adapters/wwebjs-lookup-failure.spec.tsindex 39828cbdc..3e601c2fa 100644--- a/src/engine/adapters/wwebjs-lookup-failure.spec.ts+++ b/src/engine/adapters/wwebjs-lookup-failure.spec.ts@@ -1,4 +1,5 @@import type { Client } from 'whatsapp-web.js';+import { HttpException } from '@nestjs/common';import { WwebjsContacts } from './wwebjs-contacts';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { createLogger } from '../../common/services/logger.service';@@ -33,7 +34,11 @@ function makeContacts(client: Partial<Record<string, jest.Mock>>): {reported: string[];} {const reported: string[] = [];+ // Mirrors WwebjsLifecycle.isPageTransportError, including its HttpException exclusion: an error+ // this application built is never a dead page, and without the guard here the stub would classify+ // a domain 404 the real adapter no longer does.const isPageTransportError = (error: unknown): boolean =>+ !(error instanceof HttpException) &&PAGE_TRANSPORT_ERROR_PATTERN.test(error instanceof Error ? error.message : String(error));const host = {ensureReady: jest.fn(),