Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(group): expose group membership requests (list/approve/reject + group.join_request event)
Yudhi Armyndharisb6ccf49e47ce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6f7c910c..678fb5167 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Group membership requests: list, approve, reject, and a `group.join_request` event** — the join-approval queue wwebjs/Baileys both expose is now surfaced: `GET/POST .../groups/:groupId/membership-requests[/approve|/reject]` on both engines, plus a webhook/socket event when someone asks to join an administered group. Refs #1164 (discussion).+- **The media download route now serves media sent by the account** — `GET /messages/:chatId/:messageId/media` falls back to the inline copy stored on the message row when no archived file exists, which covers outbound messages (never archived) and inbound messages whose archived file retention has purged.### Changeddiff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex 303a6ab48..790505fef 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -107,6 +107,7 @@ const availableEventNames = ['group.join','group.leave','group.update',+ 'group.join_request','call.received','call.accepted','call.rejected',diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 3937d1854..e8b1aab4f 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -910,7 +910,7 @@ export interface EngineEventCallbacks {onMessageRevoked?: (message: RevokedMessage) => void;onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;- onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update+ onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update / group.join_requestonCall?: (event: IncomingCallEvent) => void; // incoming call ringing; rejectCall() while it ringsonHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatchonDisconnected?: (reason: string) => void; // recoverable -> reconnectdiff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex b08b12166..ade130779 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -429,6 +429,7 @@ CREATE TABLE webhooks ("group.join","group.leave","group.update",+ "group.join_request","call.received","call.accepted","call.rejected",diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2df797215..d7cf62e6c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2789,6 +2789,98 @@ Update group settings. Each present field maps to one engine call; absent fields**Errors:** `400` session is not started / empty patch / unknown body field · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the account is not a group admin (`memberAddMode` on whatsapp-web.js) · `501` `ephemeralSeconds` on the whatsapp-web.js engine (library limitation)+#### GET /api/sessions/:sessionId/groups/:groupId/membership-requests++List the pending join requests of a group with join-approval mode turned on — the queue the+`group.join_request` webhook/socket event announces. Admin-only on both engines: a non-admin read+is refused by WhatsApp, not silently emptied.++**Auth:** API key++**Path parameters**++| Name | Type | Description |+| --------- | ------ | ----------- |+| sessionId | string | Session ID |+| groupId | string | Group ID |++**Response** `200` — a bare array; fields the engine does not report are omitted rather than defaulted.++```json+[+ {+ "participantId": "[email protected]",+ "addedById": "[email protected]",+ "method": "invite_link",+ "requestedAt": 1754700000+ }+]+```++Each entry is a `GroupMembershipRequest`: `participantId` (the user asking to join), optional+`addedById` (who created the request — differs from the requester on a non-admin add), optional+`method` (`invite_link` | `non_admin_add` | `linked_group_join`), optional `requestedAt` (unix+seconds).++**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` the engine refused the read — admin rights required · `409` engine not ready · `503` WhatsApp did not answer within the request budget++#### POST /api/sessions/:sessionId/groups/:groupId/membership-requests/approve++Approve pending join requests — the named requesters, or **every** pending request when the body+names none. Approving an empty queue is a no-op that returns an empty `results` list. Deliberately+not paced by the cold-reachout governor: unlike `POST .../participants`, the people here asked for+the contact themselves. On whatsapp-web.js the engine pauses 250–500ms between requesters+(upstream anti-abuse pacing), so acting on a large queue is a proportionally long request.++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --------- | ------ | ----------- |+| sessionId | string | Session ID |+| groupId | string | Group ID |++**Request body** — `MembershipRequestActionDto`++| Field | Type | Required | Constraints | Description |+| ------------ | -------- | -------- | --------------------------------------------------------------------- | ------------------------------------------------------------- |+| participants | string[] | No | `@IsOptional`, `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Requester WhatsApp IDs. Omit to act on every pending request. |++```json+{ "participants": ["[email protected]"] }+```++**Response** `200`++Status is forced to `200` via `@HttpCode(HttpStatus.OK)` (overriding the POST default). `results`+carries the engine's per-participant outcome — the same `ParticipantOperationResult` contract as+the participant writes: a partial refusal does **not** fail the batch, while a batch that failed+for every **named** requester is a `403`.++```json+{+ "success": true,+ "message": "Membership requests approved",+ "results": [{ "id": "[email protected]", "success": true, "status": 200 }]+}+```++**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights / every named requester failed) · `409` engine not ready · `503` WhatsApp did not answer within the request budget++#### POST /api/sessions/:sessionId/groups/:groupId/membership-requests/reject++Reject pending join requests. Same body, response shape, batch-guard contract and error map as+`.../membership-requests/approve`; rejecting an empty queue is likewise a no-op.++```json+{+ "success": true,+ "message": "Membership requests rejected",+ "results": [{ "id": "[email protected]", "success": true, "status": 200 }]+}+```+### 6.4.5 Message TemplatesReusable message templates scoped to a session, with `{{variable}}` placeholders rendered at send time. All routes are nested under `/api/sessions/:sessionId/templates` and require an **OPERATOR** key. The `sessionId` is stored on the template but is **not** validated against an existing session in these handlers.@@ -3901,7 +3993,7 @@ Webhooks are configured per session and managed under `/api/sessions/:sessionId/Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.-The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Four are **Baileys only**, because whatsapp-web.js produces no callback behind them: `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js sees a call ring but never its outcome, so these three are accepted on subscribe and then simply never fire). See the per-event catalog below for engine scope.+The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `group.join_request`, `call.received`, `status.received`. All of them are actively dispatched by at least one engine — none is a reserved placeholder. Four are **Baileys only**, because whatsapp-web.js produces no callback behind them: `presence.update` (its prerequisite `POST .../presence/subscribe` answers `501` there, so this one announces itself) and `call.accepted` / `call.rejected` / `call.missed` (whatsapp-web.js sees a call ring but never its outcome, so these three are accepted on subscribe and then simply never fire). See the per-event catalog below for engine scope.#### GET /api/sessions/:sessionId/webhooks@@ -6047,6 +6139,7 @@ presence.updategroup.joingroup.leavegroup.update+group.join_requestcall.receivedcall.acceptedcall.rejected@@ -6131,6 +6224,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }` — `actorId` is the admin/inviter when known || `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` || `group.update` | Group metadata changes (subject, description, announce/locked settings) | `{ groupId, actorId?, participantIds, changes?, timestamp }` — `changes` carries only the fields that changed: `subject?`, `description?`, `announce?`, `locked?` |+| `group.join_request` | Someone asked to join a group this session administers (join-approval mode on) | `{ groupId, actorId?, participantIds, timestamp }` — `participantIds` are the users asking to join; `actorId` is who created the request when the engine reports one (differs from the requester on a non-admin add). Act on it via `GET/POST .../groups/:groupId/membership-requests[...]` **Baileys caveat**: the library (7.0.0-rc13) emits this only for non-admin-add requests — an invite-link self-request may produce no event there (upstream TODO); the membership-requests list endpoint still reports it. || `call.received` | An incoming voice/video call starts ringing | `{ callId, from, isVideo, isGroup, timestamp }` — `callId` is the id to pass to `POST /sessions/:sessionId/calls/:callId/reject` || `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended — answered, declined, or never picked up. **Baileys only**: whatsapp-web.js hooks the call collection's insert and sees no status at all, so it can report the ring but never its outcome | `{ sessionId, callId, from, outcome, isVideo, isGroup, timestamp }` — `callId` matches the `call.received` that preceded it, so the pair can be correlated. The engines report _what_ happened, never _who_ did it: an accept can come from any linked device. An outcome is only sent for a call this session saw ring, and offline-replayed signalling for calls that ended while disconnected is dropped. WhatsApp's `terminate` is deliberately unmapped — it covers both a caller hanging up before answer and either side ending an answered call, with nothing to tell them apart || `status.received` | A contact posts a status/story (opt-in — see below) | `{ sessionId, statusId, contact: { id, name?, pushName? }, type, caption?, hasMedia, mediaOmitted, omitReason?, postedAt, expiresAt }` — `statusId` is the store's `id` (usable with the status endpoints below); `postedAt`/`expiresAt` are epoch **milliseconds** (unlike the epoch-seconds convention for message timestamps), matching the `GET /status` store's own `Date`-backed fields |@@ -6201,6 +6295,7 @@ Every delivery includes:- `session.disconnected`: `disc_{sessionId}_{hash(reason)}_{occurredAt}`- `group.join` / `group.leave`: `grp_{groupId}_{hash(participantIds)}_{join|leave}_{occurredAt}`- `group.update`: `grp_{groupId}_update_{hash(changes)}_{occurredAt}`+- `group.join_request`: `grp_{groupId}_{hash(participantIds)}_join_request_{occurredAt}` (salted like `group.join` — a rejected user can legitimately ask again)- `call.received`: `call_{sessionId}_{callId}` (a call id is unique per call, so no `occurredAt` salt)Recurring lifecycle events (and `message.reaction` / `message.edited`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji, or editing the same message multiple times — so they are salted with an `occurredAt` timestamp captured **once per dispatch and reused across that dispatch's retries**. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex f92f543aa..00817062c 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1179,6 +1179,7 @@ available_events:- group.join # Participant(s) added/joined- group.leave # Participant(s) left/removed- group.update # Group subject/description/announce/locked changed+ - group.join_request # Someone asked to join a group this session administers# Calls- call.received # Incoming call ringing (payload: callId, from, isVideo, isGroup, timestamp)diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.mdindex 0bf0c39d9..5d17a6877 100644--- a/docs/22-n8n-integration.md+++ b/docs/22-n8n-integration.md@@ -94,6 +94,7 @@ Start workflows when WhatsApp events occur.| `group.join` | Participant(s) joined a group | Welcome messages || `group.leave` | Participant(s) left a group | Churn tracking || `group.update` | Group subject/description/settings changed | Group administration |+| `group.join_request` | Someone asked to join an administered group | Auto-approve/vet join requests || `call.received` | Incoming call started ringing | Auto-reject + auto-reply bots |> [!NOTE]diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 7a9df4442..9633452b0 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -22,7 +22,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins## Unwired-capability inventory-21 of the 100 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.+21 of the 103 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.### Channels / Newsletter@@ -174,8 +174,8 @@ These are hand-maintained and had drifted from the source before this pass; theyfrom `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way whenadding a method, instead of incrementing the previous figure.-- **100** interface methods, **200** adapter-cells (100 × 2 engines).-- **178** supported cells; **22** not-available cells across **21** methods.+- **103** interface methods, **206** adapter-cells (103 × 2 engines).+- **184** supported cells; **22** not-available cells across **21** methods.- Of the 22 not-available cells: **2 adapter-gaps** (fixable) + **20 library-limitations** + **0 uncertain**.- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.diff --git a/openapi.json b/openapi.jsonindex 819664bc7..3b0940e94 100644--- a/openapi.json+++ b/openapi.json@@ -4954,6 +4954,182 @@]}},+ "/api/sessions/{sessionId}/groups/{groupId}/membership-requests": {+ "get": {+ "description": "The join-approval queue of a group the account administers (join-approval mode on). Admin-only on both engines — a non-admin read is refused. Fields the engine does not report are omitted rather than defaulted.",+ "operationId": "GroupController_getMembershipRequests",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "required": true,+ "in": "path",+ "description": "Group ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Pending membership requests",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/GroupMembershipRequestDto"+ }+ }+ }+ }+ },+ "403": {+ "description": "WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, most often because the account lacks the admin rights the operation requires."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — retry shortly"+ }+ },+ "summary": "List pending join requests for a group",+ "tags": [+ "groups"+ ]+ }+ },+ "/api/sessions/{sessionId}/groups/{groupId}/membership-requests/approve": {+ "post": {+ "description": "Approves the named requesters, or EVERY pending request when the body names none. Approving an empty queue is a no-op that returns an empty results list. On whatsapp-web.js the engine pauses 250-500ms between requesters (upstream anti-abuse pacing), so acting on a large queue is a proportionally long request.",+ "operationId": "GroupController_approveMembershipRequests",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "required": true,+ "in": "path",+ "description": "Group ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MembershipRequestActionDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Requests processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal of NAMED requesters is an error)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ParticipantsOperationResponseDto"+ }+ }+ }+ },+ "403": {+ "description": "WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, most often because the account lacks the admin rights the operation requires."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget, so no per-participant outcome was read at all. Deliberately not folded into the 200 above — a participant WhatsApp turned down is reported inside `results` and is an answer; an update that never came back is not."+ }+ },+ "summary": "Approve pending join requests",+ "tags": [+ "groups"+ ]+ }+ },+ "/api/sessions/{sessionId}/groups/{groupId}/membership-requests/reject": {+ "post": {+ "description": "Rejects the named requesters, or EVERY pending request when the body names none. Rejecting an empty queue is a no-op that returns an empty results list. On whatsapp-web.js the engine pauses 250-500ms between requesters (upstream anti-abuse pacing), so acting on a large queue is a proportionally long request.",+ "operationId": "GroupController_rejectMembershipRequests",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "required": true,+ "in": "path",+ "description": "Group ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MembershipRequestActionDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Requests processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal of NAMED requesters is an error)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ParticipantsOperationResponseDto"+ }+ }+ }+ },+ "403": {+ "description": "WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, most often because the account lacks the admin rights the operation requires."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget, so no per-participant outcome was read at all. Deliberately not folded into the 200 above — a participant WhatsApp turned down is reported inside `results` and is an answer; an update that never came back is not."+ }+ },+ "summary": "Reject pending join requests",+ "tags": [+ "groups"+ ]+ }+ },"/api/sessions/{sessionId}/groups/{groupId}/subject": {"put": {"operationId": "GroupController_setSubject",@@ -9590,6 +9766,7 @@"group.join","group.leave","group.update",+ "group.join_request","call.received","call.accepted","call.rejected",@@ -9741,6 +9918,7 @@"group.join","group.leave","group.update",+ "group.join_request","call.received","call.accepted","call.rejected",@@ -12587,6 +12765,52 @@"results"]},+ "GroupMembershipRequestDto": {+ "type": "object",+ "properties": {+ "participantId": {+ "type": "string",+ "description": "Neutral id of the user asking to join.",+ "example": "[email protected]"+ },+ "addedById": {+ "type": "string",+ "description": "Who created the request, when the engine reports it (differs from the requester on a non-admin add).",+ "example": "[email protected]"+ },+ "method": {+ "type": "string",+ "description": "How the request was made, when the engine reports it.",+ "enum": [+ "invite_link",+ "non_admin_add",+ "linked_group_join"+ ],+ "example": "invite_link"+ },+ "requestedAt": {+ "type": "number",+ "description": "Unix seconds the request was created, when the engine reports it.",+ "example": 1754700000+ }+ },+ "required": [+ "participantId"+ ]+ },+ "MembershipRequestActionDto": {+ "type": "object",+ "properties": {+ "participants": {+ "description": "Requester WhatsApp IDs (e.g. [email protected]). Omit to act on every pending request.",+ "maxItems": 256,+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },"GroupSubjectDto": {"type": "object","properties": {diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex d8ebdf674..56eafc077 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -357,6 +357,45 @@ export class BaileysEvents {this.host.getOnGroupEvent()?.(payload);}+ /**+ * Baileys `group.join-request`: someone asked to join a group the account admins (join-approval+ * on). Only action 'created' maps to the neutral join_request kind — the wwebjs event has no+ * revoke/reject counterpart, so only the shared signal is surfaced. Upstream scope caveat: rc13+ * emits this event only from the NON_ADMIN_ADD stub (172); the direct self-request stub (144) is+ * unhandled with an upstream TODO (Utils/process-message.js:569), so an invite-link self-request+ * may produce no event on this engine — the REST list endpoint still sees it. The pn twins are+ * preferred over lids for the same reason as everywhere else. The event carries no timestamp, so+ * it is stamped at receipt.+ */+ handleGroupJoinRequest(event: {+ id?: string;+ author?: string;+ authorPn?: string;+ participant?: string;+ participantPn?: string;+ action?: string;+ method?: string;+ }): void {+ if (event.action !== 'created' || !event.id) {+ return;+ }+ const participant = event.participantPn ?? event.participant;+ if (!participant) {+ return; // nothing addressable to report+ }+ const payload: GroupEvent = {+ kind: 'join_request',+ groupId: this.host.toNeutralJid(event.id),+ participantIds: [this.host.toNeutralJid(participant)],+ timestamp: Math.floor(Date.now() / 1000),+ };+ const actor = event.authorPn ?? event.author;+ if (actor) {+ payload.actorId = this.host.toNeutralJid(actor);+ }+ this.host.getOnGroupEvent()?.(payload);+ }+/*** Baileys `groups.update`: partial group metadata. Each entry becomes one neutral 'update'* GroupEvent with `changes` filled from whichever of subject/desc/announce/restrict it carriesdiff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 49013bdd4..6b2cca1ac 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -4,6 +4,8 @@ import {GroupInfo,GroupJoinInfo,GroupMemberAddMode,+ GroupMembershipRequest,+ GroupMembershipRequestMethod,MediaInput,ParticipantOperationResult,} from '../interfaces/whatsapp-engine.interface';@@ -92,6 +94,13 @@ export function toEngineParticipants(participants: string[], toEngineJid: (jid:return participants.map(toEngineJid);}+/** The neutral method tokens — Baileys' wire tokens are already this vocabulary. */+const MEMBERSHIP_REQUEST_METHODS: readonly GroupMembershipRequestMethod[] = [+ 'invite_link',+ 'non_admin_add',+ 'linked_group_join',+];+export class BaileysGroups {constructor(private readonly host: BaileysGroupsHost,@@ -394,4 +403,100 @@ export class BaileysGroups {this.confirmed(this.sock().groupToggleEphemeral(groupId, durationSec), 'the disappearing-message timer change'),);}++ async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {+ this.host.ensureReady();+ const raw = await mapServerRefusal('Listing the membership requests', () =>+ withQueryDeadline(+ this.sock().groupRequestParticipantsList(groupId),+ this.queryBudgetMs,+ 'WhatsApp did not answer the membership-request list query in time',+ ),+ );+ // Bare wire attrs: engine-dialect `jid`, snake_case `request_method`, stringly `request_time`.+ // Fields that do not parse are omitted rather than defaulted; an entry without a jid carries+ // nothing addressable and is dropped.+ return (raw ?? []).flatMap(attrs => {+ if (!attrs.jid) {+ return [];+ }+ const method = MEMBERSHIP_REQUEST_METHODS.includes(attrs.request_method as GroupMembershipRequestMethod)+ ? (attrs.request_method as GroupMembershipRequestMethod)+ : undefined;+ const requestedAt = Number(attrs.request_time);+ return [+ {+ participantId: this.host.toNeutralJid(attrs.jid),+ ...(method ? { method } : {}),+ ...(Number.isFinite(requestedAt) && requestedAt > 0 ? { requestedAt: Math.floor(requestedAt) } : {}),+ },+ ];+ });+ }++ approveGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.runMembershipRequestsUpdate(groupId, participants, 'approve');+ }++ rejectGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.runMembershipRequestsUpdate(groupId, participants, 'reject');+ }++ /**+ * `groupRequestParticipantsUpdate` resolves the same per-jid `[{status, jid}]` shape as the+ * participant writes (status is the server's error attr or '200', Socket/groups.js:116-139), and+ * the same guards apply — but only when the caller NAMED requesters. Baileys has no act-on-all+ * form, so an omitted list enumerates the pending queue first; an empty queue is a legitimate+ * no-op that resolves [], not a refusal.+ */+ private async runMembershipRequestsUpdate(+ groupId: string,+ participants: string[] | undefined,+ action: 'approve' | 'reject',+ ): Promise<ParticipantOperationResult[]> {+ this.host.ensureReady();+ let targets: string[];+ if (participants) {+ targets = this.toEngineParticipants(participants);+ } else {+ const pending = await mapServerRefusal(`Listing the membership requests to ${action}`, () =>+ withQueryDeadline(+ this.sock().groupRequestParticipantsList(groupId),+ this.queryBudgetMs,+ 'WhatsApp did not answer the membership-request list query in time',+ ),+ );+ targets = (pending ?? []).map(attrs => attrs.jid).filter((jid): jid is string => Boolean(jid));+ if (targets.length === 0) {+ return [];+ }+ }+ const raw = await mapServerRefusal(`Membership-request ${action}`, () =>+ withQueryDeadline(+ this.sock().groupRequestParticipantsUpdate(groupId, targets, action),+ this.queryBudgetMs,+ `WhatsApp did not answer the membership-request ${action} in time`,+ ),+ );+ const results: ParticipantOperationResult[] = (raw ?? []).map(entry => ({+ id: entry.jid ? this.host.toNeutralJid(entry.jid) : '',+ success: entry.status === '200',+ status: Number.isFinite(Number(entry.status)) ? Number(entry.status) : undefined,+ }));+ if (!participants) {+ return results;+ }+ if (results.length === 0) {+ throw new EngineRefusedError(+ `groupRequestParticipantsUpdate(${action}) returned no per-participant outcome for group ${groupId}`,+ );+ }+ if (results.every(r => !r.success)) {+ const detail = results.map(r => `${r.id || '?'} (${r.status ?? '?'})`).join(', ');+ throw new EngineRefusedError(+ `Membership-request ${action} failed for all ${results.length} participant(s) in group ${groupId}: ${detail}`,+ );+ }+ return results;+ }}diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 1c82062e5..59d840ce8 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -81,6 +81,7 @@ export interface BaileysLifecycleHost {logContactEvent: BaileysEvents['logContactEvent'];handleGroupParticipantsUpdate: BaileysEvents['handleGroupParticipantsUpdate'];handleGroupsUpdate: BaileysEvents['handleGroupsUpdate'];+ handleGroupJoinRequest: BaileysEvents['handleGroupJoinRequest'];handleCallEvents: BaileysEvents['handleCallEvents'];handlePresenceUpdate: BaileysEvents['handlePresenceUpdate'];captureHistoryMessages: BaileysHistory['captureHistoryMessages'];@@ -300,6 +301,7 @@ export class BaileysLifecycle {});sock.ev.on('group-participants.update', event => this.host.handleGroupParticipantsUpdate(event));sock.ev.on('groups.update', updates => this.host.handleGroupsUpdate(updates));+ sock.ev.on('group.join-request', event => this.host.handleGroupJoinRequest(event));sock.ev.on('messaging-history.set', history => {this.host.upsertContacts(history.contacts);this.host.upsertChats(history.chats);diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex b767cc10b..91a0b00bf 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -3425,6 +3425,46 @@ describe('BaileysAdapter group events (group-participants.update / groups.updateexpect(firstEvent(onGroupEvent).actorId).toBeUndefined();});+ it('maps a created group.join-request to a neutral join_request GroupEvent', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ const now = jest.spyOn(Date, 'now').mockReturnValue(1782000000_000);+ try {+ fakeSock.fire('group.join-request', {+ id: '[email protected]',+ author: '[email protected]',+ participant: '[email protected]',+ action: 'created',+ method: 'invite_link',+ });+ } finally {+ now.mockRestore();+ }++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent)).toEqual({+ kind: 'join_request',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1782000000, // the Baileys event is undated: stamped at receipt+ });+ });++ it('drops a revoked group.join-request — only the request being MADE is surfaced', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('group.join-request', {+ id: '[email protected]',+ author: '[email protected]',+ participant: '[email protected]',+ action: 'revoked',+ method: 'invite_link',+ });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });+it('maps groups.update entries to update GroupEvents with the neutral changes delta', async () => {const { onGroupEvent } = await readyWithGroupEvents();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex c927a521d..dc072c427 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -22,6 +22,7 @@ import {Group,GroupInfo,GroupMemberAddMode,+ GroupMembershipRequest,IncomingMessage,IWhatsAppEngine,Label,@@ -221,6 +222,7 @@ export class BaileysAdapter implements IWhatsAppEngine {logContactEvent: (event, records) => this.events.logContactEvent(event, records),handleGroupParticipantsUpdate: event => this.events.handleGroupParticipantsUpdate(event),handleGroupsUpdate: updates => this.events.handleGroupsUpdate(updates),+ handleGroupJoinRequest: event => this.events.handleGroupJoinRequest(event),handleCallEvents: calls => this.events.handleCallEvents(calls),handlePresenceUpdate: update => this.events.handlePresenceUpdate(update),captureHistoryMessages: messages => this.history.captureHistoryMessages(messages),@@ -455,6 +457,21 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.groups.setGroupEphemeral(groupId, durationSec);}+ async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {+ return this.groups.getGroupMembershipRequests(groupId);+ }++ async approveGroupMembershipRequests(+ groupId: string,+ participants?: string[],+ ): Promise<ParticipantOperationResult[]> {+ return this.groups.approveGroupMembershipRequests(groupId, participants);+ }++ async rejectGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.rejectGroupMembershipRequests(groupId, participants);+ }+async getProfilePicture(contactId: string): Promise<string | null> {return this.contacts.getProfilePicture(contactId);}diff --git a/src/engine/adapters/membership-requests.spec.ts b/src/engine/adapters/membership-requests.spec.tsnew file mode 100644index 000000000..705f437f6--- /dev/null+++ b/src/engine/adapters/membership-requests.spec.ts@@ -0,0 +1,377 @@+import { WwebjsGroups, normalizeWwebjsRequestMethod } from './wwebjs-groups';+import { BaileysGroups, type BaileysGroupsHost } from './baileys-groups';+import { BaileysEvents, type BaileysEventsHost } from './baileys-events';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import type { Client } from 'whatsapp-web.js';+import type { WASocket } from '@whiskeysockets/baileys';+import type { GroupEvent } from '../interfaces/whatsapp-engine.interface';++/**+ * Group membership requests (the join-approval queue of a group the account admins) across both+ * engines. The two upstreams disagree on every shape involved:+ *+ * - whatsapp-web.js resolves raw page-context store objects — requester wids can arrive as+ * `{_serialized}` OR `{$1}` (the #747 minifier rename), `requestMethod` is a PascalCase token,+ * and approve/reject resolve `{requesterId, error?, message}` per requester.+ * - Baileys resolves bare wire attrs — engine-dialect `jid`, snake_case `request_method`, and a+ * stringly `request_time`; approve/reject resolve `[{status, jid}]` like the participant writes.+ *+ * These tests pin both mappings to the one neutral shape, and pin the batch-guard convention:+ * a caller who NAMED participants gets the membership-write guards (all-failed → refusal, no+ * outcome → refusal), while approve/reject-ALL with an empty queue is a legitimate no-op ([]).+ */++const logger = createLogger('membership-requests.spec');++// ---------------------------------------------------------------------------------------------+// whatsapp-web.js delegate+// ---------------------------------------------------------------------------------------------++type WwebjsClientStub = {+ getGroupMembershipRequests: jest.Mock;+ approveGroupMembershipRequests: jest.Mock;+ rejectGroupMembershipRequests: jest.Mock;+};++function makeWwebjsGroups(): { groups: WwebjsGroups; client: WwebjsClientStub } {+ const client: WwebjsClientStub = {+ getGroupMembershipRequests: jest.fn(),+ approveGroupMembershipRequests: jest.fn(),+ rejectGroupMembershipRequests: jest.fn(),+ };+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ isPageTransportError: () => false,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ return { groups: new WwebjsGroups(host), client };+}++describe('WwebjsGroups membership requests', () => {+ it('normalises the PascalCase request-method tokens and reports unknown ones as undefined', () => {+ expect(normalizeWwebjsRequestMethod('InviteLink')).toBe('invite_link');+ expect(normalizeWwebjsRequestMethod('NonAdminAdd')).toBe('non_admin_add');+ expect(normalizeWwebjsRequestMethod('LinkedGroupJoin')).toBe('linked_group_join');+ expect(normalizeWwebjsRequestMethod('SomethingNew')).toBeUndefined();+ expect(normalizeWwebjsRequestMethod(undefined)).toBeUndefined();+ });++ it('lists membership requests, reading both wid spellings and dropping unreadable requesters', async () => {+ const { groups, client } = makeWwebjsGroups();+ client.getGroupMembershipRequests.mockResolvedValue([+ {+ id: { _serialized: '[email protected]' },+ addedBy: { $1: '[email protected]' }, // the #747 rename spelling+ requestMethod: 'InviteLink',+ t: 1754700000,+ },+ {+ id: {}, // unreadable requester wid: no addressable id to report+ addedBy: { _serialized: '[email protected]' },+ requestMethod: 'NonAdminAdd',+ t: 1754700001,+ },+ ]);++ const result = await groups.getGroupMembershipRequests('[email protected]');++ expect(client.getGroupMembershipRequests).toHaveBeenCalledWith('[email protected]');+ expect(result).toEqual([+ {+ participantId: '[email protected]',+ addedById: '[email protected]',+ method: 'invite_link',+ requestedAt: 1754700000,+ },+ ]);+ });++ it('omits optional fields the store did not report rather than defaulting them', async () => {+ const { groups, client } = makeWwebjsGroups();+ client.getGroupMembershipRequests.mockResolvedValue([{ id: '[email protected]', requestMethod: 'Unknowable' }]);++ const result = await groups.getGroupMembershipRequests('[email protected]');++ expect(result).toEqual([{ participantId: '[email protected]' }]);+ });++ it.each([+ ['approve', 'approveGroupMembershipRequests' as const],+ ['reject', 'rejectGroupMembershipRequests' as const],+ ])('%ss named requesters and maps the per-requester outcome', async (_action, method) => {+ const { groups, client } = makeWwebjsGroups();+ client[method].mockResolvedValue([+ { requesterId: '[email protected]', message: 'done' },+ { requesterId: { $1: '[email protected]' }, error: 403, message: 'refused' },+ ]);++ const result = await groups[method]('[email protected]', ['[email protected]', '[email protected]']);++ // The upstream default sleep is restated explicitly so a wwebjs default change cannot+ // silently alter this gateway's pacing.+ expect(client[method]).toHaveBeenCalledWith('[email protected]', {+ requesterIds: ['[email protected]', '[email protected]'],+ sleep: [250, 500],+ });+ expect(result).toEqual([+ { id: '[email protected]', success: true, message: 'done' },+ { id: '[email protected]', success: false, status: 403, message: 'refused' },+ ]);+ });++ it('reports the code-less ServerStatusCodeError entry as a FAILURE, not a success', async () => {+ // The page util's non-success RPC branch pushes {requesterId, message: 'ServerStatusCodeError'}+ // with NO error code (Injected/Utils.js:1637-1648) — reading "no error field" as success would+ // sell a server failure as an approval.+ const { groups, client } = makeWwebjsGroups();+ client.approveGroupMembershipRequests.mockResolvedValue([+ { requesterId: '[email protected]', message: 'ServerStatusCodeError' },+ { requesterId: '[email protected]', message: 'Approved successfully' },+ ]);++ const result = await groups.approveGroupMembershipRequests('[email protected]', ['[email protected]', '[email protected]']);++ expect(result).toEqual([+ { id: '[email protected]', success: false, message: 'ServerStatusCodeError' },+ { id: '[email protected]', success: true, message: 'Approved successfully' },+ ]);+ });++ it('throws EngineRefusedError when every NAMED requester failed', async () => {+ const { groups, client } = makeWwebjsGroups();+ client.approveGroupMembershipRequests.mockResolvedValue([+ { requesterId: '[email protected]', error: 403, message: 'no' },+ ]);++ await expect(groups.approveGroupMembershipRequests('[email protected]', ['[email protected]'])).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('throws EngineRefusedError when NAMED requesters produced no outcome at all', async () => {+ const { groups, client } = makeWwebjsGroups();+ client.approveGroupMembershipRequests.mockResolvedValue([]);++ await expect(groups.approveGroupMembershipRequests('[email protected]', ['[email protected]'])).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('resolves [] for approve-all on an empty queue — a no-op, not a refusal', async () => {+ const { groups, client } = makeWwebjsGroups();+ client.approveGroupMembershipRequests.mockResolvedValue([]);++ await expect(groups.approveGroupMembershipRequests('[email protected]')).resolves.toEqual([]);++ expect(client.approveGroupMembershipRequests).toHaveBeenCalledWith('[email protected]', {+ requesterIds: null,+ sleep: [250, 500],+ });+ });+});++// ---------------------------------------------------------------------------------------------+// Baileys delegate+// ---------------------------------------------------------------------------------------------++type BaileysSockStub = {+ groupRequestParticipantsList: jest.Mock;+ groupRequestParticipantsUpdate: jest.Mock;+};++function makeBaileysGroups(): { groups: BaileysGroups; sock: BaileysSockStub } {+ const sock: BaileysSockStub = {+ groupRequestParticipantsList: jest.fn(),+ groupRequestParticipantsUpdate: jest.fn(),+ };+ const host: BaileysGroupsHost = {+ ensureReady: jest.fn(),+ getSocket: () => sock as unknown as WASocket,+ logger,+ toNeutralJid: jid => jid.replace('@s.whatsapp.net', '@c.us'),+ toEngineJid: jid => jid.replace('@c.us', '@s.whatsapp.net'),+ normalizedSelfJid: () => '[email protected]',+ };+ return { groups: new BaileysGroups(host), sock };+}++describe('BaileysGroups membership requests', () => {+ it('lists membership requests, neutralising jids and parsing the stringly wire attrs', async () => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsList.mockResolvedValue([+ { jid: '[email protected]', request_method: 'invite_link', request_time: '1754700000' },+ { jid: '[email protected]', request_method: 'brand_new_token', request_time: 'soon' },+ { request_method: 'invite_link' }, // no jid: nothing addressable to report+ ]);++ const result = await groups.getGroupMembershipRequests('[email protected]');++ expect(sock.groupRequestParticipantsList).toHaveBeenCalledWith('[email protected]');+ expect(result).toEqual([+ { participantId: '[email protected]', method: 'invite_link', requestedAt: 1754700000 },+ { participantId: '[email protected]' },+ ]);+ });++ it.each([['approve' as const], ['reject' as const]])(+ '%ss named requesters in the engine dialect and maps the per-jid statuses',+ async action => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsUpdate.mockResolvedValue([+ { status: '200', jid: '[email protected]' },+ { status: '403', jid: '[email protected]' },+ ]);++ const method = action === 'approve' ? 'approveGroupMembershipRequests' : 'rejectGroupMembershipRequests';+ const result = await groups[method]('[email protected]', ['[email protected]', '[email protected]']);++ expect(sock.groupRequestParticipantsUpdate).toHaveBeenCalledWith(+ '[email protected]',+ ['[email protected]', '[email protected]'],+ action,+ );+ expect(result).toEqual([+ { id: '[email protected]', success: true, status: 200 },+ { id: '[email protected]', success: false, status: 403 },+ ]);+ },+ );++ it('throws EngineRefusedError when every NAMED requester failed', async () => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsUpdate.mockResolvedValue([{ status: '403', jid: '[email protected]' }]);++ await expect(groups.approveGroupMembershipRequests('[email protected]', ['[email protected]'])).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('throws EngineRefusedError when NAMED requesters produced no outcome at all', async () => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsUpdate.mockResolvedValue([]);++ await expect(groups.rejectGroupMembershipRequests('[email protected]', ['[email protected]'])).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('approve-all lists the pending queue first and acts on exactly those requesters', async () => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsList.mockResolvedValue([+ { jid: '[email protected]', request_method: 'invite_link', request_time: '1' },+ { jid: '[email protected]', request_method: 'invite_link', request_time: '2' },+ ]);+ sock.groupRequestParticipantsUpdate.mockResolvedValue([+ { status: '200', jid: '[email protected]' },+ { status: '200', jid: '[email protected]' },+ ]);++ const result = await groups.approveGroupMembershipRequests('[email protected]');++ expect(sock.groupRequestParticipantsUpdate).toHaveBeenCalledWith(+ '[email protected]',+ ['[email protected]', '[email protected]'],+ 'approve',+ );+ expect(result).toHaveLength(2);+ });++ it('approve-all on an empty queue resolves [] without issuing the update at all', async () => {+ const { groups, sock } = makeBaileysGroups();+ sock.groupRequestParticipantsList.mockResolvedValue([]);++ await expect(groups.approveGroupMembershipRequests('[email protected]')).resolves.toEqual([]);++ expect(sock.groupRequestParticipantsUpdate).not.toHaveBeenCalled();+ });+});++// ---------------------------------------------------------------------------------------------+// Baileys 'group.join-request' event mapping+// ---------------------------------------------------------------------------------------------++describe('BaileysEvents.handleGroupJoinRequest', () => {+ function makeEvents(): { events: BaileysEvents; onGroupEvent: jest.Mock } {+ const onGroupEvent = jest.fn();+ const host = {+ logger,+ toNeutralJid: (jid: string) => jid.replace('@s.whatsapp.net', '@c.us'),+ getOnGroupEvent: () => onGroupEvent,+ } as unknown as BaileysEventsHost;+ return { events: new BaileysEvents(host), onGroupEvent };+ }++ it('maps a created join request to a neutral join_request GroupEvent, preferring the pn twins', () => {+ const { events, onGroupEvent } = makeEvents();+ const now = jest.spyOn(Date, 'now').mockReturnValue(1782000000_000);+ try {+ events.handleGroupJoinRequest({+ id: '[email protected]',+ author: '111@lid',+ authorPn: '[email protected]',+ participant: '222@lid',+ participantPn: '[email protected]',+ action: 'created',+ method: 'invite_link',+ });+ } finally {+ now.mockRestore();+ }++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ const event = (onGroupEvent.mock.calls as Array<[GroupEvent]>)[0][0];+ expect(event).toEqual({+ kind: 'join_request',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1782000000, // the Baileys event is undated: stamped at receipt+ });+ });++ it('keeps the requester as the participant when no author is reported (a self-request)', () => {+ const { events, onGroupEvent } = makeEvents();++ events.handleGroupJoinRequest({+ id: '[email protected]',+ participant: '[email protected]',+ action: 'created',+ method: 'invite_link',+ });++ const event = (onGroupEvent.mock.calls as Array<[GroupEvent]>)[0][0];+ expect(event).toMatchObject({+ kind: 'join_request',+ groupId: '[email protected]',+ participantIds: ['[email protected]'],+ });+ expect(event.actorId).toBeUndefined();+ });++ it.each(['revoked', 'rejected'])('drops action %s — only the request being MADE is an event', action => {+ const { events, onGroupEvent } = makeEvents();++ events.handleGroupJoinRequest({+ id: '[email protected]',+ author: '[email protected]',+ participant: '[email protected]',+ action,+ method: 'invite_link',+ });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });++ it('drops a request without a group id or participant — nothing addressable to report', () => {+ const { events, onGroupEvent } = makeEvents();++ events.handleGroupJoinRequest({ id: '[email protected]', action: 'created', method: 'invite_link' });+ events.handleGroupJoinRequest({ participant: '[email protected]', action: 'created', method: 'invite_link' });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 8f8db9161..7054c8b7d 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -3058,6 +3058,68 @@ describe('WhatsAppWebJsAdapter group notifications (group_join / group_leave / g});});+ it('maps group_membership_request to a join_request GroupEvent, with the author as the requester', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ // Upstream documents chatId/author/timestamp for this event (Client.js:633-641); a+ // self-request carries no recipients, so the author IS the user asking to join.+ client.emit('group_membership_request', {+ id: { _serialized: 'NOTIF_REQ' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: [],+ body: '',+ timestamp: 1700000300,+ type: 'membership_approval_request',+ });++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(groupArg(onGroupEvent)).toEqual({+ kind: 'join_request',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000300,+ });+ });++ it('reports recipientIds as the requested users when present (a non-admin add request)', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_membership_request', {+ id: { _serialized: 'NOTIF_REQ2' },+ chatId: '[email protected]',+ author: '[email protected]',+ recipientIds: ['[email protected]'],+ body: '',+ timestamp: 1700000400,+ type: 'membership_approval_request',+ });++ expect(groupArg(onGroupEvent)).toEqual({+ kind: 'join_request',+ groupId: '[email protected]',+ actorId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000400,+ });+ });++ it('drops a membership request that names no requester at all — nothing addressable to report', () => {+ const { onGroupEvent, client } = wireGroupHandler();++ client.emit('group_membership_request', {+ id: { _serialized: 'NOTIF_REQ3' },+ chatId: '[email protected]',+ recipientIds: [],+ body: '',+ timestamp: 1700000500,+ type: 'membership_approval_request',+ });++ expect(onGroupEvent).not.toHaveBeenCalled();+ });+it('omits actorId when the notification has no author', () => {const { onGroupEvent, client } = wireGroupHandler();diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 419a515bd..8a677b357 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -22,6 +22,7 @@ import {Group,GroupInfo,GroupMemberAddMode,+ GroupMembershipRequest,ParticipantOperationResult,LocationInput,PollInput,@@ -613,6 +614,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.client.on('group_join', notification => this.handleGroupNotification('join', notification));this.client.on('group_leave', notification => this.handleGroupNotification('leave', notification));this.client.on('group_update', notification => this.handleGroupNotification('update', notification));+ this.client.on('group_membership_request', notification =>+ this.handleGroupNotification('join_request', notification),+ );this.client.on('call', call => this.handleIncomingCall(call));@@ -754,6 +758,15 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin? Math.floor(notification.timestamp): Math.floor(Date.now() / 1000),};+ if (kind === 'join_request' && payload.participantIds.length === 0) {+ // A self-request carries no recipients: the author IS the user asking to join+ // (Client.js:633-641 documents chatId/author/timestamp for this event). A request naming+ // nobody at all is unactionable and dropped.+ if (!payload.actorId) {+ return;+ }+ payload.participantIds = [payload.actorId];+ }if (kind === 'update') {// Join/leave carry no metadata delta. An update whose subtype/body cannot be interpreted// still emits with empty changes rather than being dropped silently.@@ -1739,6 +1752,18 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.groups.setGroupEphemeral(groupId, durationSec);}+ getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {+ return this.groups.getGroupMembershipRequests(groupId);+ }++ approveGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.approveGroupMembershipRequests(groupId, participants);+ }++ rejectGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.rejectGroupMembershipRequests(groupId, participants);+ }+// ========== Status/Stories (Phase 3) ==========// Note: These are stub implementations - whatsapp-web.js has limited Status API supportdiff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 0cc01c273..e4ca49092 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -4,6 +4,8 @@ import {GroupInfo,GroupJoinInfo,GroupMemberAddMode,+ GroupMembershipRequest,+ GroupMembershipRequestMethod,MediaInput,GroupParticipant,ParticipantOperationResult,@@ -57,6 +59,17 @@ export function normalizeWwebjsMemberAddMode(raw: string | boolean | undefined):return undefined;}+/**+ * Normalise whatsapp-web.js's PascalCase request-method token to the neutral vocabulary.+ * Unrecognised tokens (a future WA Web build) are reported as unknown rather than guessed.+ */+export function normalizeWwebjsRequestMethod(raw: string | undefined): GroupMembershipRequestMethod | undefined {+ if (raw === 'InviteLink') return 'invite_link';+ if (raw === 'NonAdminAdd') return 'non_admin_add';+ if (raw === 'LinkedGroupJoin') return 'linked_group_join';+ return undefined;+}+export class WwebjsGroups {constructor(private readonly host: WwebjsEngineHost) {}@@ -500,4 +513,83 @@ export class WwebjsGroups {this.host.ensureReady();throw new EngineNotSupportedError('setGroupEphemeral');}++ async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {+ this.host.ensureReady();+ try {+ const raw = await this.client().getGroupMembershipRequests(groupId);+ // Raw page-context store objects: wids can arrive as {_serialized} OR {$1} (the #747+ // minifier rename), so every id goes through readWid; a requester whose wid is unreadable+ // is dropped rather than reported as the literal "undefined".+ return (raw ?? []).flatMap(entry => {+ const e = entry as unknown as {+ id?: SerializedWid | string;+ addedBy?: SerializedWid | string;+ requestMethod?: string;+ t?: number;+ };+ const participantId = readWid(e.id);+ if (!participantId) {+ return [];+ }+ const addedById = readWid(e.addedBy);+ const method = normalizeWwebjsRequestMethod(e.requestMethod);+ return [+ {+ participantId,+ ...(addedById ? { addedById } : {}),+ ...(method ? { method } : {}),+ ...(typeof e.t === 'number' ? { requestedAt: e.t } : {}),+ },+ ];+ });+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'getGroupMembershipRequests');+ throw error;+ }+ }++ approveGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.runMembershipRequestAction('approveGroupMembershipRequests', groupId, participants);+ }++ rejectGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {+ return this.runMembershipRequestAction('rejectGroupMembershipRequests', groupId, participants);+ }++ /**+ * Shared body of the approve/reject writes. The upstream default sleep (a human-ish 250-500ms+ * pause between requesters) is restated explicitly so a wwebjs default change cannot silently+ * alter this gateway's pacing. The membership-write guards (assertParticipantResults) apply only+ * when the caller NAMED requesters: acting on "all pending" of an empty queue is a legitimate+ * no-op that resolves [], not a refusal.+ */+ private async runMembershipRequestAction(+ op: 'approveGroupMembershipRequests' | 'rejectGroupMembershipRequests',+ groupId: string,+ participants?: string[],+ ): Promise<ParticipantOperationResult[]> {+ this.host.ensureReady();+ const raw = await this.client()[op](groupId, {+ requesterIds: participants ?? null,+ sleep: [250, 500],+ });+ // {requesterId, error?, message} per requester; requesterId is a page-context value that can+ // arrive as a string or a wid object (both #747 spellings), so it goes through readWid too.+ // "No error field" is NOT sufficient for success: the page util's non-success RPC branch pushes+ // {requesterId, message: 'ServerStatusCodeError'} with no code at all (Injected/Utils.js:1637-1648).+ const results: ParticipantOperationResult[] = (raw ?? []).map(entry => {+ const e = entry as unknown as { requesterId?: SerializedWid | string | null; error?: number; message?: string };+ return {+ id: readWid(e.requesterId ?? undefined) ?? '',+ success: e.error === undefined && e.message !== 'ServerStatusCodeError',+ ...(e.error !== undefined ? { status: e.error } : {}),+ ...(e.message ? { message: e.message } : {}),+ };+ });+ if (!participants) {+ return results;+ }+ return this.assertParticipantResults(op, groupId, results);+ }}diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 509c87b31..dc2c2d7c7 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -80,6 +80,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"wwjs GroupChat.addParticipants → per-participant {code,message} object, or a reason STRING on batch refusal (index.d.ts:2184; GroupChat.js:78-264) — both mapped at the adapter; baileys groupParticipantsUpdate(jid,pids,'add') → per-jid [{status:'200'|error}] (Socket/groups.js:140-156); per-participant results surface on the HTTP `results` field, a total refusal throws",},+ approveGroupMembershipRequests: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs Client.approveGroupMembershipRequests(groupId, {requesterIds, sleep}) → per-requester [{requesterId, error?, message}] (index.d.ts:360; Client.js:3024-3038), requesterIds null = every pending request; baileys groupRequestParticipantsUpdate(jid, pids, 'approve') → per-jid [{status:'200'|error, jid}] (Socket/groups.d.ts:13; groups.js:116-139) — no act-on-all form, so an omitted list enumerates groupRequestParticipantsList first",+ },archiveChat: {wwjs: { status: 'supported' },baileys: { status: 'supported' },@@ -136,6 +142,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {deleteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },muteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },getGroupJoinInfo: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getGroupMembershipRequests: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.getGroupMembershipRequests(groupId) → raw page-context store objects {id, addedBy, parentGroupId, requestMethod, t} (index.d.ts:355; Client.js:2990-3000) — wids read via readWid for the #747 $1 rename; baileys groupRequestParticipantsList(jid) → bare wire attrs [{jid, request_method, request_time}] (Socket/groups.d.ts:10; groups.js:105-115)',+ },getChannelById: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },getChannelMessages: {wwjs: { status: 'supported' },@@ -248,6 +260,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"wwjs GroupChat.removeParticipants → batch {status:200} only (index.d.ts:2189; GroupChat.js:267-298) — a non-200 now throws at the adapter instead of being discarded; baileys groupParticipantsUpdate(jid,pids,'remove') → per-jid [{status}] (Socket/groups.js:140-156)",},+ rejectGroupMembershipRequests: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "same shapes as approveGroupMembershipRequests with the 'Reject' page action (wwjs Client.js:3050-3064) / the 'reject' update action (baileys groups.js:116-139)",+ },rejectCall: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 546ba8220..9acc56aa5 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -259,6 +259,27 @@ export interface GroupJoinInfo {participantCount?: number;}+/** How a join request was made. Neutral vocabulary; both engines' tokens map onto it. */+export type GroupMembershipRequestMethod = 'invite_link' | 'non_admin_add' | 'linked_group_join';++/**+ * One pending request to join a group that has join-approval turned on. Mapped at the adapter+ * boundary from engine shapes that disagree on everything: whatsapp-web.js resolves raw+ * page-context store objects (wid objects, PascalCase method tokens), Baileys bare wire attrs+ * (engine-dialect jids, snake_case tokens, stringly timestamps). Fields the engine did not report+ * are omitted rather than defaulted.+ */+export interface GroupMembershipRequest {+ /** Neutral id of the user asking to join. */+ participantId: string;+ /** Who created the request when the engine reports it (differs from the requester on a non-admin add). */+ addedById?: string;+ /** How the request was made, when the engine reports a token this shape models. */+ method?: GroupMembershipRequestMethod;+ /** Unix seconds the request was created, when the engine reports it. */+ requestedAt?: number;+}+/*** A caller-supplied link preview, used instead of fetching one.*@@ -520,19 +541,24 @@ export interface ReactionEvent {/*** A group membership or metadata change, mapped at the adapter boundary to this neutral* shape so consumers never see engine-specific payloads:- * - whatsapp-web.js: `group_join` / `group_leave` / `group_update` (GroupNotification).+ * - whatsapp-web.js: `group_join` / `group_leave` / `group_update` /+ * `group_membership_request` (GroupNotification).* - Baileys: `group-participants.update` (add/remove only — promote/demote are not- * surfaced) and `groups.update` (subject/desc/announce/restrict).+ * surfaced), `groups.update` (subject/desc/announce/restrict) and `group.join-request`+ * (action 'created' only — the wwebjs event has no revoke/reject counterpart, so only+ * the shared signal is surfaced; rc13 itself emits the event only for non-admin-add+ * requests — the direct self-request stub 144 is unhandled upstream, marked TODO at+ * Utils/process-message.js:569 — so an invite-link self-request may not fire on Baileys).* All ids are in the neutral dialect (`@g.us` / `@c.us`; a lid stays `<id>@lid` when the* lid->phone mapping is unknown).*/export interface GroupEvent {- kind: 'join' | 'leave' | 'update';+ kind: 'join' | 'leave' | 'update' | 'join_request';/** Neutral group id (`@g.us`). */groupId: string;/** Who performed the action, neutral user id when the engine reports one. */actorId?: string;- /** Affected users (join/leave), neutral ids. Empty for metadata updates. */+ /** Affected users (join/leave), or the users asking to join (join_request), neutral ids. Empty for metadata updates. */participantIds: string[];/** Metadata delta for kind 'update'; absent or partially populated for join/leave. */changes?: { subject?: string; description?: string; announce?: boolean; locked?: boolean };@@ -667,9 +693,9 @@ export interface EngineEventCallbacks {onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;/**- * Fired on group membership changes (join/leave) and group metadata updates- * (subject/description/announce/locked). The `kind` selects the consumer event name- * (`group.join` / `group.leave` / `group.update`).+ * Fired on group membership changes (join/leave), group metadata updates+ * (subject/description/announce/locked), and pending join requests. The `kind` selects the+ * consumer event name (`group.join` / `group.leave` / `group.update` / `group.join_request`).*/onGroupEvent?: (event: GroupEvent) => void;/**@@ -891,6 +917,20 @@ export interface IWhatsAppEngine {* Known values: 86400 (24h), 604800 (7d), 7776000 (90d).*/setGroupEphemeral(groupId: string, durationSec: number): Promise<void>;+ /**+ * Pending join requests for a group with join-approval turned on. Admin-only on both engines;+ * a non-admin's read is refused by the engine and surfaced as-is.+ */+ getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]>;+ /**+ * Approve pending join requests — the named participants, or EVERY pending request when+ * `participants` is omitted. Per-participant outcomes follow the membership-write contract+ * (see addParticipants); the all-failed/no-outcome guards apply only when participants were+ * NAMED — approving an empty queue is a no-op that resolves [].+ */+ approveGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]>;+ /** Reject pending join requests; same contract as approveGroupMembershipRequests. */+ rejectGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]>;// Message OperationsdeleteMessage(chatId: string, messageId: string, forEveryone?: boolean): Promise<void>;diff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex a1443912e..1e6194c59 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -27,6 +27,7 @@ export const SUBSCRIBABLE_EVENTS = ['group.join','group.leave','group.update',+ 'group.join_request','call.received','status.received','presence.update',diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex cca8b767a..664c6df0b 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -652,6 +652,16 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'group.update', data);}+ /**+ * Emit a pending join request (someone asked to join a group the account admins, join-approval+ * on). Payload mirrors the `group.join_request` webhook:+ * `{ groupId, participantIds, timestamp, actorId? }` — participantIds are the users asking to+ * join; actorId is who created the request when the engine reports one.+ */+ emitGroupJoinRequest(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'group.join_request', data);+ }+/*** Emit an incoming-call notification (a call is ringing). Payload mirrors the `call.received`* webhook: `{ callId, from, isVideo, isGroup, timestamp }`.diff --git a/src/modules/group/dto/group-response.dto.ts b/src/modules/group/dto/group-response.dto.tsindex 97c4bdfa1..b8ed4b455 100644--- a/src/modules/group/dto/group-response.dto.ts+++ b/src/modules/group/dto/group-response.dto.ts@@ -181,6 +181,30 @@ export class ParticipantsOperationResponseDto extends GroupAckResponseDto {results!: ParticipantOperationResultDto[];}+export class GroupMembershipRequestDto {+ @ApiProperty({ description: 'Neutral id of the user asking to join.', example: '[email protected]' })+ participantId!: string;++ @ApiPropertyOptional({+ description: 'Who created the request, when the engine reports it (differs from the requester on a non-admin add).',+ example: '[email protected]',+ })+ addedById?: string;++ @ApiPropertyOptional({+ description: 'How the request was made, when the engine reports it.',+ enum: ['invite_link', 'non_admin_add', 'linked_group_join'],+ example: 'invite_link',+ })+ method?: string;++ @ApiPropertyOptional({+ description: 'Unix seconds the request was created, when the engine reports it.',+ example: 1754700000,+ })+ requestedAt?: number;+}+export class GroupJoinedResponseDto {@ApiProperty({ description: 'Always true — a failure is reported as a non-2xx status.', example: true })success!: boolean;diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.tsindex 50036b36a..60ebc1bdc 100644--- a/src/modules/group/dto/group.dto.spec.ts+++ b/src/modules/group/dto/group.dto.spec.ts@@ -8,6 +8,8 @@ import {GroupDescriptionDto,JoinGroupDto,GroupSettingsDto,+ MembershipRequestActionDto,+ GROUP_PARTICIPANTS_MAX,} from './group.dto';// Mirror the global ValidationPipe: whitelist + forbidNonWhitelisted from src/main.ts, AND the@@ -136,3 +138,32 @@ describe('group DTO validation', () => {expect(instanceFor(GroupSettingsDto, { ephemeralSeconds: '0' }).ephemeralSeconds).toBe(0);});});++/**+ * The approve/reject body draws a sharp line between "omitted" (act on EVERY pending request) and+ * every other shape. An explicit `null` and an empty array must fail validation rather than be+ * read as approve-all — the explicit-null discipline of SetGroupPictureDto — because both are the+ * classic malformed-client shapes, and misreading either mass-approves join requests.+ */+describe('MembershipRequestActionDto', () => {+ it('accepts an empty body — approve/reject ALL pending', async () => {+ expect(await errorsFor(MembershipRequestActionDto, {})).toHaveLength(0);+ });++ it('accepts a named requester list', async () => {+ expect(await errorsFor(MembershipRequestActionDto, { participants: ['[email protected]'] })).toHaveLength(0);+ });++ it('rejects an explicit null — malformed, not approve-all', async () => {+ expect((await errorsFor(MembershipRequestActionDto, { participants: null })).length).toBeGreaterThan(0);+ });++ it('rejects an empty array — naming nobody is not the same claim as "all"', async () => {+ expect((await errorsFor(MembershipRequestActionDto, { participants: [] })).length).toBeGreaterThan(0);+ });++ it('rejects a list beyond the shared participant cap', async () => {+ const oversized = Array.from({ length: GROUP_PARTICIPANTS_MAX + 1 }, (_, i) => `62${i}@c.us`);+ expect((await errorsFor(MembershipRequestActionDto, { participants: oversized })).length).toBeGreaterThan(0);+ });+});diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex 10b3d9166..e72711f3d 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -64,6 +64,26 @@ export class ParticipantsDto {participants!: string[];}+/**+ * Approve/reject body for the membership-request routes. `participants` names specific requesters;+ * omitted (or an empty body) means EVERY pending request — mirroring both engines' act-on-all form.+ * ValidateIf (not @IsOptional) so an explicit `null` fails validation (400) instead of being read+ * as approve-all: misreading a malformed client shape here mass-approves join requests.+ */+export class MembershipRequestActionDto {+ @ApiPropertyOptional({+ description: 'Requester WhatsApp IDs (e.g. [email protected]). Omit to act on every pending request.',+ type: [String],+ maxItems: GROUP_PARTICIPANTS_MAX,+ })+ @ValidateIf(o => (o as MembershipRequestActionDto).participants !== undefined)+ @IsArray()+ @ArrayNotEmpty()+ @ArrayMaxSize(GROUP_PARTICIPANTS_MAX)+ @IsString({ each: true })+ participants?: string[];+}+export class GroupSubjectDto {@ApiProperty({ description: 'New group subject/name', maxLength: GROUP_NAME_MAX_LENGTH })@IsString()diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.tsindex ba13d141f..1373b056d 100644--- a/src/modules/group/group.controller.spec.ts+++ b/src/modules/group/group.controller.spec.ts@@ -86,6 +86,44 @@ describe('GroupController join + settings', () => {// the same path shape is unreachable — `GET /groups/join-info` would arrive at `GET /groups/:groupId`// with groupId='join-info' and be looked up as a group. Reading the decorators back off the class is// the only way to catch a reordering, since both routes keep working in isolation either way.+describe('GroupController membership requests', () => {+ const build = (service: Partial<Record<keyof GroupService, jest.Mock>>) => {+ const controller = new GroupController(service as unknown as GroupService);+ return { controller, service };+ };++ it('GET :groupId/membership-requests returns the pending queue as a bare array', async () => {+ const requests = [{ participantId: '[email protected]', method: 'invite_link', requestedAt: 1754700000 }];+ const { controller, service } = build({ getGroupMembershipRequests: jest.fn().mockResolvedValue(requests) });++ await expect(controller.getMembershipRequests('s1', 'g1')).resolves.toEqual(requests);+ expect(service.getGroupMembershipRequests).toHaveBeenCalledWith('s1', 'g1');+ });++ it.each([+ ['approve', 'approveMembershipRequests' as const, 'approveGroupMembershipRequests' as const, 'approved'],+ ['reject', 'rejectMembershipRequests' as const, 'rejectGroupMembershipRequests' as const, 'rejected'],+ ])('POST :groupId/membership-requests/%s returns the per-participant results', async (_a, route, svcMethod, verb) => {+ const results = [{ id: '[email protected]', success: true, status: 200 }];+ const { controller, service } = build({ [svcMethod]: jest.fn().mockResolvedValue(results) });++ await expect(controller[route]('s1', 'g1', { participants: ['[email protected]'] })).resolves.toEqual({+ success: true,+ message: `Membership requests ${verb}`,+ results,+ });+ expect(service[svcMethod]).toHaveBeenCalledWith('s1', 'g1', ['[email protected]']);+ });++ it('an empty body approves ALL pending requests (participants passed as undefined)', async () => {+ const { controller, service } = build({ approveGroupMembershipRequests: jest.fn().mockResolvedValue([]) });++ await controller.approveMembershipRequests('s1', 'g1', {});++ expect(service.approveGroupMembershipRequests).toHaveBeenCalledWith('s1', 'g1', undefined);+ });+});+describe('GroupController route ordering', () => {it('declares the literal join-info route before the :groupId parameter route', () => {const proto = GroupController.prototype as object;diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex c2d43c150..62d0f33f1 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -8,6 +8,7 @@ import {GroupDescriptionDto,JoinGroupDto,GroupSettingsDto,+ MembershipRequestActionDto,SetGroupPictureDto,} from './dto/group.dto';import { RequireRole } from '../auth/decorators/auth.decorators';@@ -19,6 +20,7 @@ import {GroupInviteCodeRevokedResponseDto,GroupJoinInfoDto,GroupJoinedResponseDto,+ GroupMembershipRequestDto,GroupPictureResponseDto,GroupSettingsResponseDto,GroupSummaryDto,@@ -269,6 +271,88 @@ export class GroupController {return { success: true, message: 'Participants demoted from admin', results };}+ @Get(':groupId/membership-requests')+ @ApiOperation({+ summary: 'List pending join requests for a group',+ description:+ 'The join-approval queue of a group the account administers (join-approval mode on). ' ++ 'Admin-only on both engines — a non-admin read is refused. Fields the engine does not ' ++ 'report are omitted rather than defaulted.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'groupId', description: 'Group ID' })+ @ApiResponse({ status: 200, description: 'Pending membership requests', type: [GroupMembershipRequestDto] })+ @ApiResponse({ status: 503, description: 'WhatsApp did not answer within the request budget — retry shortly' })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ async getMembershipRequests(@Param('sessionId') sessionId: string, @Param('groupId') groupId: string) {+ return this.groupService.getGroupMembershipRequests(sessionId, groupId);+ }++ @Post(':groupId/membership-requests/approve')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Approve pending join requests',+ description:+ 'Approves the named requesters, or EVERY pending request when the body names none. ' ++ 'Approving an empty queue is a no-op that returns an empty results list. On whatsapp-web.js ' ++ 'the engine pauses 250-500ms between requesters (upstream anti-abuse pacing), so acting on a ' ++ 'large queue is a proportionally long request.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'groupId', description: 'Group ID' })+ @ApiBody({ type: MembershipRequestActionDto })+ @ApiResponse({+ status: 200,+ description:+ 'Requests processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal of NAMED requesters is an error)',+ type: ParticipantsOperationResponseDto,+ })+ @ApiResponse({ status: 503, description: PARTICIPANTS_503 })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ async approveMembershipRequests(+ @Param('sessionId') sessionId: string,+ @Param('groupId') groupId: string,+ @Body() dto: MembershipRequestActionDto,+ ) {+ const results = await this.groupService.approveGroupMembershipRequests(sessionId, groupId, dto.participants);+ return { success: true, message: 'Membership requests approved', results };+ }++ @Post(':groupId/membership-requests/reject')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Reject pending join requests',+ description:+ 'Rejects the named requesters, or EVERY pending request when the body names none. ' ++ 'Rejecting an empty queue is a no-op that returns an empty results list. On whatsapp-web.js ' ++ 'the engine pauses 250-500ms between requesters (upstream anti-abuse pacing), so acting on a ' ++ 'large queue is a proportionally long request.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'groupId', description: 'Group ID' })+ @ApiBody({ type: MembershipRequestActionDto })+ @ApiResponse({+ status: 200,+ description:+ 'Requests processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal of NAMED requesters is an error)',+ type: ParticipantsOperationResponseDto,+ })+ @ApiResponse({ status: 503, description: PARTICIPANTS_503 })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 403, description: ENGINE_REFUSED_403 })+ async rejectMembershipRequests(+ @Param('sessionId') sessionId: string,+ @Param('groupId') groupId: string,+ @Body() dto: MembershipRequestActionDto,+ ) {+ const results = await this.groupService.rejectGroupMembershipRequests(sessionId, groupId, dto.participants);+ return { success: true, message: 'Membership requests rejected', results };+ }+@Put(':groupId/subject')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Change group name/subject' })diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex 2ab82da4d..b571e1f84 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -247,3 +247,60 @@ describe('GroupService join-info preview', () => {);});});++describe('GroupService membership requests', () => {+ const makeService = (engine: Partial<IWhatsAppEngine>, pacing: SendPacingService = inertPacing()) => {+ const engines = new EngineRegistry();+ engines.set('s1', engine as IWhatsAppEngine);+ return { svc: new GroupService(engines, pacing), pacing };+ };++ it('delegates the pending-request list to the engine', async () => {+ const requests = [{ participantId: '[email protected]', method: 'invite_link', requestedAt: 1754700000 }];+ const getGroupMembershipRequests = jest.fn().mockResolvedValue(requests);++ const { svc } = makeService({ getGroupMembershipRequests });++ await expect(svc.getGroupMembershipRequests('s1', 'g1')).resolves.toEqual(requests);+ expect(getGroupMembershipRequests).toHaveBeenCalledWith('g1');+ });++ it.each([['approveGroupMembershipRequests' as const], ['rejectGroupMembershipRequests' as const]])(+ '%s forwards the named participants and the results verbatim',+ async method => {+ const results = [{ id: '[email protected]', success: true, status: 200 }];+ const engineFn = jest.fn().mockResolvedValue(results);++ const { svc } = makeService({ [method]: engineFn });++ await expect(svc[method]('s1', 'g1', ['[email protected]'])).resolves.toEqual(results);+ expect(engineFn).toHaveBeenCalledWith('g1', ['[email protected]']);+ },+ );++ it('passes an omitted participant list through as undefined (approve/reject ALL pending)', async () => {+ const approveGroupMembershipRequests = jest.fn().mockResolvedValue([]);++ const { svc } = makeService({ approveGroupMembershipRequests });++ await expect(svc.approveGroupMembershipRequests('s1', 'g1')).resolves.toEqual([]);+ expect(approveGroupMembershipRequests).toHaveBeenCalledWith('g1', undefined);+ });++ it('does NOT draw on the cold-reachout budget — the requesters asked for the contact', async () => {+ const approveGroupMembershipRequests = jest.fn().mockResolvedValue([]);+ const assertReachoutAllowed = jest.fn().mockResolvedValue(undefined);++ const { svc } = makeService({ approveGroupMembershipRequests }, {+ assertReachoutAllowed,+ } as unknown as SendPacingService);+ await svc.approveGroupMembershipRequests('s1', 'g1', ['[email protected]']);++ expect(assertReachoutAllowed).not.toHaveBeenCalled();+ });++ it('throws 400 when the session is not started', () => {+ const svc = new GroupService(new EngineRegistry(), inertPacing());+ expect(() => svc.getGroupMembershipRequests('s1', 'g1')).toThrow(BadRequestException);+ });+});diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex ff68128f9..503d4b901 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -70,6 +70,23 @@ export class GroupService {return this.getEngine(sessionId).demoteParticipants(groupId, participants);}+ getGroupMembershipRequests(sessionId: string, groupId: string) {+ return this.getEngine(sessionId).getGroupMembershipRequests(groupId);+ }++ /**+ * Deliberately NOT paced, unlike addParticipants: the people here asked for the contact+ * themselves, so approving (or rejecting) them draws nothing from the cold-reachout budget.+ * `participants` omitted means every pending request.+ */+ approveGroupMembershipRequests(sessionId: string, groupId: string, participants?: string[]) {+ return this.getEngine(sessionId).approveGroupMembershipRequests(groupId, participants);+ }++ rejectGroupMembershipRequests(sessionId: string, groupId: string, participants?: string[]) {+ return this.getEngine(sessionId).rejectGroupMembershipRequests(groupId, participants);+ }+setGroupSubject(sessionId: string, groupId: string, subject: string) {return this.getEngine(sessionId).setGroupSubject(groupId, subject);}diff --git a/src/modules/session/session-engine-leaf-events.ts b/src/modules/session/session-engine-leaf-events.tsindex b12e33468..291d8299e 100644--- a/src/modules/session/session-engine-leaf-events.ts+++ b/src/modules/session/session-engine-leaf-events.ts@@ -127,10 +127,11 @@ export class SessionEngineLeafEvents {/*** Fan a neutral engine GroupEvent out to consumers: the WebSocket room and the webhook stream.- * The `kind` selects the event name (`group.join` / `group.leave` / `group.update`); the payload- * is the same plain camelCase shape on both channels, with `kind` itself carried by the name.- * There is no persistence here — group membership/metadata lives in the engine, not the message- * store — so unlike message edits there is nothing to apply before notifying.+ * The `kind` selects the event name (`group.join` / `group.leave` / `group.update` /+ * `group.join_request`); the payload is the same plain camelCase shape on both channels, with+ * `kind` itself carried by the name. There is no persistence here — group membership/metadata+ * lives in the engine, not the message store — so unlike message edits there is nothing to+ * apply before notifying.*/dispatchGroupEvent(id: string, event: GroupEvent): void {const payload: Record<string, unknown> = {@@ -159,6 +160,10 @@ export class SessionEngineLeafEvents {this.eventsGateway.emitGroupUpdate(id, payload);void this.webhookService.dispatch(id, 'group.update', payload);break;+ case 'join_request':+ this.eventsGateway.emitGroupJoinRequest(id, payload);+ void this.webhookService.dispatch(id, 'group.join_request', payload);+ break;}}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 0886b91e3..09c2a619d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -179,6 +179,7 @@ describe('SessionService', () => {emitMessageReaction: jest.fn(),emitMessageEdited: jest.fn(),emitGroupJoin: jest.fn(),+ emitGroupJoinRequest: jest.fn(),emitGroupLeave: jest.fn(),emitGroupUpdate: jest.fn(),emitCallReceived: jest.fn(),@@ -5383,6 +5384,23 @@ describe('SessionService', () => {expect(eventsGateway.emitGroupUpdate).not.toHaveBeenCalled();});+ it('dispatches a join request as group.join_request — the join-approval queue grew', async () => {+ const onGroupEvent = await startAndCaptureGroupCallback();++ onGroupEvent(groupEvent({ kind: 'join_request' }));++ const payload = {+ groupId: '[email protected]',+ participantIds: ['[email protected]'],+ timestamp: 1700000900,+ actorId: '[email protected]',+ };+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'group.join_request', payload);+ expect(eventsGateway.emitGroupJoinRequest).toHaveBeenCalledWith('sess-uuid-1', payload);+ // A request to join is NOT a join: the two names must never cross.+ expect(eventsGateway.emitGroupJoin).not.toHaveBeenCalled();+ });+it('dispatches a leave as group.leave', async () => {const onGroupEvent = await startAndCaptureGroupCallback();diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 955e68e91..b4772960a 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -53,6 +53,7 @@ export const WEBHOOK_EVENTS = ['group.join','group.leave','group.update',+ 'group.join_request','call.received','call.accepted','call.rejected',diff --git a/src/modules/webhook/utils/idempotency.util.spec.ts b/src/modules/webhook/utils/idempotency.util.spec.tsindex 91c686475..37b956048 100644--- a/src/modules/webhook/utils/idempotency.util.spec.ts+++ b/src/modules/webhook/utils/idempotency.util.spec.ts@@ -209,6 +209,19 @@ describe('Idempotency Utils', () => {expect(key).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_join_2026-07-20T00:00:00\.000Z$/);});+ it('keys group.join_request like group.join — a reject-then-re-request must stay a distinct event', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };++ const key = generateIdempotencyKey('group.join_request', data, at);++ expect(key).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_join_request_2026-07-20T00:00:00\.000Z$/);+ // Occurrence salt: the same user asking again later is a new event, not a duplicate.+ expect(generateIdempotencyKey('group.join_request', data, '2026-07-20T01:00:00.000Z')).not.toBe(key);+ // Retry-stable: the same dispatch regenerates the same key.+ expect(generateIdempotencyKey('group.join_request', data, at)).toBe(key);+ });+it('is retry-stable for group.join: the same occurrence regenerates the same key', () => {const at = '2026-07-20T00:00:00.000Z';const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex c44800205..302e7a5c2 100644--- a/src/modules/webhook/utils/idempotency.util.ts+++ b/src/modules/webhook/utils/idempotency.util.ts@@ -121,6 +121,11 @@ export function generateIdempotencyKey(event: string, data: Record<string, unkno// Same recurring-occurrence treatment as group.join.return `grp_${toStr(data.groupId)}_${hashData({ participants: data.participantIds })}_leave${occurrence}`;+ case 'group.join_request':+ // Same recurring-occurrence treatment as group.join: a user whose request was rejected can+ // legitimately ask again, so the occurrence salt keeps the re-request deliverable.+ return `grp_${toStr(data.groupId)}_${hashData({ participants: data.participantIds })}_join_request${occurrence}`;+case 'group.update':// Key on WHAT changed (a subject set to "X" twice is one logical change; announce toggling// back and forth is several), salted per occurrence so identical repeat updates stay distinct.