Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): answer 403 when a non-admin revokes an invite code
Yudhi Armyndharisd5590001885f
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 0b5e86db4..6dcb78ee6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1406,12 +1406,48 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks// WA Web yields no code when the account is not an admin of the group. String(undefined)// turned that into the literal 'undefined', which the controller rendered as the link// "https://chat.whatsapp.com/undefined" and returned with a 200.- it.each([- ['getGroupInviteCode', 'getInviteCode', (a: WhatsAppWebJsAdapter) => a.getGroupInviteCode('[email protected]')],- ['revokeGroupInviteCode', 'revokeInvite', (a: WhatsAppWebJsAdapter) => a.revokeGroupInviteCode('[email protected]')],- ])('%s treats a missing code as a refusal, not the string "undefined"', async (_name, method, call) => {- const stub = jest.fn().mockResolvedValue(undefined);- await expect(call(readyAdapter(groupChat({ [method]: stub })))).rejects.toBeInstanceOf(EngineRefusedError);+ it('getGroupInviteCode treats a missing code as a refusal, not the string "undefined"', async () => {+ const getInviteCode = jest.fn().mockResolvedValue(undefined);+ await expect(readyAdapter(groupChat({ getInviteCode })).getGroupInviteCode('[email protected]')).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ describe('revokeGroupInviteCode', () => {+ const globals = globalThis as unknown as { window?: unknown };+ afterEach(() => delete globals.window);++ // Runs the in-page function in Node against a stubbed WA Web module registry, the way the page would.+ const revokeWith = (resetGroupInviteCode: jest.Mock): Promise<string> => {+ globals.window = {+ require: (m: string) =>+ m === 'WAWebWidFactory' ? { createWid: (id: string) => ({ id }) } : { resetGroupInviteCode },+ };+ const evaluate = jest.fn(<T, A>(fn: (arg: A) => Promise<T>, arg: A) => fn(arg));+ // What upstream's GroupChat.revokeInvite hands back for a refusal: the page error, its name lost.+ const revokeInvite = jest.fn().mockRejectedValue(new Error('Evaluation failed: ServerStatusCodeError'));+ return readyAdapter({ ...groupChat({ revokeInvite }), pupPage: { evaluate } }).revokeGroupInviteCode('[email protected]');+ };++ it('returns the new code', async () => {+ await expect(revokeWith(jest.fn().mockResolvedValue({ code: 'NEW123' }))).resolves.toBe('NEW123');+ });++ // A non-admin revoke is refused by WA Web with ServerStatusCodeError, which used to reach the+ // caller as a raw 500 while the route declares 403.+ it('answers a non-admin refusal with EngineRefusedError (403)', async () => {+ const refusal = Object.assign(new Error('403'), { name: 'ServerStatusCodeError' });+ await expect(revokeWith(jest.fn().mockRejectedValue(refusal))).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('treats a missing code as a refusal, not the string "undefined"', async () => {+ await expect(revokeWith(jest.fn().mockResolvedValue(undefined))).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('keeps any other page failure unchanged', async () => {+ const failure = new TypeError('resetGroupInviteCode is not a function');+ await expect(revokeWith(jest.fn().mockRejectedValue(failure))).rejects.toBe(failure);+ });});});diff --git a/src/engine/adapters/wwebjs-group-transport-death.spec.ts b/src/engine/adapters/wwebjs-group-transport-death.spec.tsindex c33f18464..b6b781ad5 100644--- a/src/engine/adapters/wwebjs-group-transport-death.spec.ts+++ b/src/engine/adapters/wwebjs-group-transport-death.spec.ts@@ -78,7 +78,7 @@ describe('group writes classify a dead page', () => {type ChatMethods = Record<string, jest.Mock>;- function makeGroups(chat: ChatMethods | Promise<never>, clientMethods: ChatMethods = {}) {+ function makeGroups(chat: ChatMethods | Promise<never>, clientMethods: Record<string, unknown> = {}) {const client = {info: {},getChatById:@@ -110,7 +110,6 @@ describe('group writes classify a dead page', () => {];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]'])],@@ -121,7 +120,14 @@ describe('group writes classify a dead page', () => {['rejectGroupMembershipRequests', g => g.rejectGroupMembershipRequests(GROUP, ['[email protected]'])],];- it.each([...CONVERGING, ...NON_CONVERGING_CHAT])(+ // revokeGroupInviteCode runs its write in-page through pupPage.evaluate, not a chat method.+ const REVOKE: [string, string, (g: WwebjsGroups) => Promise<unknown>] = [+ 'revokeGroupInviteCode',+ 'pupPage.evaluate',+ g => g.revokeGroupInviteCode(GROUP),+ ];++ it.each([...CONVERGING, ...NON_CONVERGING_CHAT, REVOKE])('%s answers a dead page during the group lookup with 503 before calling %s',async (op, _method, run) => {const lookup = Promise.reject(transportError);@@ -155,6 +161,23 @@ describe('group writes classify a dead page', () => {expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);});+ it('revokeGroupInviteCode reports a dead page in its write but keeps the raw error', async () => {+ const { groups, reportIfPageTransportError } = makeGroups(+ {},+ { pupPage: { evaluate: jest.fn().mockRejectedValue(transportError) } },+ );++ await expect(groups.revokeGroupInviteCode(GROUP)).rejects.toBe(transportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, 'revokeGroupInviteCode');+ });++ it('revokeGroupInviteCode leaves an ordinary failure untouched', async () => {+ const failure = new Error('Evaluation failed: x');+ const { groups } = makeGroups({}, { pupPage: { evaluate: jest.fn().mockRejectedValue(failure) } });++ await expect(groups.revokeGroupInviteCode(GROUP)).rejects.toBe(failure);+ });+it.each(MEMBERSHIP)('%s reports a dead page but keeps the raw error', async (op, run) => {const { groups, reportIfPageTransportError } = makeGroups({},diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 4eda8899d..47b067fca 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -38,6 +38,31 @@ export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): stringreturn readWid(candidate) ?? null;}+/**+ * GroupChat.revokeInvite, run IN-PAGE with the refusal handling its siblings already have. Upstream's+ * getInviteCode and the admin-only setters catch WA Web's `ServerStatusCodeError` (a non-admin+ * refusal) and resolve nothing; revokeInvite alone lets it reject, so a refusal reached the caller as+ * an opaque 500. Outside the page the error's name is no longer reliable (Puppeteer rebuilds it from+ * the page's constructor name), so the check has to happen here.+ */+export async function revokeInviteInPage(chatId: string): Promise<string | undefined> {+ const w = window as unknown as {+ require: (m: string) => {+ createWid: (id: string) => unknown;+ resetGroupInviteCode: (wid: unknown) => Promise<{ code?: string } | undefined>;+ };+ };+ try {+ const res = await w+ .require('WAWebGroupQueryJob')+ .resetGroupInviteCode(w.require('WAWebWidFactory').createWid(chatId));+ return res?.code;+ } catch (err) {+ if ((err as Error | undefined)?.name === 'ServerStatusCodeError') return undefined;+ throw err;+ }+}+/*** Group-domain operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public* methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures,@@ -359,8 +384,13 @@ export class WwebjsGroups {}async revokeGroupInviteCode(groupId: string): Promise<string> {- const chat = await this.requireGroupChat(groupId, 'revokeGroupInviteCode');- const newCode = await reportPageDeath(this.host, 'revokeGroupInviteCode', () => chat.revokeInvite());+ await this.requireGroupChat(groupId, 'revokeGroupInviteCode');+ const page = (+ this.client() as unknown as { pupPage: { evaluate: <T, A>(fn: (arg: A) => Promise<T>, arg: A) => Promise<T> } }+ ).pupPage;+ const newCode = await reportPageDeath(this.host, 'revokeGroupInviteCode', () =>+ page.evaluate(revokeInviteInPage, groupId),+ );if (!newCode) {throw new EngineRefusedError(`Failed to revoke the invite code for group ${groupId} — admin rights required`);}