Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(groups): control who may add participants via memberAddMode
Yudhi Armyndharis6d6ea5eab176
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84be638ad..f862a9ef8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **`memberAddMode` on group settings — who may add participants.** `PUT /groups/:groupId/settings`+ accepts `memberAddMode: "all" | "admins"`, `GET .../settings` reports it, and `GroupInfo` carries+ it. Supported on both engines. Exposed on the `GroupSettings` shape in all five SDKs.++ The two engines encode this incompatibly, and the API deliberately hides that: Baileys uses a+ boolean where **true means everyone may add**, while whatsapp-web.js stores WhatsApp's own+ `all_member_add`/`admin_add` strings — and types the field as a boolean with the **opposite**+ meaning to Baileys'. Reading it as a plain boolean would silently invert the setting on one engine+ or the other, so both encodings are decoded explicitly and anything unrecognised is reported as+ unknown rather than guessed.++ Within a settings patch, `memberAddMode` is applied *after* `ephemeralSeconds`. That ordering is+ load-bearing: `ephemeralSeconds` is the only field with a deterministic per-engine refusal+ (whatsapp-web.js always `501`s it), so it must fail before anything else has been applied.+- **A chat's messages can be cleared without deleting the chat:**`DELETE /api/sessions/:id/chats/:chatId/messages`. Available in all five SDKs as`chats.clearMessages`. Like `chats/archive`, `success: false` is a defined outcome — an unknowndiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 6fd9ac216..e18a7b201 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2399,12 +2399,17 @@ Read the group's admin-only settings and disappearing-message timer.**Response** `200`-`announce` = only admins can send messages; `locked` = only admins can edit group info. `ephemeralSeconds` is present only when the engine reports a disappearing-message timer.+`announce` = only admins can send messages; `locked` = only admins can edit group info. `ephemeralSeconds` and `memberAddMode` are each present only when the engine reports them.```json-{ "announce": false, "locked": false, "ephemeralSeconds": 604800 }+{ "announce": false, "locked": false, "ephemeralSeconds": 604800, "memberAddMode": "all" }```+`memberAddMode` is `"all"` (any member may add participants) or `"admins"`. Both engines report and+accept it, but they encode it differently underneath — Baileys as a boolean where `true` means+*everyone*, whatsapp-web.js as WhatsApp's own `all_member_add`/`admin_add` strings (its typings claim+a boolean with the opposite sense). The adapters normalise both to these two values.+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `404` group not found#### PUT /api/sessions/:sessionId/groups/:groupId/settings@@ -2427,18 +2432,24 @@ Update group settings. Each present field maps to one engine call; absent fields| announce | boolean | No | boolean | Only admins can send messages || locked | boolean | No | boolean | Only admins can edit group info || ephemeralSeconds | integer | No | ≥ 0 | Disappearing-message timer in seconds (`0` disables). **Baileys only** — whatsapp-web.js returns `501` |+| memberAddMode | string | No | `all` \| `admins` | Who may add participants. Supported on both engines |```json{ "announce": true, "ephemeralSeconds": 86400 }```+> **Ordering within a patch is deliberate.** `ephemeralSeconds` is applied first because it is the+> only field with a deterministic per-engine refusal (whatsapp-web.js always `501`s it); applying+> anything else first would leave a half-applied patch behind when that call throws. `memberAddMode`+> is supported on both engines and is therefore applied after it.+**Response** `200````json{ "success": true, "message": "Group settings updated" }```-**Errors:** `400` session is not started / empty patch / unknown body field · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role · `501` `ephemeralSeconds` on the whatsapp-web.js engine (library limitation)+**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)### 6.4.5 Message Templatesdiff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 02f1c8843..c0da5f2ee 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -168,8 +168,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.-- **85** interface methods, **170** adapter-cells (85 × 2 engines).-- **153** supported cells; **17** not-available cells across **16** methods.+- **86** interface methods, **172** adapter-cells (86 × 2 engines).+- **155** supported cells; **17** not-available cells across **16** methods.- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 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 5dc68f7b7..9d63c32ee 100644--- a/openapi.json+++ b/openapi.json@@ -7896,6 +7896,14 @@"type": "number","description": "Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d)","minimum": 0+ },+ "memberAddMode": {+ "type": "string",+ "description": "Who may add participants: 'all' (any member) or 'admins' (admins only)",+ "enum": [+ "all",+ "admins"+ ]}}},diff --git a/sdk/go/types_group.go b/sdk/go/types_group.goindex 862faac46..e2c24a692 100644--- a/sdk/go/types_group.go+++ b/sdk/go/types_group.go@@ -75,6 +75,8 @@ type GroupSettings struct {Announce *bool `json:"announce,omitempty"`Locked *bool `json:"locked,omitempty"`EphemeralSeconds *int `json:"ephemeralSeconds,omitempty"`+ // MemberAddMode is "all" (any member may add participants) or "admins".+ MemberAddMode *string `json:"memberAddMode,omitempty"`}// ListGroupsQuery paginates the group list.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.javaindex e50b3efe4..197c4bf6e 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java@@ -7,7 +7,7 @@ package com.rmyndharis.openwa.model;* settings that were set. Setting {@code ephemeralSeconds} returns HTTP 501 on the whatsapp-web.js* engine.*/-public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralSeconds) {+public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralSeconds, String memberAddMode) {public static Builder builder() {return new Builder();}@@ -16,6 +16,7 @@ public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralSprivate Boolean announce;private Boolean locked;private Integer ephemeralSeconds;+ private String memberAddMode;/** Only admins can send messages. */public Builder announce(Boolean v) {@@ -30,13 +31,19 @@ public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralS}/** Disappearing-message timer in seconds ({@code 0} disables). Not supported on the whatsapp-web.js engine. */+ /** Who may add participants: "all" (any member) or "admins" (admins only). */+ public Builder memberAddMode(String v) {+ this.memberAddMode = v;+ return this;+ }+public Builder ephemeralSeconds(Integer v) {this.ephemeralSeconds = v;return this;}public GroupSettings build() {- return new GroupSettings(announce, locked, ephemeralSeconds);+ return new GroupSettings(announce, locked, ephemeralSeconds, memberAddMode);}}}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 032c3c1a2..88a151f67 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -497,6 +497,9 @@ export interface JoinGroupResponse {}/** Group settings as returned by `GET /sessions/:id/groups/:groupId/settings`. */+/** Who may add participants to a group. */+export type GroupMemberAddMode = 'all' | 'admins';+export interface GroupSettingsResponse {/** Only admins can send messages (announce group). */announce?: boolean;@@ -504,6 +507,8 @@ export interface GroupSettingsResponse {locked?: boolean;/** Disappearing-messages timer in seconds; 0 disables. Known values: 86400 (24h), 604800 (7d), 7776000 (90d). */ephemeralSeconds?: number;+ /** Who may add participants: 'all' (any member) or 'admins' (admins only). */+ memberAddMode?: GroupMemberAddMode;}/**diff --git a/sdk/php/src/Resources/GroupsResource.php b/sdk/php/src/Resources/GroupsResource.phpindex 2eb05fae0..ed208bab1 100644--- a/sdk/php/src/Resources/GroupsResource.php+++ b/sdk/php/src/Resources/GroupsResource.php@@ -104,8 +104,9 @@ class GroupsResource/*** Update group settings. At least one of {announce, locked,- * ephemeralSeconds} is required (400 otherwise); ephemeralSeconds responds- * 501 on engines without disappearing-message support (whatsapp-web.js).+ * ephemeralSeconds, memberAddMode} is required (400 otherwise);+ * ephemeralSeconds responds 501 on engines without disappearing-message+ * support (whatsapp-web.js). memberAddMode is 'all' or 'admins'.** @param array<string,mixed> $settings* @return array<string,mixed>diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 20fab5e30..ad4ed4e41 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -480,10 +480,15 @@ class JoinGroupResponse(TypedDict, total=False):# (callers pass plain dicts); the backend validates (empty body -> 400).# `ephemeralSeconds` is the disappearing-messages timer (0 disables); the# whatsapp-web.js engine does not support it (request -> 501).+GroupMemberAddMode = Literal["all", "admins"]++class GroupSettings(TypedDict, total=False):announce: boollocked: boolephemeralSeconds: int+ # Who may add participants: "all" (any member) or "admins" (admins only).+ memberAddMode: GroupMemberAddMode# ── Profile (own account) ─────────────────────────────────────────diff --git a/src/engine/adapters/baileys-group-mapper.ts b/src/engine/adapters/baileys-group-mapper.tsindex 672d36765..f7d55429e 100644--- a/src/engine/adapters/baileys-group-mapper.ts+++ b/src/engine/adapters/baileys-group-mapper.ts@@ -57,6 +57,14 @@ export function mapBaileysGroupInfo(metadata: GroupMetadata, normalizeJid: Normaannounce: metadata.announce,locked: metadata.restrict,ephemeralSeconds: metadata.ephemeralDuration,+ // Baileys decodes member_add_mode to a boolean where TRUE means all_member_add — the opposite+ // sense to the boolean whatsapp-web.js's types describe, hence the explicit mapping here.+ memberAddMode:+ metadata.memberAddMode === undefined+ ? undefined+ : metadata.memberAddMode+ ? ('all' as const)+ : ('admins' as const),linkedParentJID: metadata.linkedParent ?? null,};}diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 5388bdb96..3fae75efb 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -1,5 +1,10 @@import type { WASocket } from '@whiskeysockets/baileys';-import { Group, GroupInfo, ParticipantOperationResult } from '../interfaces/whatsapp-engine.interface';+import {+ Group,+ GroupInfo,+ GroupMemberAddMode,+ ParticipantOperationResult,+} from '../interfaces/whatsapp-engine.interface';import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';@@ -202,6 +207,12 @@ export class BaileysGroups {await this.sock().groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked');}+ async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {+ this.host.ensureReady();+ // A dedicated socket call, not a groupSettingUpdate option.+ await this.sock().groupMemberAddMode(groupId, mode === 'admins' ? 'admin_add' : 'all_member_add');+ }+async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {this.host.ensureReady();await this.sock().groupToggleEphemeral(groupId, durationSec);diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex c9e09064b..4f62f7edc 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -21,6 +21,7 @@ import {EngineStatus,Group,GroupInfo,+ GroupMemberAddMode,IncomingMessage,IWhatsAppEngine,Label,@@ -416,6 +417,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.groups.setGroupInfoAdminsOnly(groupId, adminsOnly);}+ async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {+ return this.groups.setGroupMemberAddMode(groupId, mode);+ }+async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {return this.groups.setGroupEphemeral(groupId, durationSec);}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 65565670d..1c1433160 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -744,6 +744,31 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks});});+ describe('setGroupMemberAddMode', () => {+ const groupChat = (over: Record<string, unknown> = {}) => ({+ getChatById: jest.fn().mockResolvedValue({ isGroup: true, ...over }),+ });++ it("maps 'admins' to adminsOnly=true — the wwjs setter is inverted relative to our vocabulary", async () => {+ const setAddMembersAdminsOnly = jest.fn().mockResolvedValue(true);+ await readyAdapter(groupChat({ setAddMembersAdminsOnly })).setGroupMemberAddMode('[email protected]', 'admins');+ expect(setAddMembersAdminsOnly).toHaveBeenCalledWith(true);+ });++ it("maps 'all' to adminsOnly=false", async () => {+ const setAddMembersAdminsOnly = jest.fn().mockResolvedValue(true);+ await readyAdapter(groupChat({ setAddMembersAdminsOnly })).setGroupMemberAddMode('[email protected]', 'all');+ expect(setAddMembersAdminsOnly).toHaveBeenCalledWith(false);+ });++ it('treats a false result as a refusal (admin rights required), not a silent no-op', async () => {+ const setAddMembersAdminsOnly = jest.fn().mockResolvedValue(false);+ await expect(+ readyAdapter(groupChat({ setAddMembersAdminsOnly })).setGroupMemberAddMode('[email protected]', 'admins'),+ ).rejects.toBeInstanceOf(EngineRefusedError);+ });+ });+describe('clearChatMessages', () => {it('clears via Chat.clearMessages and returns its result', async () => {const clearMessages = jest.fn().mockResolvedValue(true);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 9135ac9ca..6f1c347a2 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -21,6 +21,7 @@ import {Contact,Group,GroupInfo,+ GroupMemberAddMode,ParticipantOperationResult,LocationInput,PollInput,@@ -1508,6 +1509,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.groups.setGroupInfoAdminsOnly(groupId, adminsOnly);}+ setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {+ return this.groups.setGroupMemberAddMode(groupId, mode);+ }+setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {return this.groups.setGroupEphemeral(groupId, durationSec);}diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex c4bb7b767..35a8d20b4 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -2,6 +2,7 @@ import { type Client } from 'whatsapp-web.js';import {Group,GroupInfo,+ GroupMemberAddMode,GroupParticipant,ParticipantOperationResult,} from '../interfaces/whatsapp-engine.interface';@@ -38,6 +39,25 @@ export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): string* methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures,* so the delegate never touches lifecycle state directly.*/+/**+ * Normalise whatsapp-web.js's member-add-mode to the neutral vocabulary.+ *+ * Deliberately handles both encodings. The WA Web group model — and GroupChat.setAddMembersAdminsOnly+ * when it writes back (GroupChat.js:476) — use WhatsApp's `'admin_add'`/`'all_member_add'` strings,+ * but index.d.ts:890 declares the field `boolean` with `true` meaning "only admins", the OPPOSITE+ * sense to Baileys' boolean. Reading it as a plain boolean would therefore be wrong on both engines+ * for different reasons, so each shape is decoded explicitly and anything unrecognised is reported+ * as unknown rather than guessed.+ */+export function normalizeWwebjsMemberAddMode(raw: string | boolean | undefined): GroupMemberAddMode | undefined {+ if (raw === 'admin_add') return 'admins';+ if (raw === 'all_member_add') return 'all';+ // The documented (but not observed) boolean form: true = only admins may add.+ if (raw === true) return 'admins';+ if (raw === false) return 'all';+ return undefined;+}+export class WwebjsGroups {constructor(private readonly host: WwebjsEngineHost) {}@@ -104,6 +124,7 @@ export class WwebjsGroups {announce: groupChat.groupMetadata?.announce,locked: groupChat.groupMetadata?.restrict,ephemeralSeconds: groupChat.groupMetadata?.ephemeralDuration,+ memberAddMode: normalizeWwebjsMemberAddMode(groupChat.groupMetadata?.memberAddMode),linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};} catch (error) {@@ -356,6 +377,19 @@ export class WwebjsGroups {}}+ // Set who may add participants. NOT a groupSettingUpdate option on either engine — wwjs has its+ // own GroupChat setter, and it is inverted relative to our neutral vocabulary: adminsOnly=true+ // means mode 'admins'.+ async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {+ const groupChat = await this.requireGroupChat(groupId);+ const ok = await groupChat.setAddMembersAdminsOnly(mode === 'admins');+ if (!ok) {+ throw new EngineRefusedError(+ `Failed to update the member-add-mode setting for group ${groupId} — admin rights required`,+ );+ }+ }+// Set "only admins can edit group info" (locked/restrict)async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {const groupChat = await this.requireGroupChat(groupId);diff --git a/src/engine/adapters/wwebjs-member-add-mode.spec.ts b/src/engine/adapters/wwebjs-member-add-mode.spec.tsnew file mode 100644index 000000000..95e84cf60--- /dev/null+++ b/src/engine/adapters/wwebjs-member-add-mode.spec.ts@@ -0,0 +1,57 @@+import { normalizeWwebjsMemberAddMode } from './wwebjs-groups';+import { mapBaileysGroupInfo } from './baileys-group-mapper';+import type { GroupMetadata } from '@whiskeysockets/baileys';++/**+ * Member-add-mode is encoded three different ways across the two engines, and two of them are+ * booleans with OPPOSITE meanings. Reading either as a plain boolean silently inverts the setting —+ * a group left open to everyone while the API reports admins-only, or the reverse. These tests pin+ * each encoding to the neutral value it must produce.+ *+ * - whatsapp-web.js runtime: WhatsApp's raw strings 'admin_add' / 'all_member_add'+ * (GroupChat.js:476, and the WA Web group model it reads from).+ * - whatsapp-web.js types: `boolean`, documented as "true = only admins can add"+ * (index.d.ts:885-890) — not what the runtime actually stores, but decoded anyway.+ * - Baileys: `boolean` where TRUE means all_member_add — the OPPOSITE sense+ * (Socket/groups.js:304).+ */+describe('member-add-mode normalisation across engines', () => {+ describe('whatsapp-web.js', () => {+ it.each([+ ['admin_add', 'admins'],+ ['all_member_add', 'all'],+ ])('decodes the raw WhatsApp string %s to %s', (raw, expected) => {+ expect(normalizeWwebjsMemberAddMode(raw)).toBe(expected);+ });++ it.each([+ [true, 'admins'],+ [false, 'all'],+ ])('decodes the documented boolean %s to %s (true = admins-only per index.d.ts)', (raw, expected) => {+ expect(normalizeWwebjsMemberAddMode(raw)).toBe(expected);+ });++ it.each([undefined, '', 'something_else'])('reports %p as unknown rather than guessing', raw => {+ expect(normalizeWwebjsMemberAddMode(raw)).toBeUndefined();+ });+ });++ describe('Baileys', () => {+ const metadata = (memberAddMode: boolean | undefined): GroupMetadata =>+ ({ id: '[email protected]', subject: 'G', participants: [], memberAddMode }) as unknown as GroupMetadata;++ it('decodes true to all — the INVERSE of the whatsapp-web.js boolean', () => {+ expect(mapBaileysGroupInfo(metadata(true)).memberAddMode).toBe('all');+ // Same input value, opposite answer on the other engine. That is the whole hazard.+ expect(normalizeWwebjsMemberAddMode(true)).toBe('admins');+ });++ it('decodes false to admins', () => {+ expect(mapBaileysGroupInfo(metadata(false)).memberAddMode).toBe('admins');+ });++ it('leaves the field undefined when the engine did not report it', () => {+ expect(mapBaileysGroupInfo(metadata(undefined)).memberAddMode).toBeUndefined();+ });+ });+});diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 451aa6f50..aa33d5033 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -270,6 +270,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"wwjs GroupChat.setInfoAdminsOnly(adminsOnly?) (index.d.ts:2216; sets groupMetadata.restrict, GroupChat.js:544); baileys groupSettingUpdate(jid, 'locked'|'unlocked') (Socket/groups.d.ts:41)",},+ setGroupMemberAddMode: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.setAddMembersAdminsOnly(adminsOnly?) → boolean (index.d.ts:2205; false → adapter throws EngineRefusedError); baileys groupMemberAddMode(jid,'admin_add'|'all_member_add') (Socket/groups.d.ts:42). NOT a groupSettingUpdate option on either engine. Read side disagrees between engines and with wwjs's own types: baileys GroupMetadata.memberAddMode is a boolean where true = all_member_add (Socket/groups.js:304), while wwjs stores WhatsApp's raw strings (GroupChat.js:476) despite index.d.ts:890 declaring a boolean with the OPPOSITE sense — both are normalised to 'all'|'admins' at the adapter",+ },setGroupMessagesAdminsOnly: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 6ed0c6cec..f012a752f 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -212,6 +212,14 @@ export interface ParticipantOperationResult {message?: string;}+/**+ * Who may add participants to a group. Neutral vocabulary: the engines disagree on how they encode+ * this — Baileys uses a boolean where `true` means everyone, whatsapp-web.js carries WhatsApp's own+ * `'all_member_add'`/`'admin_add'` strings (despite typing the field as a boolean with the opposite+ * sense) — so adapters normalise to this on the way out and de-normalise on the way in.+ */+export type GroupMemberAddMode = 'all' | 'admins';+export interface GroupInfo {id: string;name: string;@@ -227,6 +235,8 @@ export interface GroupInfo {locked?: boolean;/** Disappearing-messages timer in seconds; 0 or undefined = off. */ephemeralSeconds?: number;+ /** Who may add participants. Undefined when the engine did not report it. */+ memberAddMode?: GroupMemberAddMode;/** JID of the parent community this group is linked to, or null if standalone. */linkedParentJID?: string | null;}@@ -681,6 +691,8 @@ export interface IWhatsAppEngine {setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void>;/** Set the "only admins can edit group info" group setting (WhatsApp locked/restrict). */setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void>;+ /** Set who may add participants to the group. */+ setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void>;/*** Set the group's disappearing-messages timer in seconds; 0 disables it.* Known values: 86400 (24h), 604800 (7d), 7776000 (90d).diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex 4fc830098..68f4f3523 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -34,6 +34,13 @@ export interface GroupMetadataRaw {restrict?: boolean;/** Disappearing-messages timer in seconds, when WA Web reports one on the group model. */ephemeralDuration?: number;+ /**+ * Who may add participants. Typed loosely on purpose: whatsapp-web.js declares this `boolean`+ * (index.d.ts:890, documented as "true = only admins") but actually writes WhatsApp's raw strings+ * `'admin_add'`/`'all_member_add'` (GroupChat.js:476), and the WA Web model it is read from uses+ * the strings too. Accepting both keeps the adapter honest about what can arrive.+ */+ memberAddMode?: string | boolean;}/**@@ -73,6 +80,8 @@ export interface GroupChat extends Omit<Chat, 'isReadOnly' | 'getLabels'> {setMessagesAdminsOnly(adminsOnly?: boolean): Promise<boolean>;/** Resolves false when the account lacks admin rights (does not throw). */setInfoAdminsOnly(adminsOnly?: boolean): Promise<boolean>;+ /** Only admins may add participants when true (index.d.ts:2205). */+ setAddMembersAdminsOnly(adminsOnly?: boolean): Promise<boolean>;}/**diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex de5e885db..3a4dd609f 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -7,11 +7,13 @@ import {IsNotEmpty,MaxLength,IsBoolean,+ IsIn,IsInt,Min,ValidateIf,} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';+import type { GroupMemberAddMode } from '../../../engine/interfaces/whatsapp-engine.interface';// Field caps shared with the agent-tool input schemas (src/core/agent-tools/tools/group.tools.ts)// so MCP and REST enforce the same limits on the equivalent operations.@@ -117,4 +119,12 @@ export class GroupSettingsDto {@IsInt()@Min(0)ephemeralSeconds?: number;++ @ApiPropertyOptional({+ description: "Who may add participants: 'all' (any member) or 'admins' (admins only)",+ enum: ['all', 'admins'],+ })+ @ValidateIf((o: GroupSettingsDto) => o.memberAddMode !== undefined)+ @IsIn(['all', 'admins'])+ memberAddMode?: GroupMemberAddMode;}diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex bce84a5e3..0b9586f84 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -152,6 +152,30 @@ describe('GroupService', () => {expect(engine.setGroupInfoAdminsOnly).not.toHaveBeenCalled();});+ it('keeps memberAddMode BEHIND ephemeralSeconds, so the deterministic 501 still fails first', async () => {+ // memberAddMode is supported on both engines and therefore has no deterministic refusal.+ // Ordering it ahead of ephemeralSeconds would reintroduce exactly the half-applied patch the+ // rule above exists to prevent: the mode would land, then the ephemeral call would 501.+ const engine = {+ setGroupMemberAddMode: jest.fn().mockResolvedValue(undefined),+ setGroupMessagesAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupInfoAdminsOnly: jest.fn().mockResolvedValue(undefined),+ setGroupEphemeral: jest.fn().mockRejectedValue(new EngineNotSupportedError('setGroupEphemeral')),+ };+ const svc = makeService(engine);+ await expect(+ svc.updateGroupSettings('s1', 'g1', { memberAddMode: 'admins', ephemeralSeconds: 86400 }),+ ).rejects.toBeInstanceOf(EngineNotSupportedError);+ expect(engine.setGroupMemberAddMode).not.toHaveBeenCalled();+ });++ it('applies memberAddMode when it is the only field in the patch', async () => {+ const engine = { setGroupMemberAddMode: jest.fn().mockResolvedValue(undefined) };+ const svc = makeService(engine);+ await svc.updateGroupSettings('s1', 'g1', { memberAddMode: 'all' });+ expect(engine.setGroupMemberAddMode).toHaveBeenCalledWith('g1', 'all');+ });+it('names the failed field AND the applied ones when a patch partially applies', async () => {// ephemeralSeconds applied, then announce failed: the client must learn the group is now in a// mixed state (and which subset took effect), not receive a bare engine error.diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex 01a5cfdd0..ff1a1dce9 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -1,6 +1,6 @@import { Injectable, BadRequestException, HttpException, HttpStatus, NotFoundException } from '@nestjs/common';import { EngineRegistry } from '../../engine/engine-registry.service';-import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { GroupMemberAddMode, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { paginate, ListOptions } from '../../common/utils/paginate';/**@@ -77,13 +77,14 @@ export class GroupService {return this.getEngine(sessionId).joinGroupViaInviteCode(inviteCode);}- /** Read the group's announce/locked/ephemeral settings; 404s (via getGroupInfo) when unknown. */+ /** Read the group's announce/locked/ephemeral/member-add settings; 404s (via getGroupInfo) when unknown. */async getGroupSettings(sessionId: string, groupId: string) {const group = await this.getGroupInfo(sessionId, groupId);return {announce: group.announce,locked: group.locked,...(group.ephemeralSeconds !== undefined ? { ephemeralSeconds: group.ephemeralSeconds } : {}),+ ...(group.memberAddMode !== undefined ? { memberAddMode: group.memberAddMode } : {}),};}@@ -104,17 +105,29 @@ export class GroupService {async updateGroupSettings(sessionId: string,groupId: string,- settings: { announce?: boolean; locked?: boolean; ephemeralSeconds?: number },+ settings: { announce?: boolean; locked?: boolean; ephemeralSeconds?: number; memberAddMode?: GroupMemberAddMode },) {- const { announce, locked, ephemeralSeconds } = settings;- if (announce === undefined && locked === undefined && ephemeralSeconds === undefined) {- throw new BadRequestException('At least one of announce, locked, ephemeralSeconds must be provided');+ const { announce, locked, ephemeralSeconds, memberAddMode } = settings;+ if (+ announce === undefined &&+ locked === undefined &&+ ephemeralSeconds === undefined &&+ memberAddMode === undefined+ ) {+ throw new BadRequestException(+ 'At least one of announce, locked, ephemeralSeconds, memberAddMode must be provided',+ );}const engine = this.getEngine(sessionId);const steps: Array<[field: string, apply: () => Promise<unknown>]> = [];if (ephemeralSeconds !== undefined) {steps.push(['ephemeralSeconds', () => engine.setGroupEphemeral(groupId, ephemeralSeconds)]);}+ // After ephemeralSeconds, per the ordering rule above: this field is supported on both engines,+ // so it carries no deterministic refusal and must not displace the one field that does.+ if (memberAddMode !== undefined) {+ steps.push(['memberAddMode', () => engine.setGroupMemberAddMode(groupId, memberAddMode)]);+ }if (announce !== undefined) {steps.push(['announce', () => engine.setGroupMessagesAdminsOnly(groupId, announce)]);}