Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): tell the caller what WhatsApp Web threw on a failed send
Yudhi Armyndharisdb34e89ece82
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 264f3e412..efd62395b 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -106,7 +106,7 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel| `413` | Payload Too Large | Base64 or downloaded media exceeds the media byte cap (see §6.3) || `415` | Unsupported Media | The request has a body carrying a `Content-Encoding` other than `identity`; compressed request bodies are not accepted, as the aggregate body cap counts wire bytes || `429` | Too Many Requests | A rate limit was exceeded: the per-client-IP tiers, the ingress per-instance limit, or send pacing (body carries `code: 'SEND_PACING_LIMITED'` and `retryAfterSeconds`); honor `Retry-After` when present |-| `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |+| `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error; when WhatsApp Web itself threw during a whatsapp-web.js send or status post, the body carries `code: 'ENGINE_PAGE_ERROR'`, `pageError` (`name`, `message`) and, when the page could read it, the WhatsApp Web `build` || `501` | Not Implemented | The operation is not supported by the active engine (see the capability matrix, docs/29) || `502` | Bad Gateway | An engine transport failure (e.g. a dead Baileys socket; retryable), an upstream component returned something unusable (not retryable; each route section carries the exact wording), or, on a multi-node deployment, forwarding a session-scoped request to its owner node failed after the request may already have been sent, so a non-idempotent call must not be replayed blindly (see docs/13) || `503` | Service Unavailable | A dependency or the session is not ready (boot draining, a datastore down, the engine reconnecting, a media `url` fetch through the session's egress proxy failing before any response, whether the proxy or the target is at fault); retryable. On a multi-node deployment a forwarded request answers `503` only when the owner node was never reached, so the request was not carried out (see docs/13) |diff --git a/src/common/errors/engine-page.error.ts b/src/common/errors/engine-page.error.tsnew file mode 100644index 000000000..f0d28fef4--- /dev/null+++ b/src/common/errors/engine-page.error.ts@@ -0,0 +1,45 @@+import { InternalServerErrorException } from '@nestjs/common';++/** The readable part of a failure WhatsApp Web threw inside the page. */+export interface PageErrorSummary {+ name: string;+ message: string;+ build?: string;+}++/** Longest name or message the response body carries; the full summary stays on `cause` for the log. */+const FIELD_LIMIT = 200;++const cut = (text: string): string => (text.length > FIELD_LIMIT ? `${text.slice(0, FIELD_LIMIT)}...` : text);++/**+ * Thrown by the whatsapp-web.js adapter when WhatsApp Web's own code threw inside the page while+ * carrying out an operation (a send or a status post). It keeps the documented **HTTP 500** "engine+ * error" but, unlike an unmapped Error, tells the caller what WhatsApp Web said: `code`+ * `ENGINE_PAGE_ERROR`, the thrown `name` and `message`, and, when the page could read it, the+ * running WhatsApp Web `build`, which `message` also names.+ *+ * The raw captured error, with its stack and own properties, travels as `cause` for the server log+ * and never reaches the response body.+ */+export class EnginePageError extends InternalServerErrorException {+ constructor(summary: PageErrorSummary, raw: Error) {+ const name = cut(summary.name);+ const message = cut(summary.message);+ const build = summary.build ? cut(summary.build) : undefined;+ const reason = `${message ? `${name}: ${message}` : name}${build ? ` (build ${build})` : ''}`;+ super(+ {+ statusCode: 500,+ error: 'Internal Server Error',+ code: 'ENGINE_PAGE_ERROR',+ // The message names the build too: the message:failed hook and the bulk batch result carry+ // only this string, and the build is what tells a WhatsApp Web regression apart.+ message: `WhatsApp Web rejected the operation: ${reason}`,+ pageError: { name, message },+ ...(build ? { build } : {}),+ },+ { cause: raw },+ );+ }+}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex d2b7c2e11..2f9cc972d 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -6227,10 +6227,17 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-it('fails the read when WhatsApp Web could not read any contact', async () => {const evaluate = jest.fn().mockResolvedValue({ rows: [], failed: 3, firstError: 'x is not a function' });const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });-- await expect(adapter.getContacts()).rejects.toThrow(- 'WhatsApp Web could not read any unblocked contact (3 failed, 0 without an id, 0 blocked read): x is not a function',- );+ const logger = (adapter as unknown as { logger: { error: (m: string) => void } }).logger;+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined);+ const reason =+ 'WhatsApp Web could not read any unblocked contact (3 failed, 0 without an id, 0 blocked read): x is not a function';++ const failure = adapter.getContacts();+ await expect(failure).rejects.toThrow(reason);+ // The documented 500 carries its reason: a bare Error would answer Nest's context-free one.+ await expect(failure).rejects.toBeInstanceOf(InternalServerErrorException);+ // Nest does not log an HttpException, so the page-wide failure needs its own server log line.+ expect(errorSpy).toHaveBeenCalledWith(reason);expect(onDisconnected).not.toHaveBeenCalled();});diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex e724c01c2..605c8ba76 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -1,4 +1,5 @@import { type Client } from 'whatsapp-web.js';+import { InternalServerErrorException } from '@nestjs/common';import { Contact } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { userPart } from '../identity/wa-id';@@ -167,10 +168,13 @@ export class WwebjsContacts {// contacts: getContactModel skips getAlternateUserWid for a blocked contact, so a blocked row// still reads when that call is broken for everyone else.if ((unreadable > 0 && !contacts.some(c => !c.isBlocked)) || (contacts.length === 0 && skipped > 0)) {- throw new Error(+ const reason =`WhatsApp Web could not read any unblocked contact (${unreadable} failed, ${skipped} without an id, ` +- `${contacts.length} blocked read)${firstError ? `: ${firstError}` : ''}`,- );+ `${contacts.length} blocked read)${firstError ? `: ${firstError}` : ''}`;+ // Nest does not log an HttpException and the contact service logs nothing, so this line is the+ // only server-side trace of a page-wide failure.+ this.host.logger.error(reason);+ throw new InternalServerErrorException(reason);}if (skipped > 0) {this.host.logger.warn(`Skipped ${skipped} contact(s) without a serialized id`);diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.tsindex 9fe4ff84a..1e4755bf5 100644--- a/src/engine/adapters/wwebjs-host.ts+++ b/src/engine/adapters/wwebjs-host.ts@@ -3,6 +3,7 @@ import { type EngineEventCallbacks, type IncomingMessage } from '../interfaces/wimport { type createLogger } from '../../common/services/logger.service';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';+import { toCapturedPageError } from './wwebjs-lifecycle';/*** Shared host surface for the delegates extracted from WhatsAppWebJsAdapter (./wwebjs-groups,@@ -49,7 +50,8 @@ export async function withPage<T>(host: WwebjsEngineHost, context: string, op: (/*** 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.+ * signal, then rethrow the error with the caller's status unchanged (a failure WhatsApp Web threw in+ * the page keeps its 500 and only gains its reason, see toCapturedPageError).** 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@@ -58,14 +60,25 @@ export async function withPage<T>(host: WwebjsEngineHost, context: string, op: (* 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.+ * keep their `500` rather than a replayable `503`. 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;+ // A status post runs the same patched Client.sendMessage as a message send, so a failure WhatsApp+ // Web threw in the page reaches the caller with its reason. A no-op for every other error.+ const mapped = toCapturedPageError(error);+ if (mapped !== error) {+ // The mapped error is an HttpException, which Nest does not log, and the status path logs+ // nothing of its own: this is the one line that keeps the full in-page summary.+ host.logger.warn(`WhatsApp Web threw during ${context}`, {+ sessionId: host.config.sessionId,+ cause: (error as Error).message,+ });+ }+ throw mapped;}}diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex c6f568e2b..8fd0478b6 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -9,6 +9,7 @@ import {} from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EnginePageError } from '../../common/errors/engine-page.error';import { type createLogger } from '../../common/services/logger.service';import { DEFAULT_PUPPETEER_ARGS, MAX_TIMER_MS, withPinnedBrowserLocale } from '../../config/configuration';import { resolveWebVersionPin } from '../wa-web-version';@@ -76,6 +77,37 @@ export function isProtocolTimeout(error: unknown): boolean {*/export const CAPTURED_PAGE_ERROR_PREFIX = 'page threw ';+/** A summary field the patcher could not read, or read off a value that lacks it. */+const EMPTY_SUMMARY_FIELD = new Set(['', 'undefined', 'null', '(unreadable)']);++/**+ * Turn a captured page error into an {@link EnginePageError} that tells the caller what WhatsApp Web+ * threw; anything else, a summary that does not parse included, comes back unchanged. The thrown+ * value can be anything, so the name falls back to its constructor and the message to its string.+ */+export function toCapturedPageError(error: unknown): unknown {+ if (!(error instanceof Error) || !error.message.startsWith(CAPTURED_PAGE_ERROR_PREFIX)) return error;+ let info: Record<string, unknown>;+ try {+ info = JSON.parse(error.message.slice(CAPTURED_PAGE_ERROR_PREFIX.length)) as Record<string, unknown>;+ } catch {+ return error;+ }+ if (!info || typeof info !== 'object') return error;+ const pick = (...keys: string[]): string => {+ for (const key of keys) {+ const value = info[key];+ if (typeof value === 'string' && !EMPTY_SUMMARY_FIELD.has(value)) return value;+ }+ return '';+ };+ const build = pick('build');+ return new EnginePageError(+ { name: pick('name', 'ctor') || 'Error', message: pick('message', 'str'), ...(build ? { build } : {}) },+ 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 hangdiff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 6945cfa9a..8ca35faa2 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -24,6 +24,7 @@ import { buildVCard } from './vcard';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';import { type WwebjsEngineHost, withPage } from './wwebjs-host';+import { toCapturedPageError } from './wwebjs-lifecycle';/*** Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.@@ -349,7 +350,7 @@ export class WwebjsMessaging {throw new MessageNotFoundError(quotedMessageId);}if (!chatId.endsWith('@c.us') || !isNoLidForUserError(err)) {- throw err;+ throw toCapturedPageError(err);}this.resolvedSendIds.delete(chatId);const fresh = await this.resolveSendId(chatId);@@ -378,7 +379,7 @@ export class WwebjsMessaging {if (isNoLidForUserError(retryErr)) {throw new RecipientUnreachableError(chatId);}- throw retryErr;+ throw toCapturedPageError(retryErr);}}}diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsindex dd4fc606a..7646438e4 100644--- a/src/engine/adapters/wwebjs-profile.ts+++ b/src/engine/adapters/wwebjs-profile.ts@@ -28,8 +28,8 @@ export class WwebjsProfile {// here. It floors the Date to seconds itself, so the epoch-milliseconds the contract takes goes// straight into the Date.// Non-idempotent: each call mints a NEW server-side link, so a client replaying a 503 would- // create a second one. Report a dead page, keep the error as thrown (500). Same rule as- // createChannel; see reportPageDeath.+ // create a second one. Report a dead page and keep the 500. Same rule as createChannel; see+ // reportPageDeath.const link = await reportPageDeath(this.host, 'createCallLink', () =>this.client().createCallLink(new Date(startTime), type === 'video' ? 'video' : 'voice'),);diff --git a/src/engine/adapters/wwebjs-send-page-error.spec.ts b/src/engine/adapters/wwebjs-send-page-error.spec.tsindex f9a4dd18f..d29166e56 100644--- a/src/engine/adapters/wwebjs-send-page-error.spec.ts+++ b/src/engine/adapters/wwebjs-send-page-error.spec.ts@@ -1,5 +1,11 @@import * as path from 'path';-import { CAPTURED_PAGE_ERROR_PREFIX, WwebjsLifecycle } from './wwebjs-lifecycle';+import type { Client } from 'whatsapp-web.js';+import { CAPTURED_PAGE_ERROR_PREFIX, WwebjsLifecycle, toCapturedPageError } from './wwebjs-lifecycle';+import { EnginePageError } from '../../common/errors/engine-page.error';+import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';+import { createLogger } from '../../common/services/logger.service';+import { WwebjsMessaging } from './wwebjs-messaging';+import { type WwebjsEngineHost, reportPageDeath } from './wwebjs-host';/*** A send failure scripts/patch-wwebjs-send-error.js captured inside the page quotes WhatsApp Web's@@ -43,3 +49,158 @@ describe('a send failure captured inside the page', () => {expect(isPageTransportError(new Error(`Session closed; ${CAPTURED_PAGE_ERROR_PREFIX}{}`))).toBe(true);});});++describe('the reason a captured page failure gives the caller', () => {+ const summary = {+ build: '2.3000.1',+ ctor: 'MediaFileTooLarge',+ str: 'MediaFileTooLarge: too big',+ name: 'MediaFileTooLarge',+ message: 'too big',+ stack: 'MediaFileTooLarge: too big\n at send (app.js:1:1)',+ code: '413',+ };++ it('is a 500 EnginePageError naming what WhatsApp Web threw, with no stack in the body', () => {+ const raw = captured(summary);+ const err = toCapturedPageError(raw) as EnginePageError;++ expect(err).toBeInstanceOf(EnginePageError);+ expect(err.getStatus()).toBe(500);+ expect(err.message).toBe('WhatsApp Web rejected the operation: MediaFileTooLarge: too big (build 2.3000.1)');+ expect(err.getResponse()).toEqual({+ statusCode: 500,+ error: 'Internal Server Error',+ code: 'ENGINE_PAGE_ERROR',+ message: 'WhatsApp Web rejected the operation: MediaFileTooLarge: too big (build 2.3000.1)',+ pageError: { name: 'MediaFileTooLarge', message: 'too big' },+ build: '2.3000.1',+ });+ expect(JSON.stringify(err.getResponse())).not.toContain('app.js');+ // The full summary stays reachable for the server log.+ expect(err.cause).toBe(raw);+ });++ it('falls back to the constructor and string of a thrown value that is not an Error', () => {+ const err = toCapturedPageError(+ captured({ build: '(unreadable)', ctor: 'String', str: 'boom', name: 'undefined', message: 'undefined' }),+ ) as EnginePageError;++ expect(err.getResponse()).toMatchObject({ pageError: { name: 'String', message: 'boom' } });+ expect(err.getResponse()).not.toHaveProperty('build');+ expect(err.message).toBe('WhatsApp Web rejected the operation: String: boom');+ });++ it('cuts a long name and message', () => {+ const err = toCapturedPageError(captured({ name: 'N'.repeat(500), message: 'm'.repeat(500) })) as EnginePageError;+ const body = err.getResponse() as { pageError: { name: string; message: string } };++ expect(body.pageError.name.length).toBeLessThanOrEqual(203);+ expect(body.pageError.message.length).toBeLessThanOrEqual(203);+ });++ it('leaves everything that is not a parseable capture untouched', () => {+ const malformed = new Error(`${CAPTURED_PAGE_ERROR_PREFIX}{not json`);+ const plain = new Error('Evaluation failed: Error: something else broke');+ for (const value of [malformed, plain, 'text', undefined]) {+ expect(toCapturedPageError(value)).toBe(value);+ }+ });++ const makeMessaging = (): {+ messaging: WwebjsMessaging;+ client: { sendMessage: jest.Mock };+ host: WwebjsEngineHost;+ } => {+ const client = { sendMessage: jest.fn() };+ const host = {+ ensureReady: jest.fn(),+ ensureNotChannelRecipient: jest.fn(),+ getClient: () => client as unknown as Client,+ logger: createLogger('wwebjs-send-page-error.spec'),+ config: {},+ getNumberId: jest.fn(),+ capInboundMediaFor: jest.fn(),+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ return { messaging: new WwebjsMessaging(host), client, host };+ };++ it('reaches the caller of a message send', async () => {+ const { messaging, client } = makeMessaging();+ client.sendMessage.mockRejectedValue(captured(summary));++ await expect(messaging.sendTextMessage('[email protected]', 'hi')).rejects.toBeInstanceOf(EnginePageError);+ });++ it('reaches the caller when the send fails on the LID retry', async () => {+ const { messaging, client, host } = makeMessaging();+ (host.getNumberId as jest.Mock).mockResolvedValueOnce(undefined).mockResolvedValueOnce('999@lid');+ client.sendMessage+ .mockRejectedValueOnce(new Error('Evaluation failed: Error: No LID for user'))+ .mockRejectedValueOnce(captured(summary));++ await expect(messaging.sendTextMessage('[email protected]', 'hi')).rejects.toBeInstanceOf(EnginePageError);+ expect(client.sendMessage).toHaveBeenCalledTimes(2);+ });++ it('does not take over the recipient remap of a plain No LID failure', async () => {+ const { messaging, client, host } = makeMessaging();+ (host.getNumberId as jest.Mock).mockResolvedValue(undefined);+ client.sendMessage.mockRejectedValue(new Error('Evaluation failed: Error: No LID for user'));++ await expect(messaging.sendTextMessage('[email protected]', 'hi')).rejects.toBeInstanceOf(RecipientUnreachableError);+ });++ it('reaches the caller of a status post', async () => {+ const report = jest.fn();+ const host = {+ logger: { warn: jest.fn() },+ config: {},+ isPageTransportError: () => false,+ reportIfPageTransportError: report,+ } as unknown as WwebjsEngineHost;+ const raw = captured(summary);++ await expect(reportPageDeath(host, 'postTextStatus', () => Promise.reject(raw))).rejects.toBeInstanceOf(+ EnginePageError,+ );+ expect(report).toHaveBeenCalledWith(raw, 'postTextStatus');+ });++ it('leaves the full summary of a status post failure in the server log', async () => {+ // The EnginePageError is an HttpException, which Nest does not log, and the status path logs+ // nothing of its own: without this line the stack and own properties reach no log at all.+ const warn = jest.fn();+ const host = {+ logger: { warn },+ config: { sessionId: 'sess-1' },+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ const raw = captured(summary);++ await expect(reportPageDeath(host, 'postTextStatus', () => Promise.reject(raw))).rejects.toBeInstanceOf(+ EnginePageError,+ );+ expect(warn).toHaveBeenCalledWith('WhatsApp Web threw during postTextStatus', {+ sessionId: 'sess-1',+ cause: raw.message,+ });+ });++ it('logs nothing of its own for an error it passes through unchanged', async () => {+ const warn = jest.fn();+ const host = {+ logger: { warn },+ config: { sessionId: 'sess-1' },+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ const plain = new Error('boom');++ await expect(reportPageDeath(host, 'postTextStatus', () => Promise.reject(plain))).rejects.toBe(plain);+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.tsindex ff868d203..e132d8e4b 100644--- a/src/engine/adapters/wwebjs-status.ts+++ b/src/engine/adapters/wwebjs-status.ts@@ -147,7 +147,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.- // Non-idempotent: report a dead page, but keep the error as thrown. See reportPageDeath.+ // Non-idempotent: report a dead page and keep the 500 (a failure WhatsApp Web threw in the page+ // gains its reason). See reportPageDeath.const msg = await reportPageDeath(this.host, 'postTextStatus', () =>this.client().sendMessage('status@broadcast', text, {extra: {diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex b711027bf..837564ce7 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -19,6 +19,7 @@ import { SendPacingService, SEND_PACING_LIMITED } from './send-pacing.service';import { SessionOwnershipService } from '../session/session-ownership.service';import { HookManager } from '../../core/hooks';import { SsrfBlockedError } from '../../common/security/ssrf-guard';+import { EnginePageError } from '../../common/errors/engine-page.error';/** Regression lock for the terminal-status decision (cancel-clobber + stopOnError overwrite bugs). */describe('resolveFinalBatchStatus', () => {@@ -744,6 +745,43 @@ describe('BulkMessageService.processBatch', () => {);});+ it('logs the in-page summary of a page error; the stored result and the hook keep only its reason and build', async () => {+ const batch = makeBatch(1);+ repo.findOne.mockResolvedValue(batch);+ engine.sendTextMessage.mockRejectedValueOnce(+ new EnginePageError(+ { name: 'TypeError', message: 'x', build: '2.3000.1' },+ new Error('page threw {"build":"2.3000.1","stack":"at y"}'),+ ),+ );+ const warn = jest.spyOn((service as unknown as { logger: LoggerService }).logger, 'warn').mockImplementation();++ await runProcessBatch();++ expect(warn).toHaveBeenCalledWith(expect.stringContaining('page threw {"build":"2.3000.1"'));+ const result = batch.results[0];+ expect(result.status).toBe(BatchMessageStatus.FAILED);+ expect(result.error?.message).toBe('WhatsApp Web rejected the operation: TypeError: x (build 2.3000.1)');+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ error: 'WhatsApp Web rejected the operation: TypeError: x (build 2.3000.1)' }),+ expect.anything(),+ );+ });++ it('never logs the cause of a blocked media URL', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ const blocked = new SsrfBlockedError('blocked');+ blocked.cause = new Error('resolved to 10.0.0.1');+ engine.sendTextMessage.mockRejectedValueOnce(blocked);+ const warn = jest.spyOn((service as unknown as { logger: LoggerService }).logger, 'warn').mockImplementation();++ await runProcessBatch();++ expect(warn).toHaveBeenCalled();+ expect(warn.mock.calls.flat().join(' ')).not.toContain('10.0.0.1');+ });+it('does NOT fire message:failed when the gate blocks a bulk item (a block is a moderation decision, not a delivery failure)', async () => {repo.findOne.mockResolvedValue(makeBatch(1));hookManager.execute.mockResolvedValueOnce({ continue: false, data: {} }); // block message 0diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 2e6003294..bbec8f49c 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -571,7 +571,15 @@ export class BulkMessageService implements OnApplicationBootstrap {);}- this.logger.warn(`Batch ${batch.batchId}: Failed message ${i + 1} to ${msg.chatId}: ${sanitized.message}`);+ // The log alone carries the cause: an EnginePageError keeps the full in-page summary (stack,+ // own properties) there, and this batch runs in the background, so no other log sees it.+ const cause =+ !(error instanceof SsrfBlockedError) && error instanceof Error && error.cause instanceof Error+ ? ` (cause: ${error.cause.message})`+ : '';+ this.logger.warn(+ `Batch ${batch.batchId}: Failed message ${i + 1} to ${msg.chatId}: ${sanitized.message}${cause}`,+ );if (batch.options.stopOnError) {batch.status = BatchStatus.FAILED;diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 2c29d448f..6d4a26f35 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -14,6 +14,7 @@ import { TemplateService } from '../template/template.service';import { Template } from '../template/entities/template.entity';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { SendPacingService } from './send-pacing.service';+import { EnginePageError } from '../../common/errors/engine-page.error';import type { MessageProjector } from '../session/message-projector.service';/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */@@ -320,6 +321,28 @@ describe('MessageSendService', () => {);});+ it('logs the full in-page summary of a page failure while the caller and hooks get its reason and build', async () => {+ const warn = jest.spyOn(+ (service as unknown as { logger: { warn: (...args: unknown[]) => void } }).logger,+ 'warn',+ );+ const raw = new Error('page threw {"build":"2.3000.1","name":"TypeError","message":"x","stack":"at y"}');+ const pageError = new EnginePageError({ name: 'TypeError', message: 'x', build: '2.3000.1' }, raw);+ mockEngine.sendTextMessage.mockRejectedValueOnce(pageError);++ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toBe(pageError);++ expect(warn).toHaveBeenCalledWith(+ 'Send failed in the engine (text)',+ expect.objectContaining({ cause: raw.message }),+ );+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ error: 'WhatsApp Web rejected the operation: TypeError: x (build 2.3000.1)' }),+ expect.anything(),+ );+ });+it('does not log a client-fault send failure', async () => {const warn = jest.spyOn((service as unknown as { logger: { warn: (...args: unknown[]) => void } }).logger,diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 6afe93fe4..7dfe2b69c 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -206,6 +206,8 @@ export class MessageSendService {chatId: message.chatId,messageId: message.id,error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),+ // An EnginePageError keeps the full in-page summary (stack, own properties) here only.+ ...(error instanceof Error && error.cause instanceof Error ? { cause: error.cause.message } : {}),});}await this.saveFailedMessage(message);diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.tsindex a36ea2a82..6f48554a7 100644--- a/src/modules/message/send-pacing.service.spec.ts+++ b/src/modules/message/send-pacing.service.spec.ts@@ -6,6 +6,7 @@ import {ServiceUnavailableException,} from '@nestjs/common';import { SendPacingService, SEND_PACING_LIMITED, countsTowardSendBreaker } from './send-pacing.service';+import { EnginePageError } from '../../common/errors/engine-page.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';@@ -601,6 +602,10 @@ describe('countsTowardSendBreaker', () => {['a WhatsApp refusal (403 EngineRefusedError)', new EngineRefusedError('not allowed to send here')],['a raw engine error', new Error('ack error 500')],['a server-side fault', new InternalServerErrorException('boom')],+ [+ 'a failure WhatsApp Web threw in the page (500 EnginePageError)',+ new EnginePageError({ name: 'TypeError', message: 'x' }, new Error('page threw {}')),+ ],])('counts %s', (_label, error) => {expect(countsTowardSendBreaker(error)).toBe(true);});