Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(groups): report an invite-code refusal instead of a 500 or a fake link
Yudhi Armyndharis28bccea2464e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 16ff8f4cc..2624d41a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A group invite code now says why it could not be read** — fetching one is admin-only, but the groups list returns every group the account belongs to whatever its role, so the request lands on ids the caller was just handed: Baileys let WhatsApp's refusal escape as a bare `500` (13 of 16 groups on the test account) while whatsapp-web.js stringified its missing result into `{"inviteCode":"undefined"}` and the link `https://chat.whatsapp.com/undefined` behind a `200` (53 of 101). Both engines now answer `403`, the same status the group writes have answered since they were fixed, and an unanswered query answers `503` instead of the codeless link `https://chat.whatsapp.com/`.- **A benign whatsapp-web.js rejection no longer reads like a crash** — the same un-awaited `framenavigated` re-injection that already logs at `WARN` when the page goes away was logged at `ERROR` in its other shape, where the navigation lands before WhatsApp Web has defined its module registry; it appears at the first boot after the pinned WhatsApp Web build moves under a warm profile, and the session reaches ready unaided.### Fixeddiff --git a/openapi.json b/openapi.jsonindex 57551ac5b..657de33f3 100644--- a/openapi.json+++ b/openapi.json@@ -4560,6 +4560,12 @@"responses": {"200": {"description": "Group invite code"+ },+ "403": {+ "description": "The engine refused the request — admin rights required for this group"+ },+ "503": {+ "description": "WhatsApp did not answer the invite-code query — retry shortly"}},"summary": "Get group invite code/link",@@ -4594,6 +4600,12 @@"responses": {"200": {"description": "New invite code generated"+ },+ "403": {+ "description": "The engine refused the request — admin rights required for this group"+ },+ "503": {+ "description": "WhatsApp did not answer the invite-code query — retry shortly"}},"summary": "Revoke group invite code and generate new one",diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 29f8e5642..162672ab6 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -11,6 +11,7 @@ import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { resolveMediaBuffer } from './baileys-messaging';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { type createLogger } from '../../common/services/logger.service';@@ -190,14 +191,30 @@ export class BaileysGroups {);}+ /**+ * Fetching an invite code is admin-only, but every group the account belongs to is listed by+ * getGroups regardless of role — so the refusal lands on ids the caller has just been handed.+ * Both failure shapes are surfaced rather than flattened into a code: a refusal rejects with a+ * Boom carrying the WA code (403, like every other admin-gated group operation), while an+ * unanswered query resolves undefined, which coalescing to '' turned into the meaningless link+ * "https://chat.whatsapp.com/" behind a 200.+ */async getGroupInviteCode(groupId: string): Promise<string> {this.host.ensureReady();- return (await this.sock().groupInviteCode(groupId)) ?? '';+ const code = await mapServerRefusal('Fetching the group invite code', () => this.sock().groupInviteCode(groupId));+ if (!code) {+ throw new EngineTransportError('WhatsApp did not answer the group invite-code query');+ }+ return code;}async revokeGroupInviteCode(groupId: string): Promise<string> {this.host.ensureReady();- return (await this.sock().groupRevokeInvite(groupId)) ?? '';+ const code = await mapServerRefusal('Revoking the group invite code', () => this.sock().groupRevokeInvite(groupId));+ if (!code) {+ throw new EngineTransportError('WhatsApp did not answer the group invite-code revocation');+ }+ return code;}/**diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 2e1266d43..b761da619 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -142,6 +142,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';const fakeStore = {@@ -3031,6 +3032,18 @@ describe('BaileysAdapter group management', () => {expect(await adapter.revokeGroupInviteCode('[email protected]')).toBe('NEW456');});+ // groupInviteCode resolves undefined only when the query went unanswered — a refusal rejects+ // with a Boom instead. Coalescing that to '' handed the controller an empty code, which it+ // rendered as the link "https://chat.whatsapp.com/" and returned with a 200.+ it.each([+ ['getGroupInviteCode', (a: BaileysAdapter) => a.getGroupInviteCode('[email protected]'), 'groupInviteCode'],+ ['revokeGroupInviteCode', (a: BaileysAdapter) => a.revokeGroupInviteCode('[email protected]'), 'groupRevokeInvite'],+ ])('%s reports an unanswered query instead of fabricating an empty code', async (_name, call, sockMethod) => {+ (fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockResolvedValueOnce(undefined);+ const adapter = await ready();+ await expect(call(adapter)).rejects.toBeInstanceOf(EngineTransportError);+ });+it('joinGroupViaInviteCode returns the joined group id (neutral dialect)', async () => {fakeSock.groupAcceptInvite.mockResolvedValue('[email protected]');const adapter = await ready();@@ -3123,7 +3136,11 @@ describe('BaileysAdapter group management', () => {(a: BaileysAdapter) => a.setGroupMemberAddMode('[email protected]', 'admins'),'groupMemberAddMode',],- ])('%s maps an admin-refused write to EngineRefusedError (403)', async (_name, call, sockMethod) => {+ // Reads, but refused by the same admin check: WhatsApp answers an invite-code query from a+ // non-admin with an error node, which reached the caller as a bare 500.+ ['getGroupInviteCode', (a: BaileysAdapter) => a.getGroupInviteCode('[email protected]'), 'groupInviteCode'],+ ['revokeGroupInviteCode', (a: BaileysAdapter) => a.revokeGroupInviteCode('[email protected]'), 'groupRevokeInvite'],+ ])('%s maps an admin-refused operation to EngineRefusedError (403)', async (_name, call, sockMethod) => {(fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockRejectedValueOnce(Object.assign(new Error('not-authorized'), { data: 401 }),);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 5a5151734..e8d89bf9c 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -860,6 +860,28 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks});});+ describe('group invite code', () => {+ const groupChat = (over: Record<string, unknown> = {}) => ({+ getChatById: jest.fn().mockResolvedValue({ isGroup: true, ...over }),+ });++ it('returns the code when WA Web supplies one', async () => {+ const getInviteCode = jest.fn().mockResolvedValue('ABC123');+ await expect(readyAdapter(groupChat({ getInviteCode })).getGroupInviteCode('[email protected]')).resolves.toBe('ABC123');+ });++ // 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);+ });+ });+describe('setGroupMemberAddMode', () => {const groupChat = (over: Record<string, unknown> = {}) => ({getChatById: jest.fn().mockResolvedValue({ isGroup: true, ...over }),diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 935beac06..0cc01c273 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -314,9 +314,15 @@ export class WwebjsGroups {if (!chat.isGroup) {throw new Error(`${groupId} is not a group`);}+ // 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 as unknown as GroupChat).getInviteCode();+ if (!inviteCode) {+ throw new EngineRefusedError(`Failed to get the invite code for group ${groupId} — admin rights required`);+ }this.host.logger.log(`Got invite code for group ${groupId}`);- return String(inviteCode);+ return inviteCode;}async revokeGroupInviteCode(groupId: string): Promise<string> {@@ -326,8 +332,11 @@ export class WwebjsGroups {throw new Error(`${groupId} is not a group`);}const newCode = await (chat as unknown as GroupChat).revokeInvite();+ if (!newCode) {+ throw new EngineRefusedError(`Failed to revoke the invite code for group ${groupId} — admin rights required`);+ }this.host.logger.log(`Revoked invite code for group ${groupId}, new code generated`);- return String(newCode);+ return newCode;}/**diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex ebdd314a3..237d2045f 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -13,6 +13,11 @@ import {import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';+// Reading an invite code is admin-only, but the groups list returns every group the account+// belongs to whatever its role — so these two statuses apply to ids the caller was just given.+const INVITE_CODE_403 = 'The engine refused the request — admin rights required for this group';+const INVITE_CODE_503 = 'WhatsApp did not answer the invite-code query — retry shortly';+// NOTE: the session→groups LIST lives on the SessionController at GET /sessions/:id/groups (it// registered first and owns the canonical narrow projection). A bare @Get() here would collide on// the same path pattern (/sessions/{x}/groups) and be shadowed, so this controller owns only the@@ -282,6 +287,8 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiResponse({ status: 200, description: 'Group invite code' })+ @ApiResponse({ status: 403, description: INVITE_CODE_403 })+ @ApiResponse({ status: 503, description: INVITE_CODE_503 })async getInviteCode(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {const inviteCode = await this.groupService.getGroupInviteCode(sessionId, groupId);return {@@ -297,6 +304,8 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiResponse({ status: 200, description: 'New invite code generated' })+ @ApiResponse({ status: 403, description: INVITE_CODE_403 })+ @ApiResponse({ status: 503, description: INVITE_CODE_503 })async revokeInviteCode(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {const newCode = await this.groupService.revokeGroupInviteCode(sessionId, groupId);return {