Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): classify a dead page in group writes
Yudhi Armyndharis384fbc1ae464
diff --git a/src/engine/adapters/wwebjs-group-transport-death.spec.ts b/src/engine/adapters/wwebjs-group-transport-death.spec.tsindex 6fa3613e1..681d4b1f9 100644--- a/src/engine/adapters/wwebjs-group-transport-death.spec.ts+++ b/src/engine/adapters/wwebjs-group-transport-death.spec.ts@@ -3,6 +3,7 @@ import { WwebjsGroups } from './wwebjs-groups';import { createLogger } from '../../common/services/logger.service';import { type WwebjsEngineHost } from './wwebjs-host';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';/*** Both group reads reported a dead page and then rethrew the raw Puppeteer error, so the caller got@@ -61,3 +62,127 @@ describe('group reads distinguish a dead page from an ordinary failure', () => {expect(reportIfPageTransportError).not.toHaveBeenCalled();});});++/**+ * The group writes looked the chat up and then called it with no page classification at all, so a+ * dead page answered an opaque 500 and never fed the liveness path, while their routes document 503.+ * The lookup and the converging writes now answer 503 with the death signal; the writes that do not+ * converge report the death and keep their status, so a retrying client cannot apply them twice.+ */+describe('group writes classify a dead page', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');+ const GROUP = '[email protected]';+ const IMAGE = { data: 'aGVsbG8=', mimetype: 'image/png' };++ type ChatMethods = Record<string, jest.Mock>;++ function makeGroups(chat: ChatMethods | Promise<never>, clientMethods: ChatMethods = {}) {+ const client = {+ info: {},+ getChatById:+ chat instanceof Promise ? jest.fn(() => chat) : jest.fn().mockResolvedValue({ isGroup: true, ...chat }),+ ...clientMethods,+ };+ const reportIfPageTransportError = jest.fn();+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: (error: unknown) => error === transportError,+ reportIfPageTransportError,+ logger,+ config: {},+ } as unknown as WwebjsEngineHost;+ return { groups: new WwebjsGroups(host), reportIfPageTransportError };+ }++ // [public op, chat method it calls, invocation]+ const CONVERGING: [string, string, (g: WwebjsGroups) => Promise<unknown>][] = [+ ['getGroupInviteCode', 'getInviteCode', g => g.getGroupInviteCode(GROUP)],+ ['setGroupSubject', 'setSubject', g => g.setGroupSubject(GROUP, 's')],+ ['setGroupDescription', 'setDescription', g => g.setGroupDescription(GROUP, 'd')],+ ['setGroupMessagesAdminsOnly', 'setMessagesAdminsOnly', g => g.setGroupMessagesAdminsOnly(GROUP, true)],+ ['setGroupInfoAdminsOnly', 'setInfoAdminsOnly', g => g.setGroupInfoAdminsOnly(GROUP, true)],+ ['setGroupMemberAddMode', 'setAddMembersAdminsOnly', g => g.setGroupMemberAddMode(GROUP, 'admins')],+ ['deleteGroupPicture', 'deletePicture', g => g.deleteGroupPicture(GROUP)],+ ['setGroupPicture', 'setPicture', g => g.setGroupPicture(GROUP, IMAGE)],+ ];+ const NON_CONVERGING_CHAT: [string, string, (g: WwebjsGroups) => Promise<unknown>][] = [+ ['leaveGroup', 'leave', g => g.leaveGroup(GROUP)],+ ['revokeGroupInviteCode', 'revokeInvite', g => g.revokeGroupInviteCode(GROUP)],+ ['addParticipants', 'addParticipants', g => g.addParticipants(GROUP, ['[email protected]'])],+ ['removeParticipants', 'removeParticipants', g => g.removeParticipants(GROUP, ['[email protected]'])],+ ['promoteParticipants', 'promoteParticipants', g => g.promoteParticipants(GROUP, ['[email protected]'])],+ ['demoteParticipants', 'demoteParticipants', g => g.demoteParticipants(GROUP, ['[email protected]'])],+ ];+ const MEMBERSHIP: [string, (g: WwebjsGroups) => Promise<unknown>][] = [+ ['approveGroupMembershipRequests', g => g.approveGroupMembershipRequests(GROUP, ['[email protected]'])],+ ['rejectGroupMembershipRequests', g => g.rejectGroupMembershipRequests(GROUP, ['[email protected]'])],+ ];++ it.each([...CONVERGING, ...NON_CONVERGING_CHAT])(+ '%s answers a dead page during the group lookup with 503 before calling %s',+ async (op, _method, run) => {+ const lookup = Promise.reject(transportError);+ lookup.catch(() => undefined);+ const { groups, reportIfPageTransportError } = makeGroups(lookup);++ // The lookup rejects before a chat exists, so no write method can have run.+ await expect(run(groups)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledTimes(1);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ },+ );++ it.each(CONVERGING)('%s answers a dead page in %s with 503 and reports it', async (op, method, run) => {+ const { groups, reportIfPageTransportError } = makeGroups({+ [method]: jest.fn().mockRejectedValue(transportError),+ });++ await expect(run(groups)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledTimes(1);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ it.each(NON_CONVERGING_CHAT)('%s reports a dead page in %s but keeps the raw error', async (op, method, run) => {+ const { groups, reportIfPageTransportError } = makeGroups({+ [method]: jest.fn().mockRejectedValue(transportError),+ });++ await expect(run(groups)).rejects.toBe(transportError);+ expect(reportIfPageTransportError).toHaveBeenCalledTimes(1);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ it.each(MEMBERSHIP)('%s reports a dead page but keeps the raw error', async (op, run) => {+ const { groups, reportIfPageTransportError } = makeGroups(+ {},+ { [op]: jest.fn().mockRejectedValue(transportError) },+ );++ await expect(run(groups)).rejects.toBe(transportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ it.each(CONVERGING)('%s leaves an ordinary failure in %s untouched and unreported', async (_op, method, run) => {+ const failure = new Error('Evaluation failed: x');+ const { groups, reportIfPageTransportError } = makeGroups({ [method]: jest.fn().mockRejectedValue(failure) });++ await expect(run(groups)).rejects.toBe(failure);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });++ // reportPageDeath hands every failure to the host, whose own classifier ignores an ordinary one.+ it.each(NON_CONVERGING_CHAT)('%s leaves an ordinary failure in %s untouched', async (_op, method, run) => {+ const failure = new Error('Evaluation failed: x');+ const { groups } = makeGroups({ [method]: jest.fn().mockRejectedValue(failure) });++ await expect(run(groups)).rejects.toBe(failure);+ });++ it('still maps an empty participant batch to a refusal, not a death', async () => {+ const arity = new Error('Evaluation failed: expected at least 1 children');+ const { groups } = makeGroups({ removeParticipants: jest.fn().mockRejectedValue(arity) });++ await expect(groups.removeParticipants(GROUP, ['[email protected]'])).rejects.toThrow(EngineRefusedError);+ });+});diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 71ade78b0..c32a6b260 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -18,7 +18,7 @@ import { EngineNotSupportedError } from '../../common/errors/engine-not-supporteimport { 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 { type WwebjsEngineHost, withPage, reportPageDeath } from './wwebjs-host';import { isProtocolTimeout } from './wwebjs-lifecycle';/**@@ -187,9 +187,9 @@ export class WwebjsGroups {}async addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {- const chat = await this.requireGroupChat(groupId);+ const chat = await this.requireGroupChat(groupId, 'addParticipants');const participantIds = participants.map(toParticipantWid);- const raw = await chat.addParticipants(participantIds);+ const raw = await reportPageDeath(this.host, 'addParticipants', () => chat.addParticipants(participantIds));// whatsapp-web.js reports a batch-level refusal (no admin rights, empty group) by RESOLVING a// plain reason string (GroupChat.js:106-107,128-130) instead of throwing — surface it as a// refusal, not a success.@@ -246,7 +246,7 @@ export class WwebjsGroups {groupId: string,participants: string[],): Promise<ParticipantOperationResult[]> {- const chat = await this.requireGroupChat(groupId);+ const chat = await this.requireGroupChat(groupId, op);const participantIds = participants.map(toParticipantWid);const res = await this.runParticipantBatch(op, groupId, chat, participantIds);if (res?.status !== 200) {@@ -280,7 +280,7 @@ export class WwebjsGroups {participantIds: string[],): Promise<{ status?: number; matched?: unknown }> {try {- return await chat[op](participantIds);+ return await reportPageDeath(this.host, op, () => chat[op](participantIds));} catch (error) {if (/expected at least 1 children/.test((error as Error)?.message ?? '')) {throw new EngineRefusedError(`${op}: none of the requested participants is a member of group ${groupId}`);@@ -313,35 +313,35 @@ export class WwebjsGroups {}async leaveGroup(groupId: string): Promise<void> {- const chat = await this.requireGroupChat(groupId);- await chat.leave();+ const chat = await this.requireGroupChat(groupId, 'leaveGroup');+ await reportPageDeath(this.host, 'leaveGroup', () => chat.leave());}async setGroupSubject(groupId: string, subject: string): Promise<void> {- const chat = await this.requireGroupChat(groupId);+ const chat = await this.requireGroupChat(groupId, 'setGroupSubject');// GroupChat.setSubject resolves false when WA Web rejects the change (e.g. the account lacks// admin rights; index.d.ts:1982) instead of throwing — surface the refusal, not a false success.- const ok = await chat.setSubject(subject);+ const ok = await withPage(this.host, 'setGroupSubject', () => chat.setSubject(subject));if (!ok) {throw new EngineRefusedError(`Failed to set the subject for group ${groupId} — admin rights required`);}}async setGroupDescription(groupId: string, description: string): Promise<void> {- const chat = await this.requireGroupChat(groupId);+ const chat = await this.requireGroupChat(groupId, 'setGroupDescription');// Same discarded-boolean contract as setSubject (index.d.ts:1984).- const ok = await chat.setDescription(description);+ const ok = await withPage(this.host, 'setGroupDescription', () => chat.setDescription(description));if (!ok) {throw new EngineRefusedError(`Failed to set the description for group ${groupId} — admin rights required`);}}async getGroupInviteCode(groupId: string): Promise<string> {- const chat = await this.requireGroupChat(groupId);+ const chat = await this.requireGroupChat(groupId, 'getGroupInviteCode');// Typed Promise<string>, but WA Web yields nothing when the account is not an admin of the// group — and String(undefined) is the literal 'undefined', which the caller renders as the// link "https://chat.whatsapp.com/undefined". Same refusal contract as setDescription.- const inviteCode = await chat.getInviteCode();+ const inviteCode = await withPage(this.host, 'getGroupInviteCode', () => chat.getInviteCode());if (!inviteCode) {throw new EngineRefusedError(`Failed to get the invite code for group ${groupId} — admin rights required`);}@@ -350,8 +350,8 @@ export class WwebjsGroups {}async revokeGroupInviteCode(groupId: string): Promise<string> {- const chat = await this.requireGroupChat(groupId);- const newCode = await chat.revokeInvite();+ const chat = await this.requireGroupChat(groupId, 'revokeGroupInviteCode');+ const newCode = await reportPageDeath(this.host, 'revokeGroupInviteCode', () => chat.revokeInvite());if (!newCode) {throw new EngineRefusedError(`Failed to revoke the invite code for group ${groupId} — admin rights required`);}@@ -455,10 +455,14 @@ export class WwebjsGroups {return groupId;}- /** Resolve a group chat or throw — the shared preamble of the group settings writes. */- private async requireGroupChat(groupId: string): Promise<GroupChat> {+ /**+ * Resolve a group chat or throw: the shared preamble of the group settings writes. The lookup is a+ * read that runs before any write, so a dead page answers 503 with the death signal even for the+ * non-idempotent callers: nothing has been applied yet. `context` names the caller's operation.+ */+ private async requireGroupChat(groupId: string, context: string): Promise<GroupChat> {this.host.ensureReady();- const chat = await this.client().getChatById(groupId);+ const chat = await withPage(this.host, context, () => this.client().getChatById(groupId));// getChatById RESOLVES undefined for an unknown id (wwebjs does not throw): unknown id and a// non-group id are the same client-facing outcome — there is no such group (404, not a 500).if (!chat?.isGroup) {@@ -469,10 +473,12 @@ export class WwebjsGroups {// Set "only admins can send messages" (announce)async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);+ const groupChat = await this.requireGroupChat(groupId, 'setGroupMessagesAdminsOnly');// Resolves false instead of throwing when the account lacks admin rights (GroupChat.js:503) —// surface that as an error rather than a silent no-op.- const ok = await groupChat.setMessagesAdminsOnly(adminsOnly);+ const ok = await withPage(this.host, 'setGroupMessagesAdminsOnly', () =>+ groupChat.setMessagesAdminsOnly(adminsOnly),+ );if (!ok) {throw new EngineRefusedError(`Failed to update the messages-admins-only setting for group ${groupId} — admin rights required`,@@ -481,17 +487,19 @@ export class WwebjsGroups {}async setGroupPicture(groupId: string, media: MediaInput): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);+ const groupChat = await this.requireGroupChat(groupId, 'setGroupPicture');+ // Loaded outside the page guard: a media fetch failing with "connection closed" is not a dead page.+ const picture = await toMessageMedia(media, this.host.config.proxy?.url);// GroupChat.setPicture, NOT Client.setProfilePicture — the latter targets the own account.- const ok = await groupChat.setPicture(await toMessageMedia(media, this.host.config.proxy?.url));+ const ok = await withPage(this.host, 'setGroupPicture', () => groupChat.setPicture(picture));if (!ok) {throw new EngineRefusedError(`Failed to set the picture for group ${groupId} — admin rights required`);}}async deleteGroupPicture(groupId: string): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);- const ok = await groupChat.deletePicture();+ const groupChat = await this.requireGroupChat(groupId, 'deleteGroupPicture');+ const ok = await withPage(this.host, 'deleteGroupPicture', () => groupChat.deletePicture());if (!ok) {throw new EngineRefusedError(`Failed to delete the picture for group ${groupId} — admin rights required`);}@@ -501,8 +509,10 @@ export class WwebjsGroups {// own GroupChat setter, and it is inverted relative to our neutral vocabulary: adminsOnly=true// means mode 'admins'.async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);- const ok = await groupChat.setAddMembersAdminsOnly(mode === 'admins');+ const groupChat = await this.requireGroupChat(groupId, 'setGroupMemberAddMode');+ const ok = await withPage(this.host, 'setGroupMemberAddMode', () =>+ groupChat.setAddMembersAdminsOnly(mode === 'admins'),+ );if (!ok) {throw new EngineRefusedError(`Failed to update the member-add-mode setting for group ${groupId} — admin rights required`,@@ -512,8 +522,8 @@ export class WwebjsGroups {// Set "only admins can edit group info" (locked/restrict)async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);- const ok = await groupChat.setInfoAdminsOnly(adminsOnly);+ const groupChat = await this.requireGroupChat(groupId, 'setGroupInfoAdminsOnly');+ const ok = await withPage(this.host, 'setGroupInfoAdminsOnly', () => groupChat.setInfoAdminsOnly(adminsOnly));if (!ok) {throw new EngineRefusedError(`Failed to update the info-admins-only setting for group ${groupId} — admin rights required`,@@ -533,7 +543,7 @@ export class WwebjsGroups {// Resolved first, like every other group operation in this file. Without it an unknown id or a// non-group jid answered 200 with an empty list, which reads as "this group has no pending// requests" rather than "there is no such group"; Baileys answers the refusal.- await this.requireGroupChat(groupId);+ await this.requireGroupChat(groupId, 'getGroupMembershipRequests');return withPage(this.host, 'getGroupMembershipRequests', async () => {const raw = await this.client().getGroupMembershipRequests(groupId);// Raw page-context store objects: wids can arrive as {_serialized} OR {$1} (the #747@@ -585,7 +595,7 @@ export class WwebjsGroups {participants?: string[],): Promise<ParticipantOperationResult[]> {this.host.ensureReady();- const raw = await this.client()[op](groupId, {+ const options = {// Qualified like every other participant write in this file: the service blesses a bare phone// number, and the page maps requesterIds straight through `createWid` (Injected/Utils.js) —// which upstream itself never hands a bare number, appending '@c.us' first. Unqualified it@@ -593,7 +603,8 @@ export class WwebjsGroups {// input succeeded on Baileys. `null` still means every pending request.requesterIds: participants?.map(toParticipantWid) ?? null,sleep: [250, 500],- });+ };+ const raw = await reportPageDeath(this.host, op, () => this.client()[op](groupId, options));// {requesterId, error?, message} per requester; requesterId is a page-context value that can// arrive as a string or a wid object (both #747 spellings), so it goes through readWid too.// "No error field" is NOT sufficient for success: the page util's non-success RPC branch pushes