Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): answer 404 for a picture write to an unknown group
Yudhi Armyndharisdf9fda193060
diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 0bf6e1a29..98a9e4bc8 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -447,20 +447,49 @@ export class BaileysGroups {this.host.ensureReady();// Same socket call as the own-account picture, addressed at the group JID.const { data } = await resolveMediaBuffer(media, this.host.sessionProxyUrl());- // Not groupWrite: the w:profile:picture IQ goes to the server with the group as `target`, so a- // 404 there is not known to mean the group is gone (on a removal it may mean "no picture").- await mapServerRefusal('Setting the group picture', () =>+ await this.pictureWrite(groupId, 'Setting the group picture', () =>this.confirmed(this.sock().updateProfilePicture(groupId, data), 'the group picture change'),);}async deleteGroupPicture(groupId: string): Promise<void> {this.host.ensureReady();- await mapServerRefusal('Removing the group picture', () =>+ await this.pictureWrite(groupId, 'Removing the group picture', () =>this.confirmed(this.sock().removeProfilePicture(groupId), 'the group picture removal'),);}+ /**+ * Not groupWrite: the w:profile:picture IQ goes to the server with the group as `target`, so a+ * 404 there is not known to mean the group is gone (on a removal it may mean "no picture"). A+ * refusal is therefore checked against the group metadata, and only a metadata item-not-found (404)+ * answers 404; a group the account left or was removed from (401/403) stays a 403 refusal, as in+ * groupWrite. The extra query is paid on the refusal path alone.+ */+ private async pictureWrite(groupId: string, operation: string, op: () => Promise<void>): Promise<void> {+ try {+ await mapServerRefusal(operation, op);+ } catch (err) {+ if (err instanceof EngineRefusedError) {+ // Inside the chain so a socket torn down meanwhile (sock() throwing) is a failed lookup too.+ const lookupCode = await Promise.resolve()+ .then(() =>+ withQueryDeadline(+ this.sock().groupMetadata(groupId),+ this.queryBudgetMs,+ 'WhatsApp did not answer the group metadata query in time',+ ),+ )+ .then(+ () => undefined,+ (lookupErr: unknown) => refusedStatusCode(lookupErr),+ );+ if (lookupCode === 404) throw new GroupNotFoundError(groupId);+ }+ throw err;+ }+ }+async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {this.host.ensureReady();// A dedicated socket call, not a groupSettingUpdate option.diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 2871f3f7b..42732b65c 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4089,6 +4089,7 @@ describe('BaileysAdapter store-backed ops', () => {});describe('BaileysAdapter group management', () => {+ const PNG_INPUT = { mimetype: 'image/png', data: 'QUJD' };const META = {id: '[email protected]',subject: 'G',@@ -4410,8 +4411,46 @@ describe('BaileysAdapter group management', () => {await expect(call(adapter)).rejects.toBeInstanceOf(GroupNotFoundError);});- it('deleteGroupPicture keeps a 404 as a refusal: that IQ is not addressed to the group', async () => {+ it('deleteGroupPicture keeps a 404 as a refusal when the group resolves: that IQ is not addressed to it', async () => {fakeSock.removeProfilePicture.mockRejectedValueOnce(Object.assign(new Error('item-not-found'), { data: 404 }));+ fakeSock.groupMetadata.mockResolvedValueOnce(META);+ const adapter = await ready();+ await expect(adapter.deleteGroupPicture('[email protected]')).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it.each([+ ['setGroupPicture', (a: BaileysAdapter) => a.setGroupPicture('[email protected]', PNG_INPUT), 'updateProfilePicture'],+ ['deleteGroupPicture', (a: BaileysAdapter) => a.deleteGroupPicture('[email protected]'), 'removeProfilePicture'],+ ])('%s answers 404 for a refused write to a group that does not resolve', async (_name, call, sockMethod) => {+ (fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockRejectedValueOnce(+ Object.assign(new Error('forbidden'), { data: 403 }),+ );+ fakeSock.groupMetadata.mockRejectedValueOnce(Object.assign(new Error('item-not-found'), { data: 404 }));+ const adapter = await ready();+ await expect(call(adapter)).rejects.toBeInstanceOf(GroupNotFoundError);+ });++ // groupMetadata answers 401/403 for a group the account left or was removed from; the sibling+ // group writes answer 403 there, so the picture writes must not read it as an unknown group.+ it.each([401, 403])('a group picture refusal stays 403 when the metadata lookup answers %i', async code => {+ fakeSock.updateProfilePicture.mockRejectedValueOnce(Object.assign(new Error('forbidden'), { data: 403 }));+ fakeSock.groupMetadata.mockRejectedValueOnce(Object.assign(new Error('forbidden'), { data: code }));+ const adapter = await ready();+ await expect(adapter.setGroupPicture('[email protected]', PNG_INPUT)).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('a group picture refusal stays a refusal when the metadata lookup itself fails', async () => {+ fakeSock.removeProfilePicture.mockRejectedValueOnce(Object.assign(new Error('forbidden'), { data: 403 }));+ fakeSock.groupMetadata.mockRejectedValueOnce(new Error('Connection Closed'));+ const adapter = await ready();+ await expect(adapter.deleteGroupPicture('[email protected]')).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('a group picture refusal stays a refusal when the metadata lookup throws synchronously', async () => {+ fakeSock.removeProfilePicture.mockRejectedValueOnce(Object.assign(new Error('forbidden'), { data: 403 }));+ fakeSock.groupMetadata.mockImplementationOnce(() => {+ throw new TypeError("Cannot read properties of null (reading 'groupMetadata')");+ });const adapter = await ready();await expect(adapter.deleteGroupPicture('[email protected]')).rejects.toBeInstanceOf(EngineRefusedError);});