Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): emit group.join when the session is added to or joins a group
Yudhi Armyndharis31845acb3dd1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 031697b68..5006e1fe4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A failed start in the dashboard that left no engine shows the gateway's error in a toast.- The dashboard closes a session's QR modal when the session fails, or disconnects with no engine left, instead of leaving it spinning.- The dashboard disables a session's Start and Reconnect buttons while its start request is in flight.+- A Baileys session added to or joining a group emits `group.join`, as whatsapp-web.js already did.### Documentationdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e1006bb08..43223bb22 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6869,7 +6869,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `presence.update` | A subscribed chat's presence changed — someone came online, started typing, or stopped. Only actual CHANGES are dispatched: WhatsApp repeats itself freely, and every repeat would otherwise be a delivery | `{ sessionId, chatId, participants: [{ id, state, lastSeen? }], groupOnlineCount? }` — `state` is `available`/`unavailable`/`composing`/`recording`/`paused`; `lastSeen` is epoch **seconds** and absent when the contact hides it. Requires `POST .../presence/subscribe` first, and Baileys — whatsapp-web.js cannot observe presence || `session.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values || `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` |-| `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.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. **Baileys**: a session added to or joining a group reports only its own id in `participantIds` (members added with it are not listed) || `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. |diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 04b2ce36f..ed5582703 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -807,7 +807,7 @@ OpenWA consumes events by normalizing them into `EngineEventCallbacks`; anything| `contacts.upsert` | ✅ | | `newsletter.view` | ❌ || `contacts.update` | ✅ | | `settings.update` | ❌ || `groups.update` | ✅ | | `blocklist.set` | ❌ |-| `groups.upsert` | ❌ | | `blocklist.update` | ❌ |+| `groups.upsert` | ✅ | | `blocklist.update` | ❌ || `group-participants.update` | ✅ | | `labels.association` | ❌ candidate (label-read cache) || `group.join-request` | ✅ | | `labels.edit` | ❌ candidate (label-read cache) || `group.member-tag.update` | ❌ | | `lid-mapping.update` | ✅ |@@ -979,7 +979,7 @@ adapter sources — re-derive the same way when anything changes:3 internal wiring, 1 class plumbing, **34 ❌ not exposed** (26 real capabilities + 8session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minusthose 8 settings; 🔩 plumbing is correctly never exposed.-- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).+- Events: Baileys **34** (16 consumed / 18 dropped), wwjs **31** (16 consumed / 15 dropped).- **0** capabilities in 29.5.3: every capability with first-class symbols on both libraries iseither wired or classified with evidence. Two of them are Baileys-only despite typedwhatsapp-web.js symbols — `demoteChannelAdmin`, whose page function WhatsApp Web no longerdiff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex c2e3d3f29..c76beb21c 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -38,6 +38,7 @@ import type { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter'import { type createLogger } from '../../common/services/logger.service';import { createSilentLogger } from './baileys-logger';import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';+import { parseWaId, userPart } from '../identity/wa-id';/*** Inbound event handling extracted from BaileysAdapter: the socket event handlers@@ -406,6 +407,50 @@ export class BaileysEvents {this.host.getOnGroupEvent()?.(payload);}+ /**+ * Baileys `groups.upsert`: this session was added to or joined a group. Baileys turns the w:gp2+ * `create` notification into this event and a content-less GROUP_CREATE stub, never into+ * `group-participants.update`. It drops the notification's type and reason, so a new group, an add+ * to an existing group and an invite-link join all arrive alike. Each entry is reported as a join of+ * this session's own id through the participants path, which owns the id guard, the authorPn+ * preference and the receipt timestamp. The entry lists the whole group, so members added with the+ * session are not reported.+ */+ handleGroupsUpsert(+ groups: Array<{ id?: string; author?: string; authorPn?: string; owner?: string; ownerPn?: string }>,+ ): void {+ const selfJid = this.host.normalizedSelfJid();+ if (!selfJid) {+ return; // no own id to report as the joining participant+ }+ const phone = userPart(selfJid);+ const lid = this.host.getSocketOrNull()?.user?.lid;+ const lidUser = lid ? userPart(lid) : undefined;+ const isSelf = (jid: string | undefined): boolean => {+ if (!jid) return false;+ const { kind, userPart: user } = parseWaId(jid);+ return kind === 'user' ? user === phone : kind === 'lid' && user === lidUser;+ };+ for (const group of Array.isArray(groups) ? groups : []) {+ // Live, whatsapp-web.js emits no group.join when the session created the group, so that entry is+ // skipped. The acting participant alone does not identify it: an invite-link join may name the+ // joining session there, so the session must also be the group's owner.+ if (+ !group ||+ ((isSelf(group.authorPn) || isSelf(group.author)) && (isSelf(group.ownerPn) || isSelf(group.owner)))+ ) {+ continue;+ }+ this.handleGroupParticipantsUpdate({+ id: group.id,+ author: group.author,+ authorPn: group.authorPn,+ action: 'add',+ participants: [selfJid],+ });+ }+ }+/*** 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 nodiff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 06ec3f2a2..5a9822518 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -141,6 +141,7 @@ export interface BaileysLifecycleHost {logContactEvent: BaileysEvents['logContactEvent'];handleGroupParticipantsUpdate: BaileysEvents['handleGroupParticipantsUpdate'];handleGroupsUpdate: BaileysEvents['handleGroupsUpdate'];+ handleGroupsUpsert: BaileysEvents['handleGroupsUpsert'];handleGroupJoinRequest: BaileysEvents['handleGroupJoinRequest'];handleCallEvents: BaileysEvents['handleCallEvents'];handlePresenceUpdate: BaileysEvents['handlePresenceUpdate'];@@ -302,7 +303,7 @@ export class BaileysLifecycle {}// An internal reconnect (transient drop) overwrites this.sock WITHOUT going through- // disconnect/logout/destroy, so the previous socket's WebSocket and the 15 ev listeners we+ // disconnect/logout/destroy, so the previous socket's WebSocket and the 16 ev listeners we// register below would leak on every reconnect. Tear the prior socket down first. Detach OUR// connection.update listener BEFORE end(): Baileys' own end() synchronously emits a synthetic// connection.update {connection:'close'}, which — if still wired — would re-enter@@ -322,6 +323,7 @@ export class BaileysLifecycle {previous.ev.removeAllListeners('lid-mapping.update');previous.ev.removeAllListeners('group-participants.update');previous.ev.removeAllListeners('groups.update');+ previous.ev.removeAllListeners('groups.upsert');previous.ev.removeAllListeners('group.join-request');previous.ev.removeAllListeners('call');previous.ev.removeAllListeners('presence.update');@@ -432,6 +434,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('groups.upsert', groups => this.host.handleGroupsUpsert(groups));sock.ev.on('group.join-request', event => this.host.handleGroupJoinRequest(event));sock.ev.on('messaging-history.set', history => {this.host.upsertContacts(history.contacts);diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 56791a28c..382fb062a 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -19,7 +19,7 @@ class FakeSock extends EventEmitter {},};public emitter = new EventEmitter();- public user: { id: string; name?: string } | undefined;+ public user: { id: string; lid?: string; name?: string } | undefined;// Baileys' WebSocketClient; the lifecycle reads isOpen after an await to detect a drop in between,// and listens on it for an upgrade response that never became a WebSocket.public ws = Object.assign(new EventEmitter(), { isOpen: true, isConnecting: false });@@ -4269,7 +4269,7 @@ describe('BaileysAdapter group management', () => {});});-describe('BaileysAdapter group events (group-participants.update / groups.update)', () => {+describe('BaileysAdapter group events (group-participants.update / groups.update / groups.upsert)', () => {beforeEach(() => {fakeSock.user = { id: '628999:[email protected]', name: 'Me' };fakeSock.resetEmitter();@@ -4522,6 +4522,101 @@ describe('BaileysAdapter group events (group-participants.update / groups.updateexpect(onGroupEvent).toHaveBeenCalledTimes(1);expect(firstEvent(onGroupEvent).changes).toEqual({ subject: 'Renamed' });});++ // The groups.upsert entry Baileys builds from a w:gp2 `create` notification: the full group metadata+ // plus the acting account as author/authorPn (Socket/messages-recv.js).+ const createdGroup = (over: Record<string, unknown> = {}): Record<string, unknown> => ({+ id: '[email protected]',+ subject: 'New group',+ owner: '555@lid',+ participants: [{ id: '555@lid' }, { id: '777@lid' }, { id: '999000@lid' }],+ author: '555@lid',+ authorPn: '[email protected]',+ ...over,+ });++ it("maps groups.upsert to a join of the session's own id, actor from authorPn, stamped at receipt", async () => {+ const { onGroupEvent } = await readyWithGroupEvents();+ const now = jest.spyOn(Date, 'now').mockReturnValue(1782000000123);++ try {+ fakeSock.fire('groups.upsert', [createdGroup()]);+ } finally {+ now.mockRestore();+ }++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent)).toEqual({+ kind: 'join',+ groupId: '[email protected]',+ actorId: '[email protected]',+ // Only the session itself: the entry lists the whole group, so co-added members are not reported.+ participantIds: ['[email protected]'],+ timestamp: 1782000000,+ });+ });++ it('emits nothing for groups.upsert when the socket has no own id', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();+ fakeSock.user = undefined;++ fakeSock.fire('groups.upsert', [createdGroup()]);++ expect(onGroupEvent).not.toHaveBeenCalled();+ });++ it.each([+ [+ 'authorPn and ownerPn are the session phone number',+ { author: '555@lid', authorPn: '[email protected]', ownerPn: '[email protected]' },+ ],+ ['a lid author and owner are the session lid', { author: '999000@lid', authorPn: undefined, owner: '999000@lid' }],+ ])('skips a groups.upsert entry for a group this session created (%s)', async (_label, author) => {+ fakeSock.user = { id: '628999:[email protected]', lid: '999000:1@lid', name: 'Me' };+ const { onGroupEvent } = await readyWithGroupEvents();++ fakeSock.fire('groups.upsert', [createdGroup({ ...author }), createdGroup({ id: '[email protected]' })]);++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent).groupId).toBe('[email protected]');+ });++ it('reports a groups.upsert entry the session authored for a group another account owns', async () => {+ fakeSock.user = { id: '628999:[email protected]', lid: '999000:1@lid', name: 'Me' };+ const { onGroupEvent } = await readyWithGroupEvents();++ // An invite-link join can name the joining session as the acting participant.+ fakeSock.fire('groups.upsert', [createdGroup({ author: '999000@lid', authorPn: '[email protected]' })]);++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ expect(firstEvent(onGroupEvent)).toMatchObject({ kind: 'join', participantIds: ['[email protected]'] });+ });++ it('emits one join per groups.upsert after an internal reconnect', async () => {+ const { onGroupEvent } = await readyWithGroupEvents();+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const makeWASocket = (jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock }).default;+ makeWASocket.mockClear();+ // The mock factory normally wipes every listener; this reconnect keeps them, so only the+ // lifecycle's own teardown stops the first socket's listener from firing a second time.+ makeWASocket.mockImplementationOnce(() => fakeSock);++ jest.useFakeTimers();+ try {+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ });+ await jest.runAllTimersAsync();+ } finally {+ jest.useRealTimers();+ }+ expect(makeWASocket).toHaveBeenCalledTimes(1);++ fakeSock.fire('groups.upsert', [createdGroup()]);++ expect(onGroupEvent).toHaveBeenCalledTimes(1);+ });});describe('BaileysAdapter call events (call offer) + rejectCall', () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 84268c1f9..306ba08d2 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -185,6 +185,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),+ handleGroupsUpsert: groups => this.events.handleGroupsUpsert(groups),handleGroupJoinRequest: event => this.events.handleGroupJoinRequest(event),handleCallEvents: calls => this.events.handleCallEvents(calls),handlePresenceUpdate: update => this.events.handlePresenceUpdate(update),diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 6cd6b39d5..edd1bee2e 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -618,7 +618,8 @@ export interface ReactionEvent {* - 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), `groups.update` (subject/desc/announce/restrict) and `group.join-request`+ * surfaced), `groups.update` (subject/desc/announce/restrict), `groups.upsert` (this+ * session added to or joining a group; participantIds is the session's own id) 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