Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(groups): preview a group from its invite code before joining

Yudhi Armyndharis349fd3f1b193
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f80f7c5ae..e1ce437a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Preview a group before joining it:** `GET /api/sessions/:sessionId/groups/join-info?code=…`, in
+ all five SDKs. Supported on both engines. Read-only, so it is safe to call on a code from an
+ untrusted source — which is the point, since it is the step you want *before* `POST /groups/join`.
+
+ The response is its own shape rather than the usual group info: a non-member has no participant
+ list, only a count, and only when WhatsApp discloses one. Reusing the member-facing shape would
+ have forced an empty participant array that reads as "this group has no members".
+
+ Only `id` and `name` are guaranteed. Everything else is omitted when the engine did not report it,
+ never defaulted — `whatsapp-web.js` returns an untyped object with no contract, and a
+ `createdAt: 0` would claim the group was created at the epoch. A response carrying no group id at
+ all is a refused invite, so it surfaces as `404` rather than a half-populated success.
+
- **Call outcomes: `call.accepted`, `call.rejected`, `call.missed`** — webhook and socket events for
what happened to a ringing call, correlated to the preceding `call.received` by `callId`. Modelled
in the JavaScript, Python, Go and Java SDKs.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 842f47160..bf8b5cd8e 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2591,6 +2591,41 @@ Revoke the current invite code and generate a new one.
**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+#### GET /api/sessions/:sessionId/groups/join-info
+
+Preview a group from its invite code, **without joining**. Supported on both engines.
+
+**Auth:** API key · **Scope:** session-scoped
+
+Read-only — nothing about the account's membership changes, which is what makes it safe to call on a
+code from an untrusted source, and what makes it the natural step before `POST /groups/join`.
+
+**Query parameters**
+
+| Name | Type | Required | Description |
+| --- | --- | --- | --- |
+| `code` | string | Yes | Group invite code — the part after the invite link |
+
+**Response** `200`
+
+```json
+{
+ "name": "Product team",
+ "description": "Internal coordination",
+ "owner": "[email protected]",
+ "createdAt": 1700000000,
+ "participantCount": 42
+}
+```
+
+There is **no participant list** — the account is not a member — only `participantCount`, and only
+when WhatsApp discloses one. `id` and `name` are always present; every other field is **omitted**
+rather than zeroed when the engine did not report it, because `whatsapp-web.js` returns an untyped
+object with no guaranteed shape and a defaulted `createdAt: 0` would read as "created at the epoch".
+
+**Errors:** `400` no code supplied, or session not started · `401` · `404` no such invite — invalid, expired, or revoked
+
#### POST /api/sessions/:sessionId/groups/join
Join a group via an invite code (the part after `https://chat.whatsapp.com/`).
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index c3cf38fe7..e66d52296 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -174,8 +174,8 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **98** interface methods, **196** adapter-cells (98 × 2 engines).
-- **174** supported cells; **22** not-available cells across **21** methods.
+- **99** interface methods, **198** adapter-cells (99 × 2 engines).
+- **176** 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.json
index 6b522d1a6..956202fdf 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3576,6 +3576,47 @@
]
}
},
+ "/api/sessions/{sessionId}/groups/join-info": {
+ "get": {
+ "description": "Read-only: nothing about the account changes, which is what makes it safe to call on a code from an untrusted source. Supported on both engines.\n\nThere is no participant LIST — the account is not a member — only a count, and only when WhatsApp discloses one. Fields the engine does not report are omitted rather than defaulted, because whatsapp-web.js returns an untyped object with no guaranteed shape.",
+ "operationId": "GroupController_joinInfo",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "code",
+ "required": true,
+ "in": "query",
+ "description": "Group invite code (the part after the invite link)",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "What the invite discloses about the group"
+ },
+ "400": {
+ "description": "Session not started, or no code supplied"
+ },
+ "404": {
+ "description": "No such invite — invalid, expired or revoked"
+ }
+ },
+ "summary": "Preview a group from its invite code, without joining",
+ "tags": [
+ "groups"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/groups/{groupId}": {
"get": {
"operationId": "GroupController_findOne",
diff --git a/sdk/go/groups.go b/sdk/go/groups.go
index 7dbc158ef..ef267dfed 100644
--- a/sdk/go/groups.go
+++ b/sdk/go/groups.go
@@ -1,6 +1,9 @@
package openwa
-import "context"
+import (
+ "context"
+ "net/url"
+)
// GroupsService manages WhatsApp groups.
// Backed by src/modules/group/group.controller.ts.
@@ -27,6 +30,17 @@ func (s *GroupsService) Get(ctx context.Context, sessionID, groupID string) (*Gr
return &out, nil
}
+// JoinInfo previews a group from its invite code WITHOUT joining. Read-only, so it is safe to call
+// on a code from an untrusted source.
+//
+// There is no participant list — the account is not a member — only a count, and only when WhatsApp
+// discloses one. Fields the engine did not report are nil rather than zeroed.
+func (s *GroupsService) JoinInfo(ctx context.Context, sessionID, code string) (*GroupJoinInfo, error) {
+ var out GroupJoinInfo
+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/join-info", url.Values{"code": {code}}, nil, &out)
+ return &out, err
+}
+
// Create creates a group.
func (s *GroupsService) Create(ctx context.Context, sessionID string, body CreateGroupRequest) (*GroupInfo, error) {
var out GroupInfo
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index 89b79c325..18a745352 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -15,6 +15,18 @@ func (q *ListSessionsQuery) values() url.Values {
return v
}
+// GroupJoinInfo is what an invite code discloses about a group before joining. Not GroupInfo: a
+// non-member has no participant list, only a count, and only when WhatsApp discloses one.
+type GroupJoinInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description *string `json:"description,omitempty"`
+ Owner *string `json:"owner,omitempty"`
+ // CreatedAt is Unix seconds.
+ CreatedAt *int64 `json:"createdAt,omitempty"`
+ ParticipantCount *int `json:"participantCount,omitempty"`
+}
+
// CreateChannelRequest is the body for creating a channel.
type CreateChannelRequest struct {
Name string `json:"name"`
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupJoinInfo.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupJoinInfo.java
new file mode 100644
index 000000000..a03716802
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupJoinInfo.java
@@ -0,0 +1,12 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * What an invite code discloses about a group before joining.
+ *
+ * <p>Not {@link GroupInfo}: a non-member has no participant list, only a count, and only when
+ * WhatsApp discloses one. {@code null} means the engine did not report the field.
+ *
+ * @param createdAt Unix seconds
+ */
+public record GroupJoinInfo(
+ String id, String name, String description, String owner, Long createdAt, Integer participantCount) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
index 9b36b6a44..75bebab8e 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
@@ -7,6 +7,7 @@ import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.CreateGroupRequest;
import com.rmyndharis.openwa.model.GroupDescriptionRequest;
import com.rmyndharis.openwa.model.GroupInfo;
+import com.rmyndharis.openwa.model.GroupJoinInfo;
import com.rmyndharis.openwa.model.GroupSettings;
import com.rmyndharis.openwa.model.GroupSubjectRequest;
import com.rmyndharis.openwa.model.GroupSummary;
@@ -105,6 +106,22 @@ public final class GroupsResource {
SuccessResult.class);
}
+ /**
+ * Preview a group from its invite code, WITHOUT joining. Read-only, so it is safe to call on a
+ * code from an untrusted source.
+ *
+ * <p>There is no participant list — the account is not a member — only a count, and only when
+ * WhatsApp discloses one.
+ */
+ public GroupJoinInfo joinInfo(String sessionId, String code) {
+ return client.request(
+ HttpMethod.GET,
+ "/api/sessions/" + encodeSegment(sessionId) + "/groups/join-info",
+ java.util.Map.of("code", code),
+ null,
+ GroupJoinInfo.class);
+ }
+
/** Join a group via an invite code. Returns the joined group id. */
public JoinGroupResponse joinGroup(String sessionId, String inviteCode) {
return client.request(
diff --git a/sdk/javascript/src/resources/groups.ts b/sdk/javascript/src/resources/groups.ts
index c4438c774..719680205 100644
--- a/sdk/javascript/src/resources/groups.ts
+++ b/sdk/javascript/src/resources/groups.ts
@@ -10,6 +10,7 @@ import type { OpenWAClient } from '../client.js';
import type {
CreateGroupRequest,
GroupInfo,
+ GroupJoinInfo,
GroupSettingsResponse,
GroupSummary,
InviteCodeResponse,
@@ -54,6 +55,21 @@ export class GroupsResource {
});
}
+ /**
+ * Preview a group from its invite code, WITHOUT joining. Read-only, so it is safe to call on a
+ * code from an untrusted source.
+ *
+ * There is no participant list — the account is not a member — only a count, and only when
+ * WhatsApp discloses one. Fields the engine did not report are absent rather than zeroed.
+ */
+ joinInfo(sessionId: string, code: string): Promise<GroupJoinInfo> {
+ return this.client.request<GroupJoinInfo>({
+ method: 'GET',
+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/join-info`,
+ query: { code },
+ });
+ }
+
/** Join a group via an invite code. */
joinGroup(sessionId: string, body: JoinGroupRequest): Promise<JoinGroupResponse> {
return this.client.request<JoinGroupResponse>({
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index b441dad95..37954fab1 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -125,6 +125,20 @@ export interface MuteChannelRequest {
mute: boolean;
}
+/**
+ * What an invite code discloses about a group before joining. Not `GroupInfo`: a non-member has no
+ * participant list, only a count, and only when WhatsApp discloses one.
+ */
+export interface GroupJoinInfo {
+ id: string;
+ name: string;
+ description?: string;
+ owner?: string;
+ /** Unix seconds. */
+ createdAt?: number;
+ participantCount?: number;
+}
+
export interface CreateSessionRequest {
/** Alphanumeric + hyphens, 3–50 chars. */
name: string;
diff --git a/sdk/php/src/Resources/GroupsResource.php b/sdk/php/src/Resources/GroupsResource.php
index a5738336c..737a5d7bc 100644
--- a/sdk/php/src/Resources/GroupsResource.php
+++ b/sdk/php/src/Resources/GroupsResource.php
@@ -44,6 +44,18 @@ class GroupsResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups", [], $body);
}
+ /**
+ * Preview a group from its invite code, WITHOUT joining. Read-only, so it is safe to call on a
+ * code from an untrusted source. There is no participant list — the account is not a member —
+ * only a count, and only when WhatsApp discloses one.
+ *
+ * @return array<string,mixed>
+ */
+ public function joinInfo(string $sessionId, string $code): array
+ {
+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/join-info", ['code' => $code]);
+ }
+
/**
* Join a group via an invite code (the token from a chat.whatsapp.com/<code>
* link). Returns {success: true, groupId}.
diff --git a/sdk/python/openwa/resources/groups.py b/sdk/python/openwa/resources/groups.py
index b5ad85373..c929de71c 100644
--- a/sdk/python/openwa/resources/groups.py
+++ b/sdk/python/openwa/resources/groups.py
@@ -9,6 +9,7 @@ from typing import Any, TYPE_CHECKING, TypedDict
from .._http import quote_segment
from ..types import (
+ GroupJoinInfo,
SetGroupPictureRequest,
CreateGroupRequest,
GroupInfo,
@@ -108,6 +109,16 @@ class GroupsResource:
"POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/invite-code/revoke"
)
+ def join_info(self, session_id: str, code: str) -> GroupJoinInfo:
+ """Preview a group from its invite code, WITHOUT joining.
+
+ Read-only, so it is safe to call on a code from an untrusted source. There is no participant
+ list -- the account is not a member -- only a count, and only when WhatsApp discloses one.
+ """
+ return self._http.request(
+ "GET", f"/api/sessions/{quote_segment(session_id)}/groups/join-info", query={"code": code}
+ )
+
def join_group(self, session_id: str, body: JoinGroupRequest) -> JoinGroupResponse:
"""Join a group via an invite code. Requires an OPERATOR-level key."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups/join", body=body)
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index a78dc4ecc..259f7d765 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -87,6 +87,22 @@ class MuteChannelRequest(TypedDict):
mute: bool
+class GroupJoinInfo(TypedDict, total=False):
+ """What an invite code discloses about a group before joining.
+
+ Not GroupInfo: a non-member has no participant list, only a count, and only when WhatsApp
+ discloses one.
+ """
+
+ id: str
+ name: str
+ description: str
+ owner: str
+ # Unix seconds.
+ createdAt: int
+ participantCount: int
+
+
# ── Session ───────────────────────────────────────────────────────
diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.ts
index 802f5ee51..e534f228b 100644
--- a/src/engine/adapters/baileys-groups.ts
+++ b/src/engine/adapters/baileys-groups.ts
@@ -2,11 +2,13 @@ import type { WASocket } from '@whiskeysockets/baileys';
import {
Group,
GroupInfo,
+ GroupJoinInfo,
GroupMemberAddMode,
MediaInput,
ParticipantOperationResult,
} from '../interfaces/whatsapp-engine.interface';
import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';
+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';
import { resolveMediaBuffer } from './baileys-messaging';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';
@@ -175,6 +177,33 @@ export class BaileysGroups {
return (await this.sock().groupRevokeInvite(groupId)) ?? '';
}
+ /**
+ * Preview a group from its invite code. Read-only — nothing about membership changes, which is
+ * what makes it safe to call on a code from an untrusted source.
+ *
+ * Unlike whatsapp-web.js this comes back typed (GroupMetadata), so the mapping is direct. The
+ * participant LIST is dropped even when present: a preview reports a count, and passing a list
+ * through would say more about a group the account has not joined than the other engine can.
+ */
+ async getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
+ this.host.ensureReady();
+ const meta = await this.sock().groupGetInviteInfo(inviteCode);
+ if (!meta?.id) {
+ throw new GroupNotFoundError(inviteCode);
+ }
+ const count = typeof meta.size === 'number' ? meta.size : meta.participants?.length;
+ return {
+ id: this.host.toNeutralJid(meta.id),
+ name: String(meta.subject ?? ''),
+ ...(meta.desc ? { description: String(meta.desc) } : {}),
+ // ownerPn is the phone-dialect twin of a lid owner: prefer it so the neutral id does not
+ // depend on whether the lid->pn mapping happens to be learned yet.
+ ...((meta.ownerPn ?? meta.owner) ? { owner: this.host.toNeutralJid(meta.ownerPn ?? meta.owner!) } : {}),
+ ...(typeof meta.creation === 'number' ? { createdAt: meta.creation } : {}),
+ ...(typeof count === 'number' ? { participantCount: count } : {}),
+ };
+ }
+
async joinGroupViaInviteCode(inviteCode: string): Promise<string> {
this.host.ensureReady();
// Baileys resolves undefined when the invite is invalid/expired/revoked — no group id surfaces —
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 1c7be58c9..ef64aa3a4 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -25,6 +25,7 @@ import {
IncomingMessage,
IWhatsAppEngine,
Label,
+ GroupJoinInfo,
LabelInput,
LocationInput,
MediaInput,
@@ -410,6 +411,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.groups.revokeGroupInviteCode(groupId);
}
+ getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
+ return this.groups.getGroupJoinInfo(inviteCode);
+ }
+
async joinGroupViaInviteCode(inviteCode: string): Promise<string> {
return this.groups.joinGroupViaInviteCode(inviteCode);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 3c7286d4f..36539e4ba 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5800,3 +5800,61 @@ describe('WhatsAppWebJsAdapter channel administration', () => {
await expect(readyAdapter({ getChatById }).muteChannel(CHANNEL, true)).rejects.toBeInstanceOf(ChannelNotFoundError);
});
});
+
+// getInviteInfo is typed Promise<object> and forwards whatever WA Web returns, so there is no shape
+// to rely on. These pin that missing fields are OMITTED rather than defaulted into something a
+// caller would read as fact, and that a shapeless answer becomes a not-found.
+describe('WhatsAppWebJsAdapter group join-info', () => {
+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+
+ it('maps the full shape, taking the disclosed member count', async () => {
+ const getInviteInfo = jest.fn().mockResolvedValue({
+ id: { _serialized: '[email protected]' },
+ subject: 'Team',
+ desc: 'Internal',
+ owner: { _serialized: '[email protected]' },
+ creation: 1700000000,
+ size: 42,
+ });
+
+ await expect(readyAdapter({ getInviteInfo }).getGroupJoinInfo('ABC')).resolves.toEqual({
+ name: 'Team',
+ description: 'Internal',
+ owner: '[email protected]',
+ createdAt: 1700000000,
+ participantCount: 42,
+ });
+ });
+
+ // Absent fields must not become empty strings or zeroes: "created at the epoch" and "owned by
+ // nobody" are claims, and this engine never promised to report them.
+ it('omits everything the engine did not report', async () => {
+ const getInviteInfo = jest.fn().mockResolvedValue({ id: '[email protected]', subject: 'Team' });
+
+ const info = await readyAdapter({ getInviteInfo }).getGroupJoinInfo('ABC');
+
+ expect(info).toEqual({ id: '[email protected]', name: 'Team' });
+ });
+
+ it('falls back to a participants array when no count is disclosed', async () => {
+ const getInviteInfo = jest.fn().mockResolvedValue({ id: '[email protected]', subject: 'T', participants: [{}, {}, {}] });
+
+ await expect(readyAdapter({ getInviteInfo }).getGroupJoinInfo('ABC')).resolves.toMatchObject({
+ participantCount: 3,
+ });
+ });
+
+ // No id means there is no group to describe — the invite was refused, which is a 404 rather than a
+ // half-populated success.
+ it.each([{}, null, { subject: 'Team' }])('reports %p as not-found', async raw => {
+ const getInviteInfo = jest.fn().mockResolvedValue(raw);
+
+ await expect(readyAdapter({ getInviteInfo }).getGroupJoinInfo('ABC')).rejects.toBeInstanceOf(GroupNotFoundError);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index c7b1a78a9..d8928cecc 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -41,6 +41,7 @@ import {
ChatState,
LabelInput,
GroupEvent,
+ GroupJoinInfo,
IncomingCallEvent,
AccountRestriction,
} from '../interfaces/whatsapp-engine.interface';
@@ -1580,6 +1581,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
// Join Group via Invite Code
+ getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
+ return this.groups.getGroupJoinInfo(inviteCode);
+ }
+
joinGroupViaInviteCode(inviteCode: string): Promise<string> {
return this.groups.joinGroupViaInviteCode(inviteCode);
}
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index 465911763..31d1b0bf5 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,
+ GroupJoinInfo,
GroupMemberAddMode,
MediaInput,
GroupParticipant,
@@ -327,6 +328,46 @@ export class WwebjsGroups {
return String(newCode);
}
+ /**
+ * Preview a group from its invite code.
+ *
+ * `Client.getInviteInfo` is typed `Promise<object>` and forwards whatever WA Web's
+ * `queryGroupInvite` returns, so there is no contract to rely on — every field is read
+ * defensively and omitted when absent rather than defaulted into something that reads as fact.
+ * The one thing that IS required is an id: without it there is no group to describe, which means
+ * the invite was refused (invalid, expired or revoked) rather than that a field is missing.
+ */
+ async getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
+ this.host.ensureReady();
+ const raw = (await this.client().getInviteInfo(inviteCode)) as {
+ id?: { _serialized?: string } | string;
+ subject?: string;
+ desc?: string;
+ owner?: { _serialized?: string } | string;
+ creation?: number;
+ size?: number;
+ participants?: unknown[];
+ } | null;
+
+ const id = typeof raw?.id === 'string' ? raw.id : raw?.id?._serialized;
+ if (!id) {
+ throw new GroupNotFoundError(inviteCode);
+ }
+ const owner = typeof raw?.owner === 'string' ? raw.owner : raw?.owner?._serialized;
+ // `size` is the disclosed count; a participants array is used only as a fallback for builds that
+ // send one instead. Neither is synthesised when both are missing.
+ const count = typeof raw?.size === 'number' ? raw.size : raw?.participants?.length;
+
+ return {
+ id,
+ name: String(raw?.subject ?? ''),
+ ...(raw?.desc ? { description: String(raw.desc) } : {}),
+ ...(owner ? { owner } : {}),
+ ...(typeof raw?.creation === 'number' ? { createdAt: raw.creation } : {}),
+ ...(typeof count === 'number' ? { participantCount: count } : {}),
+ };
+ }
+
async joinGroupViaInviteCode(inviteCode: string): Promise<string> {
this.host.ensureReady();
// acceptInvite throws a page-side evaluation error when the invite is refused (invalid/expired/
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 5868f322f..456c8ae33 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -135,6 +135,7 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
createChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
muteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ getGroupJoinInfo: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getChannelById: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getChannelMessages: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index b951d39fd..31fc8020b 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -241,6 +241,24 @@ export interface GroupInfo {
linkedParentJID?: string | null;
}
+/**
+ * What an invite code discloses about a group BEFORE joining it.
+ *
+ * Deliberately not `GroupInfo`: that carries a participant list, and a non-member has no such list —
+ * WhatsApp discloses at most a count. Reusing it would force an empty array that reads as "this
+ * group has no members", which is a different and wrong claim.
+ */
+export interface GroupJoinInfo {
+ id: string;
+ name: string;
+ description?: string;
+ owner?: string;
+ /** Unix seconds the group was created, when the engine reports it. */
+ createdAt?: number;
+ /** How many members, when disclosed. There is no list to give — you are not in the group yet. */
+ participantCount?: number;
+}
+
export interface ContactCard {
name: string;
number: string;
@@ -818,6 +836,11 @@ export interface IWhatsAppEngine {
* Resolves with the joined group's neutral id (`<id>@g.us`).
*/
joinGroupViaInviteCode(inviteCode: string): Promise<string>;
+ /**
+ * What an invite code discloses about a group, without joining it. Read-only: nothing about the
+ * account's membership changes, which is what makes it safe to call on an untrusted code.
+ */
+ getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo>;
/** Set the "only admins can send messages" group setting (WhatsApp announce). */
setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void>;
/** Set the "only admins can edit group info" group setting (WhatsApp locked/restrict). */
diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.ts
index dbb322490..ba13d141f 100644
--- a/src/modules/group/group.controller.spec.ts
+++ b/src/modules/group/group.controller.spec.ts
@@ -81,3 +81,23 @@ describe('GroupController join + settings', () => {
).resolves.toEqual({ success: true, message, results });
});
});
+
+// Nest matches routes in DECLARATION order, so a literal segment declared after a parameter route on
+// 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 route ordering', () => {
+ it('declares the literal join-info route before the :groupId parameter route', () => {
+ const proto = GroupController.prototype as object;
+ const order = Object.getOwnPropertyNames(proto).filter(name => name === 'joinInfo' || name === 'findOne');
+
+ expect(order).toEqual(['joinInfo', 'findOne']);
+ });
+
+ it('keeps join-info a literal path, not a parameter', () => {
+ const handler = Object.getOwnPropertyDescriptor(GroupController.prototype, 'joinInfo')?.value as object;
+ const path: unknown = Reflect.getMetadata('path', handler);
+
+ expect(path).toBe('join-info');
+ });
+});
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index 36323cbcb..269f5f383 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -1,5 +1,5 @@
-import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';
-import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';
+import { Controller, Get, Post, Put, Delete, Param, Body, Query, HttpCode, HttpStatus } from '@nestjs/common';
+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger';
import { GroupService } from './group.service';
import {
CreateGroupDto,
@@ -22,6 +22,27 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';
export class GroupController {
constructor(private readonly groupService: GroupService) {}
+ // MUST stay above @Get(':groupId'): Nest matches in declaration order, and a literal segment
+ // declared after a parameter route is shadowed by it — `join-info` would arrive as a group id.
+ @Get('join-info')
+ @ApiOperation({
+ summary: 'Preview a group from its invite code, without joining',
+ description:
+ 'Read-only: nothing about the account changes, which is what makes it safe to call on a code ' +
+ 'from an untrusted source. Supported on both engines.\n\n' +
+ 'There is no participant LIST — the account is not a member — only a count, and only when ' +
+ 'WhatsApp discloses one. Fields the engine does not report are omitted rather than defaulted, ' +
+ 'because whatsapp-web.js returns an untyped object with no guaranteed shape.',
+ })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiQuery({ name: 'code', description: 'Group invite code (the part after the invite link)' })
+ @ApiResponse({ status: 200, description: 'What the invite discloses about the group' })
+ @ApiResponse({ status: 400, description: 'Session not started, or no code supplied' })
+ @ApiResponse({ status: 404, description: 'No such invite — invalid, expired or revoked' })
+ async joinInfo(@Param('sessionId') sessionId: string, @Query('code') code: string) {
+ return this.groupService.getGroupJoinInfo(sessionId, code);
+ }
+
@Get(':groupId')
@ApiOperation({ summary: 'Get detailed group info' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.ts
index 2a9a26cc1..2ab82da4d 100644
--- a/src/modules/group/group.service.spec.ts
+++ b/src/modules/group/group.service.spec.ts
@@ -6,11 +6,11 @@ import { EngineNotSupportedError } from '../../common/errors/engine-not-supporte
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { SendPacingService } from '../message/send-pacing.service';
-describe('GroupService', () => {
- /** Pacing is off by default; its own spec covers the governor, so here it must simply not refuse. */
- const inertPacing = (): SendPacingService =>
- ({ assertReachoutAllowed: jest.fn().mockResolvedValue(undefined) }) as unknown as SendPacingService;
+/** Pacing is off by default; its own spec covers the governor, so here it must simply not refuse. */
+const inertPacing = (): SendPacingService =>
+ ({ assertReachoutAllowed: jest.fn().mockResolvedValue(undefined) }) as unknown as SendPacingService;
+describe('GroupService', () => {
const makeService = (engine: Partial<IWhatsAppEngine> | undefined, pacing: SendPacingService = inertPacing()) => {
const engines = new EngineRegistry();
if (engine) engines.set('s1', engine as IWhatsAppEngine);
@@ -214,3 +214,36 @@ describe('GroupService', () => {
});
});
});
+
+// A preview must never look like membership: it reports a count, never a participant list, and it
+// changes nothing about the account.
+describe('GroupService join-info preview', () => {
+ const makeService = (engine: Partial<IWhatsAppEngine>) => {
+ const engines = new EngineRegistry();
+ engines.set('s1', engine as IWhatsAppEngine);
+ return new GroupService(engines, inertPacing());
+ };
+
+ it('delegates the trimmed code to the engine', async () => {
+ const getGroupJoinInfo = jest.fn().mockResolvedValue({ id: '[email protected]', name: 'Team' });
+
+ await makeService({ getGroupJoinInfo }).getGroupJoinInfo('s1', ' ABC123 ');
+
+ expect(getGroupJoinInfo).toHaveBeenCalledWith('ABC123');
+ });
+
+ // An empty code would otherwise reach the engine and come back as a confusing not-found rather
+ // than the client error it plainly is.
+ it.each(['', ' ', undefined])('rejects a missing code (%p) before reaching the engine', code => {
+ const getGroupJoinInfo = jest.fn();
+
+ expect(() => makeService({ getGroupJoinInfo }).getGroupJoinInfo('s1', code as string)).toThrow(BadRequestException);
+ expect(getGroupJoinInfo).not.toHaveBeenCalled();
+ });
+
+ it('throws 400 when the session is not started', () => {
+ expect(() => new GroupService(new EngineRegistry(), inertPacing()).getGroupJoinInfo('s1', 'ABC')).toThrow(
+ BadRequestException,
+ );
+ });
+});
diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.ts
index 7e520d4a6..ff68128f9 100644
--- a/src/modules/group/group.service.ts
+++ b/src/modules/group/group.service.ts
@@ -90,6 +90,18 @@ export class GroupService {
return this.getEngine(sessionId).revokeGroupInviteCode(groupId);
}
+ /**
+ * Preview a group from an invite code. The code is required rather than optional-with-a-default:
+ * an empty one would reach the engine and come back as a confusing not-found instead of the
+ * client error it is.
+ */
+ getGroupJoinInfo(sessionId: string, inviteCode: string) {
+ if (!inviteCode?.trim()) {
+ throw new BadRequestException('An invite code is required');
+ }
+ return this.getEngine(sessionId).getGroupJoinInfo(inviteCode.trim());
+ }
+
joinGroupViaInviteCode(sessionId: string, inviteCode: string) {
return this.getEngine(sessionId).joinGroupViaInviteCode(inviteCode);
}