Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): add createCallLink on both engines
Yudhi Armyndharis438babf1e5d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbfb6daba..3dfa5a18d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- An onboarding modal the "What's new" probe does not recognise is now logged once with its heading and confirm-button labels (`onboarding_dialog_unrecognized`), so it can be covered via `WWEBJS_ONBOARDING_CONTINUE_LABELS` before WhatsApp unlinks the companion. Refs #1072.- `npm run check:sdk-events` compares each typed SDK's webhook event list to the contract, so an event the gateway accepts can no longer be missing from the SDKs.- `npm run check:sdk-docs` compares the SDK design doc and the coverage tables to the shipped client surface, so a client method can no longer ship undocumented.+- `POST /sessions/:sessionId/calls/link` generates a shareable WhatsApp call link on both engines, returning the finished `https://call.whatsapp.com/…` URL; a WhatsApp-side failure answers `403` rather than a success carrying an empty link.### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 63b9d5cc5..a2098ee0e 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6026,6 +6026,45 @@ orIncoming-call management. A `call.received` webhook/socket event (§6.6) announces an incoming ringing call and carries the `callId` used below.+#### POST /api/sessions/:sessionId/calls/link++Generate a shareable WhatsApp call link.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped++**Request body** — `CreateCallLinkDto`++| Field | Type | Required | Constraints | Description |+| ----------- | ------ | -------- | -------------------------- | ----------------------------------------------------- |+| `type` | string | Yes | `@IsIn(['audio','video'])` | Which kind of call the link opens |+| `startTime` | number | Yes | `@IsInt`; `@Min(1)` | Epoch **milliseconds** the call is scheduled to start |++```json+{ "type": "video", "startTime": 1800000000000 }+```++**Response** `200`++```json+{ "link": "https://call.whatsapp.com/video/XxXxXxXxXxXxXx" }+```++> **`startTime` is required on purpose.** whatsapp-web.js generates an _event-linked_ call and has no+> notion of "no start time", so a link for right now is `Date.now()` rather than an omitted field.+> Sending it in seconds instead of milliseconds produces a link scheduled in 1970.++> **`audio` is the neutral spelling; WhatsApp's own URL path is `/voice/`.** Baileys uses `audio`,+> whatsapp-web.js uses `voice`, and the generated link reads+> `https://call.whatsapp.com/voice/…` either way.++> **A refusal is a `403`, never a `200` with an empty link.** whatsapp-web.js returns an empty string+> when generation fails and Baileys returns no token; both become `EngineRefusedError`, because a+> caller handed `{ "link": "" }` — or a bare prefix with nothing after it — would pass it to a user+> before discovering it is dead.++**Errors:** `400` session not ready, or an invalid `type`/`startTime` · `401` missing/invalid API key ·+`403` WhatsApp generated no link · `503` WhatsApp did not answer within the request budget+#### POST /api/sessions/:sessionId/calls/:callId/rejectReject a currently ringing incoming call. Only a live call can be rejected — the id is valid while the call rings (a short server-side cache); afterwards it expires.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 0fe82a7fa..60df8f9c1 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -3,7 +3,7 @@Three-way comparison of every capability: the **Baileys library** (`@whiskeysockets/baileys`7.0.0-rc13), the **whatsapp-web.js library** (1.34.7), and what **OpenWA actually exposes** throughits adapter layer and REST API — including which "supported" cells only work because OpenWA patches-the installed library. Coverage is total: all 107 `IWhatsAppEngine` methods (29.4), **all 152+the installed library. Coverage is total: all 108 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all5 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.@@ -24,7 +24,7 @@ Statuses used in the tables:Two complementary views:-- **29.4 — the OpenWA contract view.** Rows are the 107 `IWhatsAppEngine` methods; use it to see+- **29.4 — the OpenWA contract view.** Rows are the 108 `IWhatsAppEngine` methods; use it to seewhat a REST caller gets per engine. Source of truth: `src/engine/engine-capability-matrix.ts`(per-cell `evidence` strings cite the exact library `file:symbol` inspected).- **29.5 — the full engine inventory.** Rows are **every method the installed libraries expose**,@@ -36,14 +36,14 @@ Two complementary views:## 29.2 Adapter architectureOpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine-instance behind the neutral `IWhatsAppEngine` interface (107 methods ++instance behind the neutral `IWhatsAppEngine` interface (108 methods +`EngineEventCallbacks`), and all modules go through it:```mermaidflowchart LRsubgraph OpenWA["OpenWA"]API["REST API controllers"] --> SVC["Modules / services"]- SVC --> IF["IWhatsAppEngine - 107 methods"]+ SVC --> IF["IWhatsAppEngine - 108 methods"]IF --> WA["WwebjsAdapter"]IF --> BA["BaileysAdapter"]SVC --> STORE["OpenWA-side stores"]@@ -156,7 +156,7 @@ Rows that are ✅ on **both** engines where one side is patch-dependent: `initiarests on the column-wide 🔧¹ (wwjs) and 🔧⁵ (baileys) — no row runs on stock library code on bothsides.-## 29.4 Full capability matrix — the OpenWA contract view (107 methods)+## 29.4 Full capability matrix — the OpenWA contract view (108 methods)Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide@@ -335,10 +335,11 @@ answers 501.| --------------------- | ------------------- | ------------------ | --------------- || `subscribeToPresence` | ✅ | ❌ lib | ⚠️ baileys only || `rejectCall` | ✅ | ✅ | ✅ |+| `createCallLink` | ✅ | ✅ | ✅ |-**Totals:** 107 methods → 214 adapter cells: **192 ✅, 22 ❌** (2 adapter-gaps, 20-library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **88** methods-work on any engine (86 fully supported + 2 store-backed status reads), **9** are Baileys-only,+**Totals:** 108 methods → 216 adapter cells: **194 ✅, 22 ❌** (2 adapter-gaps, 20+library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **89** methods+work on any engine (87 fully supported + 2 store-backed status reads), **9** are Baileys-only,**9** are wwjs-only (the 2 store-backed rows excluded), **1** (`sendCatalog`) is 501 on both.## 29.5 Full engine method inventory — every library method, mapped to OpenWA@@ -531,7 +532,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| Library method | OpenWA exposure || ------------------------ | ----------------------------------------- || `addOrEditContact` | ✅ `upsertContact` |-| `createCallLink` | ❌ **not exposed** |+| `createCallLink` | ✅ `createCallLink` || `presenceSubscribe` | ✅ `subscribeToPresence` || `removeContact` | ✅ `deleteContact` || `removeCoverPhoto` | ❌ **not exposed** |@@ -703,9 +704,9 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at**Misc** (1)-| Library method | OpenWA exposure |-| ---------------- | ------------------ |-| `createCallLink` | ❌ **not exposed** |+| Library method | OpenWA exposure |+| ---------------- | ------------------- |+| `createCallLink` | ✅ `createCallLink` |### 29.5.3 Supported by BOTH libraries — missing only in OpenWA@@ -713,12 +714,11 @@ The highest-value backlog: capabilities with first-class symbols on **both** engnew `IWhatsAppEngine` method wires both adapters at once. All cross-checked against the installed`.d.ts` files.-| Capability | Baileys symbol | wwjs symbol | Note |-| -------------------------- | -------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------ |-| Create call link | `createCallLink` (`Socket/chats.d.ts:17`) | `createCallLink` (`index.d.ts:342`) | identical shape on both |-| Delete own profile picture | `removeProfilePicture(ownJid)` (`Socket/groups.d.ts:83`) | `deleteProfilePicture` | the Baileys symbol is already wired for `deleteGroupPicture` |-| Channel admin demote | `newsletterDemote` (`Socket/newsletter.d.ts:25`) | `demoteChannelAdmin` | pair with the ❌-exposed invite flows below |-| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |+| Capability | Baileys symbol | wwjs symbol | Note |+| -------------------------- | -------------------------------------------------------- | -------------------------- | ------------------------------------------------------------ |+| Delete own profile picture | `removeProfilePicture(ownJid)` (`Socket/groups.d.ts:83`) | `deleteProfilePicture` | the Baileys symbol is already wired for `deleteGroupPicture` |+| Channel admin demote | `newsletterDemote` (`Socket/newsletter.d.ts:25`) | `demoteChannelAdmin` | pair with the ❌-exposed invite flows below |+| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |Near-misses (both libraries have the area, but the symbol sets only partially overlap — stillworth an interface method): **channel admin invites** (wwjs@@ -868,25 +868,25 @@ adapter boundary — none silently stubs.Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of theadapter sources — re-derive the same way when anything changes:-- **107** interface methods → **214** adapter cells: **192 ✅** / **22 ❌** (2 adapter-gaps, 20+- **108** interface methods → **216** adapter cells: **194 ✅** / **22 ❌** (2 adapter-gaps, 20library-limitations, 0 uncertain), spanning **21** methods.-- Of the 192 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,+- Of the 194 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync) and the whole wwjs column additionallydepends on 🔧¹, the whole Baileys column on 🔧⁵ — so every row rests on a patch on each side,even though no row carries a row-level mark on both.-- REST caller's view: **88** engine-neutral (86 + 2 store-backed status reads), **9** Baileys-only,+- REST caller's view: **89** engine-neutral (87 + 2 store-backed status reads), **9** Baileys-only,**9** wwjs-only, **1** unavailable on both (`sendCatalog`).- Full engine inventory (29.5), split by the exposure legend rather than lumped: Baileys **152**- socket methods — 46 wired into interface methods, 5 internal wiring, 29 plumbing, **72 ❌ not- exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 45 wired,- 2 internal wiring, 1 class plumbing, **33 ❌ not exposed** (25 real capabilities + 8+ socket methods — 47 wired into interface methods, 5 internal wiring, 29 plumbing, **71 ❌ not+ exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 46 wired,+ 2 internal wiring, 1 class plumbing, **32 ❌ not exposed** (24 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).-- **4** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the- cheapest backlog: create-call-link, delete-own-profile-picture, channel admin demote, channel- ownership transfer. (Chat mute/unmute and chat pin/unpin were two of the six; both are now wired —- see `muteChat` and `pinChat`.)+- **3** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the+ cheapest backlog: delete-own-profile-picture, channel admin demote, channel ownership transfer.+ (Chat mute/unmute, chat pin/unpin and create-call-link were three of the six; all three are now+ wired — see `muteChat`, `pinChat` and `createCallLink`.)- **5** install-time patches (4 whatsapp-web.js + 1 Baileys), all exact and self-disabling.- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —diff --git a/openapi.json b/openapi.jsonindex 78564956a..c1276478e 100644--- a/openapi.json+++ b/openapi.json@@ -5903,6 +5903,60 @@]}},+ "/api/sessions/{sessionId}/calls/link": {+ "post": {+ "operationId": "CallController_createLink",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateCallLinkDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "The generated link",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CallLinkResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session is not started, or an invalid type / startTime"+ },+ "403": {+ "description": "WhatsApp generated no link for this request"+ },+ "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. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget. The link may or may not have been created — the gateway stopped waiting for a reply that never came."+ }+ },+ "summary": "Generate a shareable WhatsApp call link",+ "tags": [+ "calls"+ ]+ }+ },"/api/sessions/{sessionId}/calls/{callId}/reject": {"post": {"operationId": "CallController_reject",@@ -13213,6 +13267,42 @@}}},+ "CreateCallLinkDto": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "description": "Which kind of call the link opens. WhatsApp's own URL path for `audio` is `/voice/`.",+ "enum": [+ "audio",+ "video"+ ],+ "example": "video"+ },+ "startTime": {+ "type": "number",+ "description": "Absolute epoch-MILLISECONDS timestamp the call is scheduled to start at. Required: whatsapp-web.js generates an event-linked call and has no notion of \"no start time\", so a link for right now is `Date.now()` rather than an omitted field.",+ "example": 1800000000000+ }+ },+ "required": [+ "type",+ "startTime"+ ]+ },+ "CallLinkResponseDto": {+ "type": "object",+ "properties": {+ "link": {+ "type": "string",+ "description": "The shareable WhatsApp call link.",+ "example": "https://call.whatsapp.com/video/XxXxXxXxXxXxXx"+ }+ },+ "required": [+ "link"+ ]+ },"CallAckResponseDto": {"type": "object","properties": {diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 6a0e0020b..bb26280bc 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -3,6 +3,7 @@ import type * as BaileysLib from '@whiskeysockets/baileys';import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';import { generateSafeLinkPreview } from './safe-link-preview';import {+ CallLinkType,CustomLinkPreview,ChatState,ContactCard,@@ -327,6 +328,28 @@ export class BaileysMessaging {});}+ async createCallLink(type: CallLinkType, startTime: number): Promise<string> {+ this.host.ensureReady();+ const lib = await this.host.loadLib();+ // The socket resolves only the bare `token` attribute of the `link_create` node; the finished+ // link is that token behind one of the library's two exported prefixes. Note the audio prefix+ // WhatsApp itself uses is `/voice/`, which is also what whatsapp-web.js calls the same thing.+ //+ // timeoutMs is passed so the library can retire its own pending query, and the call is ALSO+ // wrapped: baileys' query() swallows its timeout, so an unanswered request would otherwise+ // resolve to nothing and be indistinguishable from a refusal.+ const token = await this.confirmed(+ this.sock().createCallLink(type, { startTime: Math.floor(startTime / 1000) }, this.queryBudgetMs),+ 'the call link',+ );+ if (!token) {+ // A prefix with nothing after it is a dead link that looks like a real one — the caller would+ // hand it to a user and only find out then.+ throw new EngineRefusedError('WhatsApp did not return a call link');+ }+ return `${type === 'video' ? lib.CALL_VIDEO_PREFIX : lib.CALL_AUDIO_PREFIX}${token}`;+ }+async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex aef88ea2b..b353a185a 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -11,6 +11,7 @@ import { BaileysLifecycle } from './baileys-lifecycle';import { BaileysMessaging } from './baileys-messaging';import { BaileysStatus } from './baileys-status';import {+ CallLinkType,ChatState,Channel,ChannelMessage,@@ -750,6 +751,10 @@ export class BaileysAdapter implements IWhatsAppEngine {// ----- Events -----+ createCallLink(type: CallLinkType, startTime: number): Promise<string> {+ return this.messaging.createCallLink(type, startTime);+ }+async rejectCall(callId: string): Promise<void> {return this.events.rejectCall(callId);}diff --git a/src/engine/adapters/create-call-link.spec.ts b/src/engine/adapters/create-call-link.spec.tsnew file mode 100644index 000000000..dc115f91d--- /dev/null+++ b/src/engine/adapters/create-call-link.spec.ts@@ -0,0 +1,125 @@+import type { WASocket } from '@whiskeysockets/baileys';+import type { Client } from 'whatsapp-web.js';+import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';+import { WwebjsProfile } from './wwebjs-profile';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Create-call-link — the third of the §29.5.3 "supported by BOTH libraries, missing only in OpenWA"+ * backlog, and the first where both engines hand back a value rather than a void.+ *+ * They hand back DIFFERENT values, which is the whole design problem. whatsapp-web.js resolves the+ * finished link (`https://call.whatsapp.com/video/…`, or `''` when generation failed). Baileys+ * resolves only the bare `token` attribute off the `link_create` node, and exports the two prefixes+ * separately as `CALL_VIDEO_PREFIX` / `CALL_AUDIO_PREFIX`. The interface promises one shape — the+ * finished link — so the Baileys side assembles it.+ *+ * The vocabularies differ too, and reconcile through the URL rather than by guesswork: Baileys calls+ * it `'audio'` while whatsapp-web.js calls it `'voice'`, and the audio prefix WhatsApp itself uses is+ * `/voice/`. The neutral contract says `'audio'`; each adapter maps.+ *+ * A failure must not become an empty or half-built link. `''` from whatsapp-web.js and a missing+ * token from Baileys are both "no link was generated", and a caller that received+ * `https://call.whatsapp.com/video/` with nothing after it would hand a dead link to a user.+ */++const logger = createLogger('create-call-link.spec');+const START_MS = 1_800_000_000_000; // epoch MILLISECONDS, as muteChat uses+const START_S = 1_800_000_000; // what both libraries want on the wire++describe('BaileysMessaging.createCallLink', () => {+ function makeMessaging(sock: Record<string, jest.Mock>, budgetMs = 500): BaileysMessaging {+ const host = {+ ensureReady: jest.fn(),+ getSocket: () => sock as unknown as WASocket,+ logger,+ toNeutralJid: (j: string) => j,+ toEngineJid: (j: string) => j,+ normalizedSelfJid: () => '[email protected]',+ getEphemeralExpiration: () => undefined,+ toUnixSeconds: () => 1,+ loadLib: () =>+ Promise.resolve({+ CALL_VIDEO_PREFIX: 'https://call.whatsapp.com/video/',+ CALL_AUDIO_PREFIX: 'https://call.whatsapp.com/voice/',+ } as never),+ getStoredMessage: () => Promise.resolve(undefined),+ putStoredMessage: () => undefined,+ recordLidMapping: () => undefined,+ getOnMessageCreate: () => undefined,+ mapMessage: () => Promise.resolve({} as never),+ } as unknown as BaileysMessagingHost;+ return new BaileysMessaging(host, budgetMs);+ }++ it('assembles the video link from the bare token the socket returns', async () => {+ const createCallLink = jest.fn().mockResolvedValue('TOKEN123');+ const link = await makeMessaging({ createCallLink }).createCallLink('video', START_MS);++ expect(link).toBe('https://call.whatsapp.com/video/TOKEN123');+ // Baileys takes the start time in SECONDS, and its own type is 'audio' | 'video'.+ expect(createCallLink).toHaveBeenCalledWith('video', { startTime: START_S }, expect.any(Number));+ });++ it("uses WhatsApp's /voice/ prefix for an audio link", async () => {+ const createCallLink = jest.fn().mockResolvedValue('TOKEN456');+ const link = await makeMessaging({ createCallLink }).createCallLink('audio', START_MS);++ expect(link).toBe('https://call.whatsapp.com/voice/TOKEN456');+ expect(createCallLink).toHaveBeenCalledWith('audio', { startTime: START_S }, expect.any(Number));+ });++ // The failure that would otherwise be silent: a prefix with nothing after it is a dead link that+ // looks like a real one.+ it('refuses to return a prefix-only link when no token came back', async () => {+ const createCallLink = jest.fn().mockResolvedValue(undefined);+ await expect(makeMessaging({ createCallLink }).createCallLink('video', START_MS)).rejects.toThrow(+ /did not return a call link/i,+ );+ });++ it('reports an unanswered query rather than hanging on a silent socket', async () => {+ const createCallLink = jest.fn(() => new Promise<never>(() => undefined));+ await expect(makeMessaging({ createCallLink }, 15).createCallLink('video', START_MS)).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });+});++describe('WwebjsProfile.createCallLink', () => {+ function makeProfile(client: Record<string, jest.Mock>): WwebjsProfile {+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ } as unknown as WwebjsEngineHost;+ return new WwebjsProfile(host);+ }++ it('returns the finished link the client resolves', async () => {+ const createCallLink = jest.fn().mockResolvedValue('https://call.whatsapp.com/video/TOKEN789');+ const link = await makeProfile({ createCallLink }).createCallLink('video', START_MS);++ expect(link).toBe('https://call.whatsapp.com/video/TOKEN789');+ const [startDate, callType] = createCallLink.mock.calls[0] as [Date, string];+ expect(startDate.getTime()).toBe(START_MS);+ expect(callType).toBe('video');+ });++ // whatsapp-web.js rejects anything but 'voice' | 'video', so the neutral 'audio' must be mapped.+ it("maps the neutral 'audio' onto the library's 'voice'", async () => {+ const createCallLink = jest.fn().mockResolvedValue('https://call.whatsapp.com/voice/TOKENABC');+ await makeProfile({ createCallLink }).createCallLink('audio', START_MS);++ expect((createCallLink.mock.calls[0] as [Date, string])[1]).toBe('voice');+ });++ it('treats the empty string as a failure rather than returning it', async () => {+ const createCallLink = jest.fn().mockResolvedValue('');+ await expect(makeProfile({ createCallLink }).createCallLink('video', START_MS)).rejects.toThrow(+ /did not return a call link/i,+ );+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex e9bde9fea..32b3ed317 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -12,6 +12,7 @@ import * as qrcode from 'qrcode';import * as path from 'path';import * as fs from 'fs';import {+ CallLinkType,IWhatsAppEngine,EngineStatus,EngineEventCallbacks,@@ -1005,6 +1006,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin* will not become rejectable again); an unknown id or an expired entry maps to CallNotFoundError* (HTTP 404). A failure of the library's reject() itself propagates as-is.*/+ createCallLink(type: CallLinkType, startTime: number): Promise<string> {+ return this.profile.createCallLink(type, startTime);+ }+async rejectCall(callId: string): Promise<void> {const entry = this.liveCalls.get(callId);this.liveCalls.delete(callId);diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsindex f4465b9d0..0cb538348 100644--- a/src/engine/adapters/wwebjs-profile.ts+++ b/src/engine/adapters/wwebjs-profile.ts@@ -1,5 +1,5 @@import { type Client } from 'whatsapp-web.js';-import { MediaInput } from '../interfaces/whatsapp-engine.interface';+import { CallLinkType, MediaInput } from '../interfaces/whatsapp-engine.interface';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { toMessageMedia } from './wwebjs-messaging';import { type WwebjsEngineHost } from './wwebjs-host';@@ -17,6 +17,20 @@ export class WwebjsProfile {return this.host.getClient();}+ async createCallLink(type: CallLinkType, startTime: number): Promise<string> {+ this.host.ensureReady();+ // whatsapp-web.js rejects any callType outside 'voice' | 'video', so the neutral 'audio' maps+ // here. It floors the Date to seconds itself, so the epoch-milliseconds the contract takes goes+ // straight into the Date.+ const link = await this.client().createCallLink(new Date(startTime), type === 'video' ? 'video' : 'voice');+ if (!link) {+ // Documented as "the link, or an empty string if a generation failed" — returning that empty+ // string would hand the caller a success with nothing in it.+ throw new EngineRefusedError('WhatsApp did not return a call link');+ }+ return link;+ }+async setProfileName(name: string): Promise<void> {this.host.ensureReady();// setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex cdfa66993..fbfb40d25 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -284,6 +284,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"same shapes as approveGroupMembershipRequests with the 'Reject' page action (wwjs Client.js:3044) / the 'reject' update action (baileys groups.js:116-139)",},+ createCallLink: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'baileys createCallLink(type, {startTime}, timeoutMs) (Socket/chats.d.ts:17) resolves the bare link_create token (Socket/chats.js:586-603), assembled behind CALL_VIDEO_PREFIX / CALL_AUDIO_PREFIX (Defaults/index.d.ts:5-6); wwjs Client.createCallLink(startTime, callType) (index.d.ts:342) resolves the finished link or an empty string (Client.js:3212-3235)',+ },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 86f5bbba7..56e9c67af 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -476,6 +476,12 @@ export interface ChatSummary {*/export type ChatState = 'typing' | 'recording' | 'paused';+/**+ * Which kind of call a generated link opens. `audio` is the neutral spelling; Baileys uses the same+ * word, whatsapp-web.js calls it `voice`, and WhatsApp's own URL path is `/voice/`.+ */+export type CallLinkType = 'audio' | 'video';+/*** Engine-neutral message delivery status. Each adapter maps its native delivery signal* (e.g. whatsapp-web.js MessageAck integers, Baileys WAMessageStatus) to this vocabulary,@@ -988,6 +994,17 @@ export interface IWhatsAppEngine {* ringing window, and an unknown or expired callId fails with a not-found error (HTTP 404).*/rejectCall(callId: string): Promise<void>;+ /**+ * Generate a shareable WhatsApp call link, returning the finished `https://call.whatsapp.com/…`+ * URL. `startTime` is an absolute epoch-MILLISECONDS timestamp; both engines take seconds on the+ * wire and each adapter converts.+ *+ * The engines return different things and the adapters reconcile them: whatsapp-web.js resolves+ * the finished link (or `''` on failure), Baileys resolves only the bare token and the adapter+ * assembles it behind the library's own prefix. A WhatsApp-side failure throws rather than+ * returning an empty or prefix-only link, which would look like a working link and is not one.+ */+ createCallLink(type: CallLinkType, startTime: number): Promise<string>;// Contact Extended OperationsgetProfilePicture(contactId: string): Promise<string | null>;diff --git a/src/modules/call/call.controller.spec.ts b/src/modules/call/call.controller.spec.tsindex 241525e20..ccce04b12 100644--- a/src/modules/call/call.controller.spec.ts+++ b/src/modules/call/call.controller.spec.ts@@ -2,6 +2,7 @@ import { BadRequestException } from '@nestjs/common';import { CallController } from './call.controller';import { CallService } from './call.service';import { CallNotFoundError } from '../../common/errors/call-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';describe('CallController', () => {const build = (service: Partial<Record<keyof CallService, jest.Mock>>) => {@@ -9,6 +10,27 @@ describe('CallController', () => {return { controller, service };};+ it('POST link returns the generated link', async () => {+ const { controller, service } = build({+ createCallLink: jest.fn().mockResolvedValue('https://call.whatsapp.com/video/TOKEN'),+ });+ await expect(controller.createLink('s1', { type: 'video', startTime: 1_800_000_000_000 })).resolves.toEqual({+ link: 'https://call.whatsapp.com/video/TOKEN',+ });+ expect(service.createCallLink).toHaveBeenCalledWith('s1', 'video', 1_800_000_000_000);+ });++ // A refusal must reach the caller as a refusal. Returning `{ link: '' }` would be a 200 carrying+ // nothing, which reads as success and hands the caller a link that does not exist.+ it('propagates a WhatsApp-side refusal rather than answering with an empty link', async () => {+ const { controller } = build({+ createCallLink: jest.fn().mockRejectedValue(new EngineRefusedError('WhatsApp did not return a call link')),+ });+ await expect(controller.createLink('s1', { type: 'audio', startTime: 1_800_000_000_000 })).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });+it('POST :callId/reject returns the success envelope', async () => {const { controller, service } = build({ rejectCall: jest.fn().mockResolvedValue(undefined) });await expect(controller.reject('s1', 'CALL1')).resolves.toEqual({ success: true });diff --git a/src/modules/call/call.controller.ts b/src/modules/call/call.controller.tsindex 1f37f0744..5b0cde2cc 100644--- a/src/modules/call/call.controller.ts+++ b/src/modules/call/call.controller.ts@@ -1,6 +1,8 @@-import { Controller, Post, Param, HttpCode, HttpStatus } from '@nestjs/common';+import { Controller, Post, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';import { CallAckResponseDto } from './dto/call-response.dto';+import { CreateCallLinkDto } from './dto/create-call-link.dto';+import { CallLinkResponseDto } from './dto/call-link-response.dto';import { CallService } from './call.service';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -11,6 +13,29 @@ import { ENGINE_NOT_READY_409 } from '../../common/openapi/engine-status-responsexport class CallController {constructor(private readonly callService: CallService) {}+ @Post('link')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Generate a shareable WhatsApp call link' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'The generated link', type: CallLinkResponseDto })+ @ApiResponse({ status: 400, description: 'Session is not started, or an invalid type / startTime' })+ @ApiResponse({ status: 403, description: 'WhatsApp generated no link for this request' })+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer within the request budget. The link may or may not have been created — ' ++ 'the gateway stopped waiting for a reply that never came.',+ })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ async createLink(+ @Param('sessionId') sessionId: string,+ @Body() dto: CreateCallLinkDto,+ ): Promise<CallLinkResponseDto> {+ const link = await this.callService.createCallLink(sessionId, dto.type, dto.startTime);+ return { link };+ }+@Post(':callId/reject')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)diff --git a/src/modules/call/call.service.ts b/src/modules/call/call.service.tsindex 45766aa84..117766e3b 100644--- a/src/modules/call/call.service.ts+++ b/src/modules/call/call.service.ts@@ -1,6 +1,6 @@import { Injectable } from '@nestjs/common';import { EngineRegistry } from '../../engine/engine-registry.service';-import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { CallLinkType, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';/*** Owns engine access for call operations. Controllers depend on this service instead of@@ -24,4 +24,12 @@ export class CallService {rejectCall(sessionId: string, callId: string): Promise<void> {return this.getEngine(sessionId).rejectCall(callId);}++ /**+ * Generate a shareable call link. A WhatsApp-side refusal (no link generated) surfaces as 403 via+ * the adapter's EngineRefusedError rather than as a success carrying an empty string.+ */+ createCallLink(sessionId: string, type: CallLinkType, startTime: number): Promise<string> {+ return this.getEngine(sessionId).createCallLink(type, startTime);+ }}diff --git a/src/modules/call/dto/call-link-response.dto.ts b/src/modules/call/dto/call-link-response.dto.tsnew file mode 100644index 000000000..4c18324a3--- /dev/null+++ b/src/modules/call/dto/call-link-response.dto.ts@@ -0,0 +1,9 @@+import { ApiProperty } from '@nestjs/swagger';++export class CallLinkResponseDto {+ @ApiProperty({+ description: 'The shareable WhatsApp call link.',+ example: 'https://call.whatsapp.com/video/XxXxXxXxXxXxXx',+ })+ link!: string;+}diff --git a/src/modules/call/dto/create-call-link.dto.ts b/src/modules/call/dto/create-call-link.dto.tsnew file mode 100644index 000000000..eb733317f--- /dev/null+++ b/src/modules/call/dto/create-call-link.dto.ts@@ -0,0 +1,24 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsIn, IsInt, IsString, Min } from 'class-validator';++export class CreateCallLinkDto {+ @ApiProperty({+ description: "Which kind of call the link opens. WhatsApp's own URL path for `audio` is `/voice/`.",+ enum: ['audio', 'video'],+ example: 'video',+ })+ @IsString()+ @IsIn(['audio', 'video'])+ type!: 'audio' | 'video';++ @ApiProperty({+ description:+ 'Absolute epoch-MILLISECONDS timestamp the call is scheduled to start at. Required: ' ++ 'whatsapp-web.js generates an event-linked call and has no notion of "no start time", so a ' ++ 'link for right now is `Date.now()` rather than an omitted field.',+ example: 1800000000000,+ })+ @IsInt()+ @Min(1)+ startTime!: number;+}