Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): require the OPERATOR role for the group invite-code read
Yudhi Armyndharisd66439db9653
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb40a400a..2ec8e82ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The group invite-code read, over REST or the MCP `GroupGetInviteCode` tool, requires the OPERATOR role; the code is a transferable join capability, so a VIEWER key can no longer extract it.- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 5614d6b4b..9ae45bf3d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2672,9 +2672,9 @@ Remove the group's picture. The account must be a group admin.#### GET /api/sessions/:sessionId/groups/:groupId/invite-code-Get the group invite code and full invite link.+Get the group invite code and full invite link. The code is a transferable join capability rather than plain read data, so it sits at OPERATOR, like the QR endpoint.-**Auth:** API key+**Auth:** API key (OPERATOR)**Path parameters**@@ -2694,7 +2694,7 @@ Get the group invite code and full invite link.}```-**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights required) · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)#### POST /api/sessions/:sessionId/groupsdiff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 16653370d..c3135190f 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -709,7 +709,7 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/groups/[email protected]" \#### GET /api/sessions/:sessionId/groups/:groupId/invite-code-Get the group invite code and full invite link.+Get the group invite code and full invite link (OPERATOR).```bashcurl -X GET "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/invite-code" \diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex ebeaf130e..dd1558380 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -213,7 +213,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime| `getPicture` | `getPicture(sessionId, groupId)` | The group's picture URL, or `null` when it has none. || `setPicture` | `setPicture(sessionId, groupId, body)` | Set the group's picture. **OPERATOR** || `deletePicture` | `deletePicture(sessionId, groupId)` | Remove the group's picture. **OPERATOR** |-| `inviteCode` | `inviteCode(sessionId, groupId)` | Get the group invite code and link. |+| `inviteCode` | `inviteCode(sessionId, groupId)` | Get the group invite code and link. **OPERATOR** || `revokeInviteCode` | `revokeInviteCode(sessionId, groupId)` | Revoke the current invite code and generate a new one. **OPERATOR** || `getMembershipRequests` | `getMembershipRequests(sessionId, groupId)` | List a group's pending join requests. Requires group admin. **OPERATOR** || `approveMembershipRequests` | `approveMembershipRequests(sessionId, groupId, participants?)` | Approve pending join requests; omit the list to approve all. **OPERATOR** |diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 6ecca629c..4f6dc9043 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -116,14 +116,17 @@ down on response close — any request can hit any instance.The surface is an **allowlist by construction** — a capability is exposed only if a`ToolDescriptor` is written for it. There is no automatic route reflection. Each tool-declares a `tier` (`read` | `write`) and, for writes, a required role.+declares a `tier` (`read` | `write`) and a `requiredRole` when the call warrants one: every+write carries its privilege level, and so does a read whose payload is itself a credential+(`GroupGetInviteCode`: the invite code is a transferable join capability, so it sits at+OPERATOR like the QR endpoint).| Domain | Read tools | Write tools || -------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------- || **Session** | list, get, chats, stats, presence | mark read/unread, typing, subscribe presence || **Message** | list, history, reactions | send text/image/video/audio/document/location/contact/sticker/template, reply, forward, react || **Contact** | list, get, check-number, resolve-phone, profile-picture | block, unblock |-| **Group** | list, get, invite-code | create, add participants, set subject, set description |+| **Group** | list, get, invite-code (OPERATOR) | create, add participants, set subject, set description || **Webhook** | list, get (read-only) | — || **Label** | list, get, chats for a label, labels on a chat | upsert, delete, add to chat, remove from chat || **Automation** | rules list, get | — |@@ -232,7 +235,9 @@ Guidelines:- **Reuse the response DTO** the matching REST controller uses (e.g.`WebhookResponseDto.fromEntity`, `SessionResponseDto.fromEntity`). Returning a raw entitycan leak fields the REST API deliberately strips.-- Mark writes with `tier: 'write'` and the appropriate `requiredRole`.+- Mark writes with `tier: 'write'` and the appropriate `requiredRole`. A read can carry a+ `requiredRole` too, when its payload is a credential for a system outside OpenWA rather+ than data (`GroupGetInviteCode` is the current example).- Use `sessionScoped: true` and a non-empty `sessionId` field for any per-session tool sothe scope check applies.- A snapshot test (`tool-registry.spec.ts`) locks the public tool-name set; update itdiff --git a/src/core/agent-tools/tools/group.tools.spec.ts b/src/core/agent-tools/tools/group.tools.spec.tsindex 2b5a72988..0d3a02a56 100644--- a/src/core/agent-tools/tools/group.tools.spec.ts+++ b/src/core/agent-tools/tools/group.tools.spec.ts@@ -1,7 +1,9 @@+import { ForbiddenException } from '@nestjs/common';import { invokeTool } from '../tool-invoker';import { groupTools } from './group.tools';import type { GroupService } from '../../../modules/group/group.service';import type { AuthService } from '../../../modules/auth/auth.service';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { ParticipantOperationResult } from '../../../engine/interfaces/whatsapp-engine.interface';function makeAuth(): Pick<AuthService, 'validateApiKey' | 'hasPermission'> {@@ -114,6 +116,24 @@ describe('groupTools execute handlers', () => {expect(out).toEqual({ inviteCode: 'abc123', inviteLink: 'https://chat.whatsapp.com/abc123' });});+ it('GroupGetInviteCode requires OPERATOR: a below-role key is refused before the service is called', async () => {+ // The invite code is a transferable join capability, so this read is gated at OPERATOR even+ // though the tool stays tier: 'read' (the tier says the call mutates nothing, not who may+ // extract a credential).+ const getGroupInviteCode = jest.fn().mockResolvedValue('abc123');+ const tool = groupTools({ getGroupInviteCode } as unknown as GroupService).find(+ t => t.name === 'GroupGetInviteCode',+ )!;+ expect(tool.requiredRole).toBe(ApiKeyRole.OPERATOR);++ const auth = makeAuth();+ (auth.hasPermission as jest.Mock).mockReturnValue(false);+ await expect(+ invokeTool(tool, { sessionId: 's1', groupId: '[email protected]' }, 'key', auth as unknown as AuthService),+ ).rejects.toBeInstanceOf(ForbiddenException);+ expect(getGroupInviteCode).not.toHaveBeenCalled();+ });+it('GroupCreate delegates to createGroup', async () => {const createGroup = jest.fn().mockResolvedValue({ id: 'g1' });const tool = groupTools({ createGroup } as unknown as GroupService).find(t => t.name === 'GroupCreate')!;diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex 582f46f66..03815cd24 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -37,8 +37,11 @@ export function groupTools(group: GroupService): AnyToolDescriptor[] {}),defineTool({name: 'GroupGetInviteCode',- description: 'Get the invite code and link for a group.',+ description:+ 'Get the invite code and link for a group. Requires OPERATOR role: the code is a ' ++ 'transferable join capability, not plain read data.',tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,sessionScoped: true,inputSchema: z.object({sessionId,diff --git a/src/modules/auth/role-coverage.spec.ts b/src/modules/auth/role-coverage.spec.tsindex 16d3a3cf1..5d0e96587 100644--- a/src/modules/auth/role-coverage.spec.ts+++ b/src/modules/auth/role-coverage.spec.ts@@ -3,6 +3,7 @@ import { REQUIRED_ROLE_KEY } from './decorators/auth.decorators';import { ApiKeyRole } from './entities/api-key.entity';import { IntegrationInstanceController } from '../integration/integration-instance.controller';import { RedriveController } from '../integration/redrive.controller';+import { GroupController } from '../group/group.controller';// The dashboard's client-side role (seeded from localStorage) is cosmetic UX only — the ACTUAL// authorization boundary is the backend @RequireRole guard. These assertions lock that the sensitive@@ -16,3 +17,14 @@ describe('admin controller role coverage (server-side authorization is the realexpect(Reflect.getMetadata(REQUIRED_ROLE_KEY, controller)).toBe(ApiKeyRole.ADMIN);});});++// A group invite code is a bearer capability, not read data: whoever holds the link joins the group+// on WhatsApp with no OpenWA credential at all, and that membership survives revoking the key that+// fetched the code. Both invite-code routes therefore sit at OPERATOR, like the QR endpoint: the+// reads whose payload is a credential for a system outside OpenWA's authority.+describe('group invite-code role coverage (the code is a capability, not read data)', () => {+ it.each(['getInviteCode', 'revokeInviteCode'] as const)('GroupController.%s requires the OPERATOR role', method => {+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, GroupController.prototype[method])).toBe(ApiKeyRole.OPERATOR);+ });+});diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex fd0cc4840..3766a6c54 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -510,7 +510,10 @@ export class GroupController {return { success: true, message: 'Group picture removed' };}+ // The invite code is a bearer join capability, not read data: it works outside OpenWA and keeps+ // working after the key that fetched it is revoked. OPERATOR, like the QR endpoint.@Get(':groupId/invite-code')+ @RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Get group invite code/link' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })diff --git a/test/group-invite-code-role.e2e-spec.ts b/test/group-invite-code-role.e2e-spec.tsnew file mode 100644index 000000000..76d0d0398--- /dev/null+++ b/test/group-invite-code-role.e2e-spec.ts@@ -0,0 +1,95 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import type { App } from 'supertest/types';+import { AppModule } from '../src/app.module';+import { applyGlobalValidation } from '../src/config/app-validation';+import { AuthService } from '../src/modules/auth/auth.service';+import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';+import { Session } from '../src/modules/session/entities/session.entity';+import { EngineRegistry } from '../src/engine/engine-registry.service';+import type { IWhatsAppEngine } from '../src/engine/interfaces/whatsapp-engine.interface';++/**+ * A group invite code is a transferable join capability, not read data: whoever holds the link+ * joins the group on WhatsApp with no OpenWA credential at all, and that membership survives+ * revoking the key that fetched the code. These tests pin the invite-code GET at the OPERATOR+ * role through the real HTTP stack, mirroring the QR endpoint: the reads whose payload is a+ * credential for a system outside OpenWA's authority are not VIEWER surface.+ *+ * The engine is a stub registered in the live EngineRegistry (the message-send e2e harness), so+ * the 403 asserts the guard refusal itself while the 200s prove the pass-through path: a+ * session-scoped VIEWER key is the least-credential holder that can otherwise reach the route.+ */+describe('Group invite-code role gate (e2e)', () => {+ let app: INestApplication<App>;+ let sessionId: string;+ let scopedViewerKey: string;+ let operatorKey: string;+ let adminKey: string;+ const groupId = '[email protected]';++ const engine = {+ getGroupInviteCode: jest.fn().mockResolvedValue('AbCdEf123456'),+ };++ const inviteCodeGet = (key: string) =>+ request(app.getHttpServer()).get(`/api/sessions/${sessionId}/groups/${groupId}/invite-code`).set('X-API-Key', key);++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();+ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));+ sessionId = (await sessionRepo.save(sessionRepo.create({ name: `e2e-invite-${Date.now()}` }))).id;++ app.get(EngineRegistry).set(sessionId, engine as unknown as IWhatsAppEngine);++ const authService = app.get(AuthService);+ scopedViewerKey = (+ await authService.createApiKey({+ name: 'e2e-invite-viewer',+ role: ApiKeyRole.VIEWER,+ allowedSessions: [sessionId],+ })+ ).rawKey;+ operatorKey = (await authService.createApiKey({ name: 'e2e-invite-operator', role: ApiKeyRole.OPERATOR })).rawKey;+ adminKey = (await authService.createApiKey({ name: 'e2e-invite-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore TypeORM multi-datasource teardown quirk */+ }+ });++ beforeEach(() => jest.clearAllMocks());++ it('refuses a session-scoped VIEWER key (403) without reaching the engine', async () => {+ const res = await inviteCodeGet(scopedViewerKey).expect(403);+ expect((res.body as { message?: string }).message).toContain('Required: operator');+ expect(engine.getGroupInviteCode).not.toHaveBeenCalled();+ });++ it('serves an OPERATOR key the code + link', async () => {+ const res = await inviteCodeGet(operatorKey).expect(200);+ expect(res.body).toEqual({+ inviteCode: 'AbCdEf123456',+ inviteLink: 'https://chat.whatsapp.com/AbCdEf123456',+ });+ expect(engine.getGroupInviteCode).toHaveBeenCalledWith(groupId);+ });++ it('serves an ADMIN key the code + link', async () => {+ await inviteCodeGet(adminKey).expect(200);+ });+});