Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): stop reporting participants WhatsApp never touched

Yudhi Armyndharis71b7d2825d3c
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index a8a4cf3f8..585bac567 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5841,15 +5841,16 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
describe.each([['removeParticipants'], ['promoteParticipants'], ['demoteParticipants']])(
'%s (batch {status} is honored)',
op => {
- it('resolves one batch-confirmed entry per requested participant on {status: 200}', async () => {
+ it('falls back to batch-confirmed entries when the tree is unpatched (no matched marker)', async () => {
+ // Without scripts/patch-wwebjs-participant-arity.js the page reports only the batch status,
+ // so there is nothing per-participant to read. Keeping the old shape is the honest answer
+ // here; inventing an outcome would be the very defect this suite guards against.
const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200 }) });
const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
const results = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](
GROUP,
['628111', '[email protected]'],
);
- // wwebjs confirms the batch only — the entries must say so rather than claim an
- // individually-confirmed outcome the engine never reported.
expect(results).toEqual([
{
@@ -5866,6 +5867,71 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
]);
});
+ it('reports only the participants the page resolved to members', async () => {
+ const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200, matched: [true, false] }) });
+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
+ const results = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](
+ GROUP,
+ ['628111', '[email protected]'],
+ );
+ // The second id was dropped page-side, so WhatsApp never acted on it. Reporting it as a
+ // success is what #1220 was: a removal that never happened, confirmed to the caller.
+ expect(results).toEqual([
+ expect.objectContaining({ id: '[email protected]', success: true, status: 200 }),
+ expect.objectContaining({ id: '[email protected]', success: false, status: 404 }),
+ ]);
+ });
+
+ it('throws EngineRefusedError when the page resolved none of the requested participants', async () => {
+ const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200, matched: [false, false] }) });
+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
+ await expect(
+ (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](GROUP, [
+ '628111',
+ ]),
+ ).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
+ it('ignores a matched marker whose length does not match the request', async () => {
+ // A partially applied patch must degrade to the old behaviour rather than read undefined at
+ // an index and report a real participant as untouched.
+ const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200, matched: [true] }) });
+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
+ const results = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](
+ GROUP,
+ ['628111', '[email protected]'],
+ );
+ expect(results).toEqual([
+ expect.objectContaining({ success: true }),
+ expect.objectContaining({ success: true }),
+ ]);
+ });
+
+ it('translates the empty-batch page rejection into a refusal rather than a 500', async () => {
+ const chat = groupChat({
+ [op]: jest
+ .fn()
+ .mockRejectedValue(new Error('Evaluation failed: Error: expected at least 1 children, but found 0')),
+ });
+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
+ await expect(
+ (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](GROUP, ['628111']),
+ ).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
+ it('rethrows an unrecognised page failure instead of calling it a refusal', async () => {
+ // A dead transport must not be sold to the caller as a permissions problem — the Baileys
+ // adapter states the same rule for its own empty-results guard.
+ const boom = new Error('Protocol error (Runtime.callFunctionOn): Target closed');
+ const chat = groupChat({ [op]: jest.fn().mockRejectedValue(boom) });
+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
+ const err = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)
+ [op](GROUP, ['628111'])
+ .catch((e: unknown) => e);
+ expect(err).toBe(boom);
+ });
+
it('throws EngineRefusedError on a non-200 batch status instead of reporting success', async () => {
const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 403 }) });
const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index b42acdbd4..0e41a213e 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -232,13 +232,18 @@ export class WwebjsGroups {
}
/**
- * whatsapp-web.js remove/promote/demote resolve `{status: 200}` for the whole batch and reject on
- * a page-side failure (GroupChat.js:267-298,305-340,343-374) — there is no per-participant
- * breakdown to map: the page-side code even drops requested ids it can't find in the group and
- * still resolves 200, so a 200 confirms the batch, not any individual. A non-200 status is a
- * batch refusal. Within the per-participant shape the truthful report is one entry per requested
- * participant carrying the batch status, annotated so a consumer can tell it apart from an
- * individually-confirmed outcome (addParticipants); nothing per-participant exists to map.
+ * whatsapp-web.js resolves each requested id against the group's OWN participant collection and
+ * silently drops what it cannot find (GroupChat.js:289), then resolves `{status: 200}` for the
+ * whole batch. Reporting that as one success per requested participant claimed removals WhatsApp
+ * never performed, and an all-dropped batch reached a request builder that asserts at least one
+ * child — surfacing as an unnamed `500` (#1220).
+ *
+ * `scripts/patch-wwebjs-participant-arity.js` makes the page report `matched`, one boolean per
+ * requested id, and skip the call when nothing resolved. An absent or wrong-length `matched` means
+ * the installed tree is unpatched: keep the previous batch-confirmed shape rather than invent an
+ * outcome, mirroring the `eventsAttached` marker convention from the ready-sync patcher. A batch
+ * where nothing matched is a refusal of the operation itself (HTTP 403) via
+ * {@link assertParticipantResults}.
*/
private async runStatusOnlyParticipantOp(
op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',
@@ -251,16 +256,45 @@ export class WwebjsGroups {
throw new Error('Chat is not a group');
}
const participantIds = participants.map(toParticipantWid);
- const res = await (chat as unknown as GroupChat)[op](participantIds);
+ const res = await this.runParticipantBatch(op, groupId, chat as unknown as GroupChat, participantIds);
if (res?.status !== 200) {
throw new EngineRefusedError(`${op} refused for group ${groupId} (status ${res?.status ?? 'unknown'})`);
}
- return participantIds.map(id => ({
- id,
- success: true,
- status: 200,
- message: 'confirmed with the batch — wwebjs reports no per-participant outcome',
- }));
+ const matched = Array.isArray(res.matched) && res.matched.length === participantIds.length ? res.matched : null;
+ const results = participantIds.map((id, i) => {
+ const resolved = matched ? matched[i] === true : true;
+ return {
+ id,
+ success: resolved,
+ status: resolved ? 200 : 404,
+ message: resolved
+ ? 'confirmed with the batch — wwebjs reports no per-participant outcome'
+ : 'not a member of this group — WhatsApp was not asked to act on this participant',
+ };
+ });
+ return this.assertParticipantResults(op, groupId, results);
+ }
+
+ /**
+ * An unpatched tree hands the WA Web request builder an empty participant list when nothing
+ * resolved, and its repeated-field arity assertion rejects. Classify ONLY that: anything else — a
+ * closed target, a dead transport — must keep its own identity rather than be sold to the caller
+ * as a permissions problem, the same rule the Baileys adapter states for its empty-results guard.
+ */
+ private async runParticipantBatch(
+ op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',
+ groupId: string,
+ chat: GroupChat,
+ participantIds: string[],
+ ): Promise<{ status?: number; matched?: unknown }> {
+ try {
+ return await 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}`);
+ }
+ throw error;
+ }
}
/**