Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat: add unit tests, release workflow, and SDK scaffolds

rmyndharis32a0205c69e6
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 000000000..b81926436
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,112 @@
+name: Release
+
+on:
+ push:
+ tags: ['v*']
+
+env:
+ NODE_VERSION: '20'
+
+permissions:
+ contents: write
+ packages: write
+
+jobs:
+ # ──── Build & Test Gate ───────────────────────────────────────────
+ test:
+ name: Test Gate
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Run tests
+ run: npm test -- --coverage
+
+ - name: Build
+ run: npm run build
+
+ # ──── Create GitHub Release ───────────────────────────────────────
+ release:
+ name: GitHub Release
+ runs-on: ubuntu-latest
+ needs: [test]
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Extract version from tag
+ id: version
+ run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
+
+ - name: Extract release notes from CHANGELOG
+ id: changelog
+ run: |
+ # Extract the section for this version from CHANGELOG.md
+ VERSION="${{ steps.version.outputs.VERSION }}"
+ NOTES=$(awk "/^## \[${VERSION}\]/{flag=1; next} /^## \[/{flag=0} flag" CHANGELOG.md)
+ if [ -z "$NOTES" ]; then
+ NOTES="Release v${VERSION}"
+ fi
+ # Use EOF delimiter for multi-line output
+ echo "NOTES<<EOF" >> $GITHUB_OUTPUT
+ echo "$NOTES" >> $GITHUB_OUTPUT
+ echo "EOF" >> $GITHUB_OUTPUT
+
+ - name: Create GitHub Release
+ uses: softprops/action-gh-release@v2
+ with:
+ tag_name: ${{ github.ref_name }}
+ name: v${{ steps.version.outputs.VERSION }}
+ body: ${{ steps.changelog.outputs.NOTES }}
+ draft: false
+ prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ # ──── Docker Image with Version Tag ───────────────────────────────
+ docker:
+ name: Docker Release
+ runs-on: ubuntu-latest
+ needs: [test]
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Login to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Extract metadata
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ghcr.io/${{ github.repository }}
+ tags: |
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+ type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
+
+ - name: Build and push
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ push: true
+ tags: ${{ steps.meta.outputs.tags }}
+ labels: ${{ steps.meta.outputs.labels }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 2b663a082..df12af769 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -134,7 +134,7 @@ export class OpenWA extends EventEmitter {
}
private setupWebSocket(): void {
- this.ws.on('message', (event) => {
+ this.ws.on('message', event => {
this.emit(event.type, event.data);
});
}
@@ -166,13 +166,7 @@ export interface Session {
lastSeen?: string;
}
-export type SessionStatus =
- | 'INITIALIZING'
- | 'SCAN_QR'
- | 'CONNECTING'
- | 'CONNECTED'
- | 'DISCONNECTED'
- | 'FAILED';
+export type SessionStatus = 'INITIALIZING' | 'SCAN_QR' | 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED' | 'FAILED';
export interface CreateSessionInput {
id?: string;
@@ -281,7 +275,7 @@ export class MessagesResource {
sessionId: string,
phone: string,
file: File | Buffer | ReadStream,
- options?: SendFileOptions
+ options?: SendFileOptions,
): Promise<Message> {
const formData = new FormData();
formData.append('phone', phone);
@@ -297,11 +291,7 @@ export class MessagesResource {
});
}
- async list(
- sessionId: string,
- phone: string,
- params?: MessageListParams
- ): Promise<PaginatedResponse<Message>> {
+ async list(sessionId: string, phone: string, params?: MessageListParams): Promise<PaginatedResponse<Message>> {
return this.http.get(`/api/sessions/${sessionId}/messages`, {
params: { phone, ...params },
});
@@ -311,25 +301,14 @@ export class MessagesResource {
return this.http.get(`/api/sessions/${sessionId}/messages/${messageId}`);
}
- async delete(
- sessionId: string,
- messageId: string,
- forEveryone = true
- ): Promise<void> {
+ async delete(sessionId: string, messageId: string, forEveryone = true): Promise<void> {
return this.http.delete(`/api/sessions/${sessionId}/messages/${messageId}`, {
params: { forEveryone },
});
}
- async react(
- sessionId: string,
- messageId: string,
- emoji: string
- ): Promise<void> {
- return this.http.post(
- `/api/sessions/${sessionId}/messages/${messageId}/react`,
- { emoji }
- );
+ async react(sessionId: string, messageId: string, emoji: string): Promise<void> {
+ return this.http.post(`/api/sessions/${sessionId}/messages/${messageId}/react`, { emoji });
}
}
```
@@ -496,7 +475,7 @@ export class OpenWAError extends Error {
message: string,
public code: string,
public status: number,
- public details?: unknown
+ public details?: unknown,
) {
super(message);
this.name = 'OpenWAError';
@@ -525,14 +504,8 @@ export class SessionNotFoundError extends OpenWAError {
}
export class RateLimitError extends OpenWAError {
- constructor(
- public retryAfter: number
- ) {
- super(
- `Rate limited. Retry after ${retryAfter}ms`,
- 'RATE_LIMIT_EXCEEDED',
- 429
- );
+ constructor(public retryAfter: number) {
+ super(`Rate limited. Retry after ${retryAfter}ms`, 'RATE_LIMIT_EXCEEDED', 429);
this.name = 'RateLimitError';
}
}
@@ -1150,7 +1123,7 @@ class Messages
### Installation
```bash
-npm install n8n-nodes-openwa
+npm install @rmyndharis/n8n-nodes-openwa
```
### Node Configuration
@@ -1158,12 +1131,7 @@ npm install n8n-nodes-openwa
```typescript
// nodes/OpenWA/OpenWA.node.ts
-import {
- IExecuteFunctions,
- INodeExecutionData,
- INodeType,
- INodeTypeDescription,
-} from 'n8n-workflow';
+import { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow';
export class OpenWA implements INodeType {
description: INodeTypeDescription = {
@@ -1367,13 +1335,7 @@ export class OpenWA implements INodeType {
```typescript
// nodes/OpenWA/OpenWATrigger.node.ts
-import {
- IHookFunctions,
- IWebhookFunctions,
- INodeType,
- INodeTypeDescription,
- IWebhookResponseData,
-} from 'n8n-workflow';
+import { IHookFunctions, IWebhookFunctions, INodeType, INodeTypeDescription, IWebhookResponseData } from 'n8n-workflow';
export class OpenWATrigger implements INodeType {
description: INodeTypeDescription = {
@@ -1496,9 +1458,7 @@ export class OpenWATrigger implements INodeType {
const body = this.getBodyData() as any;
return {
- workflowData: [
- this.helpers.returnJsonArray(body),
- ],
+ workflowData: [this.helpers.returnJsonArray(body)],
};
}
}
@@ -1532,6 +1492,7 @@ API v2.0.0 → SDK v2.0.x (breaking changes)
- [ ] Tag release in Git
- [ ] Update examples repository
```
+
---
<div align="center">
diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.md
index f87fbd86c..e8a006831 100644
--- a/docs/22-n8n-integration.md
+++ b/docs/22-n8n-integration.md
@@ -5,7 +5,7 @@
OpenWA provides official n8n community nodes for integrating WhatsApp automation into n8n workflows. This enables users to build powerful automations combining WhatsApp messaging with hundreds of other services available in n8n.
**Repository:** https://github.com/rmyndharis/OpenWA-n8n
-**npm Package:** `n8n-nodes-openwa`
+**npm Package:** `@rmyndharis/n8n-nodes-openwa`
## Architecture
@@ -28,7 +28,7 @@ OpenWA provides official n8n community nodes for integrating WhatsApp automation
1. Go to **Settings > Community Nodes**
2. Select **Install**
-3. Enter `n8n-nodes-openwa`
+3. Enter `@rmyndharis/n8n-nodes-openwa`
4. Agree to the risks and install
5. Restart n8n
@@ -36,7 +36,7 @@ OpenWA provides official n8n community nodes for integrating WhatsApp automation
```bash
cd ~/.n8n/nodes
-npm install n8n-nodes-openwa
+npm install @rmyndharis/n8n-nodes-openwa
```
## Nodes
@@ -47,25 +47,25 @@ Execute operations on your OpenWA server.
#### Credentials Setup
-| Field | Description | Example |
-|-------|-------------|---------|
+| Field | Description | Example |
+| ---------- | -------------------------------- | ------------------------ |
| Server URL | OpenWA server URL (without /api) | `https://wa.example.com` |
-| API Key | API key from OpenWA dashboard | `owa_xxxxxxxx...` |
+| API Key | API key from OpenWA dashboard | `owa_xxxxxxxx...` |
#### Resources & Operations
-| Resource | Operation | Description | Endpoint |
-|----------|-----------|-------------|----------|
-| Session | Get Status | Get session status | `GET /api/sessions/:id` |
-| Session | List All | List all sessions | `GET /api/sessions` |
-| Message | Send Text | Send text message | `POST /api/sessions/:id/messages/send-text` |
-| Message | Send Image | Send image (URL/Base64) | `POST /api/sessions/:id/messages/send-image` |
-| Message | Send Document | Send file/document | `POST /api/sessions/:id/messages/send-document` |
-| Message | Send Location | Send location pin | `POST /api/sessions/:id/messages/send-location` |
-| Contact | Check Exists | Check if number on WhatsApp | `GET /api/sessions/:id/contacts/check/:number` |
-| Contact | Get Info | Get contact information | `GET /api/sessions/:id/contacts/:contactId` |
-| Webhook | Create | Create a webhook | `POST /api/sessions/:id/webhooks` |
-| Webhook | Delete | Delete a webhook | `DELETE /api/sessions/:id/webhooks/:webhookId` |
+| Resource | Operation | Description | Endpoint |
+| -------- | ------------- | --------------------------- | ----------------------------------------------- |
+| Session | Get Status | Get session status | `GET /api/sessions/:id` |
+| Session | List All | List all sessions | `GET /api/sessions` |
+| Message | Send Text | Send text message | `POST /api/sessions/:id/messages/send-text` |
+| Message | Send Image | Send image (URL/Base64) | `POST /api/sessions/:id/messages/send-image` |
+| Message | Send Document | Send file/document | `POST /api/sessions/:id/messages/send-document` |
+| Message | Send Location | Send location pin | `POST /api/sessions/:id/messages/send-location` |
+| Contact | Check Exists | Check if number on WhatsApp | `GET /api/sessions/:id/contacts/check/:number` |
+| Contact | Get Info | Get contact information | `GET /api/sessions/:id/contacts/:contactId` |
+| Webhook | Create | Create a webhook | `POST /api/sessions/:id/webhooks` |
+| Webhook | Delete | Delete a webhook | `DELETE /api/sessions/:id/webhooks/:webhookId` |
### OpenWA Trigger Node
@@ -73,13 +73,13 @@ Start workflows when WhatsApp events occur.
#### Supported Events
-| Event | Description | Use Case |
-|-------|-------------|----------|
-| `message.received` | New incoming message | Auto-reply, lead capture |
-| `message.sent` | Message sent successfully | Delivery confirmation |
-| `session.connected` | Session authenticated | Startup notifications |
-| `session.disconnected` | Session lost connection | Alert monitoring |
-| `session.qr_ready` | QR code generated | Reconnection alerts |
+| Event | Description | Use Case |
+| ---------------------- | ------------------------- | ------------------------ |
+| `message.received` | New incoming message | Auto-reply, lead capture |
+| `message.sent` | Message sent successfully | Delivery confirmation |
+| `session.connected` | Session authenticated | Startup notifications |
+| `session.disconnected` | Session lost connection | Alert monitoring |
+| `session.qr_ready` | QR code generated | Reconnection alerts |
#### How It Works
@@ -118,6 +118,7 @@ Automatically reply to incoming messages with a welcome message.
```
**Configuration:**
+
- Trigger: `message.received`
- IF Node: Check if `{{$json.data.body}}` contains "hello"
- OpenWA: Send Text with welcome message
@@ -144,6 +145,7 @@ Get notified on Slack when WhatsApp session disconnects.
```
**Slack Message:**
+
```
⚠️ WhatsApp session "{{$json.sessionId}}" disconnected!
Time: {{$json.timestamp}}
@@ -193,14 +195,16 @@ WhatsApp has rate limits. Add delays between messages:
### 3. Message Formatting
Use WhatsApp formatting in your messages:
+
- Bold: `*text*`
- Italic: `_text_`
- Strikethrough: `~text~`
-- Monospace: ``` `text` ```
+- Monospace: `` `text` ``
### 4. Phone Number Format
Always use the correct format for chat IDs:
+
- Personal: `[email protected]`
- Group: `[email protected]`
diff --git a/sdk/README.md b/sdk/README.md
new file mode 100644
index 000000000..97219813d
--- /dev/null
+++ b/sdk/README.md
@@ -0,0 +1,48 @@
+# OpenWA SDKs
+
+Official client libraries for the OpenWA WhatsApp API Gateway.
+
+> **Note:** These SDKs are scaffolds and will be auto-generated from the OpenAPI spec in the future. They provide a working starting point for community contributions.
+
+## JavaScript / TypeScript
+
+```bash
+cd sdk/javascript
+npm install
+npm run build
+```
+
+```typescript
+import { OpenWAClient } from '@openwa/sdk';
+
+const client = new OpenWAClient({
+ baseUrl: 'http://localhost:2785',
+ apiKey: 'your-api-key',
+});
+
+const result = await client.messages.sendText('session-1', {
+ chatId: '[email protected]',
+ text: 'Hello from OpenWA SDK!',
+});
+```
+
+## Python
+
+```bash
+cd sdk/python
+pip install -e .
+```
+
+```python
+from openwa import OpenWAClient
+
+client = OpenWAClient(
+ base_url="http://localhost:2785",
+ api_key="your-api-key",
+)
+
+result = client.messages.send_text("session-1", {
+ "chatId": "[email protected]",
+ "text": "Hello from OpenWA Python SDK!",
+})
+```
diff --git a/sdk/javascript/package.json b/sdk/javascript/package.json
new file mode 100644
index 000000000..377412e69
--- /dev/null
+++ b/sdk/javascript/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@openwa/sdk",
+ "version": "0.0.1",
+ "description": "Official JavaScript/TypeScript SDK for OpenWA WhatsApp API Gateway",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "scripts": {
+ "build": "tsc",
+ "dev": "tsc --watch",
+ "test": "jest",
+ "lint": "eslint src/"
+ },
+ "keywords": [
+ "whatsapp",
+ "api",
+ "sdk",
+ "openwa",
+ "gateway"
+ ],
+ "author": "OpenWA Contributors",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/openwa/openwa",
+ "directory": "sdk/javascript"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {},
+ "devDependencies": {
+ "typescript": "^5.3.0"
+ }
+}
\ No newline at end of file
diff --git a/sdk/javascript/src/index.ts b/sdk/javascript/src/index.ts
new file mode 100644
index 000000000..ae56714c0
--- /dev/null
+++ b/sdk/javascript/src/index.ts
@@ -0,0 +1,112 @@
+/**
+ * OpenWA JavaScript/TypeScript SDK
+ *
+ * Official client library for the OpenWA WhatsApp API Gateway.
+ *
+ * @example
+ * ```typescript
+ * import { OpenWAClient } from '@openwa/sdk';
+ *
+ * const client = new OpenWAClient({
+ * baseUrl: 'http://localhost:2785',
+ * apiKey: 'your-api-key',
+ * });
+ *
+ * // Send a text message
+ * const result = await client.messages.sendText('session-1', {
+ * chatId: '[email protected]',
+ * text: 'Hello from OpenWA SDK!',
+ * });
+ * ```
+ *
+ * @packageDocumentation
+ */
+
+// ── Client Configuration ──────────────────────────────────────────
+
+export interface OpenWAClientConfig {
+ /** Base URL of the OpenWA API (e.g., 'http://localhost:2785') */
+ baseUrl: string;
+
+ /** API key for authentication */
+ apiKey: string;
+
+ /** Request timeout in milliseconds (default: 30000) */
+ timeout?: number;
+}
+
+// ── Response Types ────────────────────────────────────────────────
+
+export interface MessageResponse {
+ messageId: string;
+ timestamp: number;
+}
+
+export interface Session {
+ id: string;
+ name: string;
+ status: string;
+ phone: string | null;
+ pushName: string | null;
+}
+
+// ── Client Class ──────────────────────────────────────────────────
+
+export class OpenWAClient {
+ private readonly config: Required<OpenWAClientConfig>;
+
+ constructor(config: OpenWAClientConfig) {
+ this.config = {
+ timeout: 30000,
+ ...config,
+ };
+ }
+
+ // Placeholder — will be auto-generated from OpenAPI spec
+ get sessions() {
+ return {
+ list: () => this.request<Session[]>('GET', '/api/sessions'),
+ get: (id: string) => this.request<Session>('GET', `/api/sessions/${id}`),
+ create: (data: { name: string }) => this.request<Session>('POST', '/api/sessions', data),
+ start: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/start`),
+ stop: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/stop`),
+ delete: (id: string) => this.request<void>('DELETE', `/api/sessions/${id}`),
+ };
+ }
+
+ get messages() {
+ return {
+ sendText: (sessionId: string, data: { chatId: string; text: string }) =>
+ this.request<MessageResponse>('POST', `/api/sessions/${sessionId}/messages/text`, data),
+ };
+ }
+
+ // ── Internal HTTP client ──────────────────────────────────────────
+
+ private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
+ const url = `${this.config.baseUrl}${path}`;
+ const response = await fetch(url, {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': this.config.apiKey,
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ signal: AbortSignal.timeout(this.config.timeout),
+ });
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({ message: response.statusText }));
+ throw new Error(`OpenWA API Error (${response.status}): ${(error as { message: string }).message}`);
+ }
+
+ // Handle empty responses (204 No Content)
+ if (response.status === 204) {
+ return undefined as T;
+ }
+
+ return response.json() as Promise<T>;
+ }
+}
+
+export default OpenWAClient;
diff --git a/sdk/javascript/tsconfig.json b/sdk/javascript/tsconfig.json
new file mode 100644
index 000000000..fd1c1e812
--- /dev/null
+++ b/sdk/javascript/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "commonjs",
+ "lib": ["ES2022"],
+ "declaration": true,
+ "strict": true,
+ "esModuleInterop": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/sdk/python/openwa/__init__.py b/sdk/python/openwa/__init__.py
new file mode 100644
index 000000000..2164a1f36
--- /dev/null
+++ b/sdk/python/openwa/__init__.py
@@ -0,0 +1,131 @@
+"""
+OpenWA Python SDK
+
+Official client library for the OpenWA WhatsApp API Gateway.
+
+Example usage::
+
+ from openwa import OpenWAClient
+
+ client = OpenWAClient(
+ base_url="http://localhost:2785",
+ api_key="your-api-key",
+ )
+
+ # Send a text message
+ result = client.messages.send_text("session-1", {
+ "chatId": "[email protected]",
+ "text": "Hello from OpenWA Python SDK!",
+ })
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+
+@dataclass
+class OpenWAClientConfig:
+ """Configuration for the OpenWA client."""
+
+ base_url: str
+ api_key: str
+ timeout: float = 30.0
+
+
+@dataclass
+class MessageResponse:
+ """Response from sending a message."""
+
+ message_id: str
+ timestamp: int
+
+
+class OpenWAClient:
+ """OpenWA API client.
+
+ This is a scaffold — methods will be auto-generated from the OpenAPI spec.
+ """
+
+ def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
+ self.config = OpenWAClientConfig(
+ base_url=base_url.rstrip("/"),
+ api_key=api_key,
+ timeout=timeout,
+ )
+
+ # Placeholder — will be auto-generated from OpenAPI spec
+ @property
+ def sessions(self) -> "_SessionsResource":
+ return _SessionsResource(self)
+
+ @property
+ def messages(self) -> "_MessagesResource":
+ return _MessagesResource(self)
+
+ def _request(self, method: str, path: str, json: Any = None) -> Any:
+ """Internal HTTP request helper. Requires httpx."""
+ try:
+ import httpx
+ except ImportError:
+ raise ImportError(
+ "httpx is required for the OpenWA SDK. "
+ "Install it with: pip install openwa-sdk"
+ )
+
+ with httpx.Client(timeout=self.config.timeout) as client:
+ response = client.request(
+ method,
+ f"{self.config.base_url}{path}",
+ headers={
+ "Content-Type": "application/json",
+ "X-API-Key": self.config.api_key,
+ },
+ json=json,
+ )
+ response.raise_for_status()
+
+ if response.status_code == 204:
+ return None
+
+ return response.json()
+
+
+class _SessionsResource:
+ def __init__(self, client: OpenWAClient) -> None:
+ self._client = client
+
+ def list(self) -> list[dict]:
+ return self._client._request("GET", "/api/sessions")
+
+ def get(self, session_id: str) -> dict:
+ return self._client._request("GET", f"/api/sessions/{session_id}")
+
+ def create(self, name: str) -> dict:
+ return self._client._request("POST", "/api/sessions", {"name": name})
+
+ def start(self, session_id: str) -> dict:
+ return self._client._request("POST", f"/api/sessions/{session_id}/start")
+
+ def stop(self, session_id: str) -> dict:
+ return self._client._request("POST", f"/api/sessions/{session_id}/stop")
+
+ def delete(self, session_id: str) -> None:
+ self._client._request("DELETE", f"/api/sessions/{session_id}")
+
+
+class _MessagesResource:
+ def __init__(self, client: OpenWAClient) -> None:
+ self._client = client
+
+ def send_text(
+ self, session_id: str, data: dict[str, str]
+ ) -> MessageResponse:
+ result = self._client._request(
+ "POST", f"/api/sessions/{session_id}/messages/text", data
+ )
+ return MessageResponse(
+ message_id=result["messageId"],
+ timestamp=result["timestamp"],
+ )
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
new file mode 100644
index 000000000..aab160daa
--- /dev/null
+++ b/sdk/python/pyproject.toml
@@ -0,0 +1,25 @@
+[build-system]
+requires = ["setuptools>=68.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "openwa-sdk"
+version = "0.0.1"
+description = "Official Python SDK for OpenWA WhatsApp API Gateway"
+readme = "README.md"
+license = { text = "MIT" }
+requires-python = ">=3.9"
+authors = [
+ { name = "OpenWA Contributors" }
+]
+keywords = ["whatsapp", "api", "sdk", "openwa", "gateway"]
+
+dependencies = [
+ "httpx>=0.25.0",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=7.0",
+ "pytest-asyncio>=0.23",
+]
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
new file mode 100644
index 000000000..44ce32b32
--- /dev/null
+++ b/src/modules/auth/auth.service.spec.ts
@@ -0,0 +1,339 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { UnauthorizedException, NotFoundException } from '@nestjs/common';
+import { createHash } from 'crypto';
+import { AuthService } from './auth.service';
+import { ApiKey, ApiKeyRole } from './entities/api-key.entity';
+
+// Helpers
+const hashKey = (key: string) => createHash('sha256').update(key).digest('hex');
+
+function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {
+ return {
+ id: 'uuid-1',
+ name: 'Test Key',
+ keyHash: hashKey('test-key'),
+ keyPrefix: 'test-key-pre',
+ role: ApiKeyRole.OPERATOR,
+ allowedIps: null,
+ allowedSessions: null,
+ isActive: true,
+ expiresAt: null,
+ lastUsedAt: null,
+ usageCount: 0,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+}
+
+describe('AuthService', () => {
+ let service: AuthService;
+ let repository: jest.Mocked<Partial<Repository<ApiKey>>>;
+
+ beforeEach(async () => {
+ repository = {
+ count: jest.fn(),
+ find: jest.fn(),
+ findOne: jest.fn(),
+ create: jest.fn(),
+ save: jest.fn(),
+ remove: jest.fn(),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ AuthService,
+ {
+ provide: getRepositoryToken(ApiKey, 'main'),
+ useValue: repository,
+ },
+ ],
+ }).compile();
+
+ service = module.get<AuthService>(AuthService);
+ });
+
+ // ── createApiKey ──────────────────────────────────────────────────
+
+ describe('createApiKey', () => {
+ it('should generate a key with owa_k1_ prefix and save to DB', async () => {
+ const mockSaved = createMockApiKey({ name: 'My Key' });
+ (repository.create as jest.Mock).mockReturnValue(mockSaved);
+ (repository.save as jest.Mock).mockResolvedValue(mockSaved);
+
+ const result = await service.createApiKey({ name: 'My Key' });
+
+ expect(result.rawKey).toMatch(/^owa_k1_[a-f0-9]{64}$/);
+ expect(result.apiKey).toBe(mockSaved);
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'My Key',
+ role: ApiKeyRole.OPERATOR, // default
+ }),
+ );
+ });
+
+ it('should use the provided role instead of default', async () => {
+ const mockSaved = createMockApiKey({ role: ApiKeyRole.ADMIN });
+ (repository.create as jest.Mock).mockReturnValue(mockSaved);
+ (repository.save as jest.Mock).mockResolvedValue(mockSaved);
+
+ await service.createApiKey({ name: 'Admin Key', role: ApiKeyRole.ADMIN });
+
+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ role: ApiKeyRole.ADMIN }));
+ });
+
+ it('should store the SHA-256 hash, not the raw key', async () => {
+ const mockSaved = createMockApiKey();
+ (repository.create as jest.Mock).mockReturnValue(mockSaved);
+ (repository.save as jest.Mock).mockResolvedValue(mockSaved);
+
+ const result = await service.createApiKey({ name: 'Test' });
+
+ const expectedHash = hashKey(result.rawKey);
+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ keyHash: expectedHash }));
+ });
+ });
+
+ // ── findAll / findOne ─────────────────────────────────────────────
+
+ describe('findAll', () => {
+ it('should return all API keys ordered by createdAt DESC', async () => {
+ const keys = [createMockApiKey(), createMockApiKey({ id: 'uuid-2' })];
+ (repository.find as jest.Mock).mockResolvedValue(keys);
+
+ const result = await service.findAll();
+
+ expect(result).toHaveLength(2);
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' } });
+ });
+ });
+
+ describe('findOne', () => {
+ it('should return the API key if found', async () => {
+ const key = createMockApiKey();
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ const result = await service.findOne('uuid-1');
+ expect(result).toBe(key);
+ });
+
+ it('should throw NotFoundException if key not found', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.findOne('nonexistent')).rejects.toThrow(NotFoundException);
+ });
+ });
+
+ // ── update ────────────────────────────────────────────────────────
+
+ describe('update', () => {
+ it('should update only the provided fields', async () => {
+ const key = createMockApiKey();
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ const result = await service.update('uuid-1', { name: 'Updated' });
+
+ expect(result.name).toBe('Updated');
+ expect(result.role).toBe(ApiKeyRole.OPERATOR); // unchanged
+ });
+ });
+
+ // ── delete / revoke ───────────────────────────────────────────────
+
+ describe('delete', () => {
+ it('should remove the API key from DB', async () => {
+ const key = createMockApiKey();
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.remove as jest.Mock).mockResolvedValue(key);
+
+ await service.delete('uuid-1');
+
+ expect(repository.remove).toHaveBeenCalledWith(key);
+ });
+
+ it('should throw NotFoundException for non-existent key', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.delete('nonexistent')).rejects.toThrow(NotFoundException);
+ });
+ });
+
+ describe('revoke', () => {
+ it('should set isActive to false', async () => {
+ const key = createMockApiKey({ isActive: true });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ const result = await service.revoke('uuid-1');
+
+ expect(result.isActive).toBe(false);
+ });
+ });
+
+ // ── validateApiKey ────────────────────────────────────────────────
+
+ describe('validateApiKey', () => {
+ it('should return the API key for a valid raw key', async () => {
+ const rawKey = 'test-key';
+ const key = createMockApiKey({ keyHash: hashKey(rawKey) });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ const result = await service.validateApiKey(rawKey);
+
+ expect(result.id).toBe(key.id);
+ expect(result.usageCount).toBe(1);
+ expect(result.lastUsedAt).toBeDefined();
+ });
+
+ it('should throw UnauthorizedException for invalid key', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.validateApiKey('wrong-key')).rejects.toThrow(UnauthorizedException);
+ });
+
+ it('should throw UnauthorizedException for revoked key', async () => {
+ const key = createMockApiKey({ isActive: false, keyHash: hashKey('revoked') });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('revoked')).rejects.toThrow('API key is revoked');
+ });
+
+ it('should throw UnauthorizedException for expired key', async () => {
+ const expired = new Date();
+ expired.setDate(expired.getDate() - 1);
+ const key = createMockApiKey({ expiresAt: expired, keyHash: hashKey('expired') });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('expired')).rejects.toThrow('API key has expired');
+ });
+
+ it('should throw UnauthorizedException when IP is not allowed', async () => {
+ const key = createMockApiKey({
+ allowedIps: ['10.0.0.1'],
+ keyHash: hashKey('ip-restricted'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('ip-restricted', '192.168.1.1')).rejects.toThrow('IP address not allowed');
+ });
+
+ it('should pass when client IP matches allowed IPs', async () => {
+ const key = createMockApiKey({
+ allowedIps: ['10.0.0.1'],
+ keyHash: hashKey('ip-ok'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ const result = await service.validateApiKey('ip-ok', '10.0.0.1');
+ expect(result.id).toBe(key.id);
+ });
+
+ it('should throw UnauthorizedException when session not in allowedSessions', async () => {
+ const key = createMockApiKey({
+ allowedSessions: ['session-A'],
+ keyHash: hashKey('sess-restricted'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('sess-restricted', undefined, 'session-B')).rejects.toThrow(
+ 'API key not authorized for this session',
+ );
+ });
+ });
+
+ // ── hasPermission ─────────────────────────────────────────────────
+
+ describe('hasPermission', () => {
+ it('should allow ADMIN to access ADMIN routes', () => {
+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN });
+ expect(service.hasPermission(key, ApiKeyRole.ADMIN)).toBe(true);
+ });
+
+ it('should allow ADMIN to access OPERATOR routes', () => {
+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN });
+ expect(service.hasPermission(key, ApiKeyRole.OPERATOR)).toBe(true);
+ });
+
+ it('should allow ADMIN to access VIEWER routes', () => {
+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN });
+ expect(service.hasPermission(key, ApiKeyRole.VIEWER)).toBe(true);
+ });
+
+ it('should deny VIEWER access to OPERATOR routes', () => {
+ const key = createMockApiKey({ role: ApiKeyRole.VIEWER });
+ expect(service.hasPermission(key, ApiKeyRole.OPERATOR)).toBe(false);
+ });
+
+ it('should deny OPERATOR access to ADMIN routes', () => {
+ const key = createMockApiKey({ role: ApiKeyRole.OPERATOR });
+ expect(service.hasPermission(key, ApiKeyRole.ADMIN)).toBe(false);
+ });
+ });
+
+ // ── hashKey (via validateApiKey) ──────────────────────────────────
+
+ describe('hashKey (determinism)', () => {
+ it('should produce the same hash for the same input', () => {
+ const key1 = createMockApiKey({ keyHash: hashKey('same-key') });
+ const key2 = createMockApiKey({ keyHash: hashKey('same-key') });
+
+ expect(key1.keyHash).toBe(key2.keyHash);
+ });
+
+ it('should produce different hashes for different inputs', () => {
+ expect(hashKey('key-a')).not.toBe(hashKey('key-b'));
+ });
+ });
+
+ // ── isIpAllowed / ipInCidr (via validateApiKey) ───────────────────
+
+ describe('IP CIDR validation (via validateApiKey)', () => {
+ it('should allow IP within CIDR range', async () => {
+ const key = createMockApiKey({
+ allowedIps: ['192.168.1.0/24'],
+ keyHash: hashKey('cidr-ok'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ const result = await service.validateApiKey('cidr-ok', '192.168.1.100');
+ expect(result.id).toBe(key.id);
+ });
+
+ it('should reject IP outside CIDR range', async () => {
+ const key = createMockApiKey({
+ allowedIps: ['192.168.1.0/24'],
+ keyHash: hashKey('cidr-fail'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('cidr-fail', '10.0.0.1')).rejects.toThrow('IP address not allowed');
+ });
+
+ it('should handle mixed exact IP and CIDR entries', async () => {
+ const key = createMockApiKey({
+ allowedIps: ['10.0.0.5', '192.168.0.0/16'],
+ keyHash: hashKey('mixed'),
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+
+ // Exact match
+ const r1 = await service.validateApiKey('mixed', '10.0.0.5');
+ expect(r1.id).toBe(key.id);
+
+ // Reset usage for second call
+ key.usageCount = 0;
+
+ // CIDR match
+ const r2 = await service.validateApiKey('mixed', '192.168.50.1');
+ expect(r2.id).toBe(key.id);
+ });
+ });
+});
diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.ts
new file mode 100644
index 000000000..7d8c01d7f
--- /dev/null
+++ b/src/modules/auth/guards/api-key.guard.spec.ts
@@ -0,0 +1,161 @@
+import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
+import { Reflector } from '@nestjs/core';
+import { ApiKeyGuard } from './api-key.guard';
+import { AuthService } from '../auth.service';
+import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';
+
+function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {
+ return {
+ id: 'uuid-1',
+ name: 'Test Key',
+ keyHash: 'hash',
+ keyPrefix: 'owa_k1_xxxx',
+ role: ApiKeyRole.OPERATOR,
+ allowedIps: null,
+ allowedSessions: null,
+ isActive: true,
+ expiresAt: null,
+ lastUsedAt: null,
+ usageCount: 0,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+}
+
+function createMockContext(
+ headers: Record<string, string> = {},
+ params: Record<string, string> = {},
+): ExecutionContext {
+ const request = {
+ headers,
+ params,
+ ip: '127.0.0.1',
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+
+ return {
+ switchToHttp: () => ({
+ getRequest: () => request,
+ }),
+ getHandler: () => ({}),
+ getClass: () => ({}),
+ } as unknown as ExecutionContext;
+}
+
+describe('ApiKeyGuard', () => {
+ let guard: ApiKeyGuard;
+ let authService: jest.Mocked<Partial<AuthService>>;
+ let reflector: jest.Mocked<Reflector>;
+
+ beforeEach(() => {
+ authService = {
+ validateApiKey: jest.fn(),
+ hasPermission: jest.fn(),
+ };
+
+ reflector = {
+ getAllAndOverride: jest.fn(),
+ } as unknown as jest.Mocked<Reflector>;
+
+ guard = new ApiKeyGuard(authService as AuthService, reflector);
+ });
+
+ it('should allow access to @Public() routes without API key', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(true); // isPublic = true
+
+ const context = createMockContext();
+ const result = await guard.canActivate(context);
+
+ expect(result).toBe(true);
+ expect(authService.validateApiKey).not.toHaveBeenCalled();
+ });
+
+ it('should reject requests without X-API-Key header', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false); // not public
+
+ const context = createMockContext({});
+
+ await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
+ await expect(guard.canActivate(context)).rejects.toThrow('API key is required');
+ });
+
+ it('should accept X-API-Key header', async () => {
+ reflector.getAllAndOverride
+ .mockReturnValueOnce(false) // not public
+ .mockReturnValueOnce(undefined); // no required role
+
+ const apiKey = createMockApiKey();
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'my-key' });
+ const result = await guard.canActivate(context);
+
+ expect(result).toBe(true);
+ expect(authService.validateApiKey).toHaveBeenCalledWith('my-key', '127.0.0.1', undefined);
+ });
+
+ it('should accept Authorization Bearer header', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+
+ const apiKey = createMockApiKey();
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ authorization: 'Bearer my-bearer-key' });
+ const result = await guard.canActivate(context);
+
+ expect(result).toBe(true);
+ expect(authService.validateApiKey).toHaveBeenCalledWith('my-bearer-key', '127.0.0.1', undefined);
+ });
+
+ it('should reject when API key validation fails', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false);
+
+ (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnauthorizedException('Invalid API key'));
+
+ const context = createMockContext({ 'x-api-key': 'bad-key' });
+
+ await expect(guard.canActivate(context)).rejects.toThrow('Invalid API key');
+ });
+
+ it('should reject when role permission is insufficient', async () => {
+ reflector.getAllAndOverride
+ .mockReturnValueOnce(false) // not public
+ .mockReturnValueOnce(ApiKeyRole.ADMIN); // required role = ADMIN
+
+ const apiKey = createMockApiKey({ role: ApiKeyRole.VIEWER });
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+ (authService.hasPermission as jest.Mock).mockReturnValue(false);
+
+ const context = createMockContext({ 'x-api-key': 'viewer-key' });
+
+ await expect(guard.canActivate(context)).rejects.toThrow('Insufficient permissions');
+ });
+
+ it('should pass session ID from route params to validateApiKey', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+
+ const apiKey = createMockApiKey();
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({ 'x-api-key': 'key' }, { sessionId: 'sess-123' });
+ await guard.canActivate(context);
+
+ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', 'sess-123');
+ });
+
+ it('should extract client IP from X-Forwarded-For header', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);
+
+ const apiKey = createMockApiKey();
+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);
+
+ const context = createMockContext({
+ 'x-api-key': 'key',
+ 'x-forwarded-for': '203.0.113.50, 70.41.3.18',
+ });
+ await guard.canActivate(context);
+
+ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '203.0.113.50', undefined);
+ });
+});
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
new file mode 100644
index 000000000..65ab63bdd
--- /dev/null
+++ b/src/modules/message/message.service.spec.ts
@@ -0,0 +1,365 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { BadRequestException } from '@nestjs/common';
+import { MessageService } from './message.service';
+import { Message, MessageDirection } from './entities/message.entity';
+import { SessionService } from '../session/session.service';
+import { HookManager } from '../../core/hooks';
+
+const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };
+
+function createMockEngine() {
+ return {
+ sendTextMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendImageMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendVideoMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendAudioMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendDocumentMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendStickerMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendLocationMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ sendContactMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ replyToMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ forwardMessage: jest.fn().mockResolvedValue(mockEngineResult),
+ reactToMessage: jest.fn().mockResolvedValue(undefined),
+ getMessageReactions: jest.fn().mockResolvedValue([]),
+ deleteMessage: jest.fn().mockResolvedValue(undefined),
+ };
+}
+
+describe('MessageService', () => {
+ let service: MessageService;
+ let repository: jest.Mocked<Partial<Repository<Message>>>;
+ let sessionService: jest.Mocked<Partial<SessionService>>;
+ let hookManager: jest.Mocked<Partial<HookManager>>;
+ let mockEngine: ReturnType<typeof createMockEngine>;
+
+ beforeEach(async () => {
+ repository = {
+ create: jest.fn().mockImplementation((data: Partial<Message>) => ({ id: 'msg-uuid-1', ...data }) as Message),
+ save: jest.fn().mockImplementation(msg => Promise.resolve(msg)),
+ createQueryBuilder: jest.fn(),
+ };
+
+ mockEngine = createMockEngine();
+
+ sessionService = {
+ getEngine: jest.fn().mockReturnValue(mockEngine),
+ findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),
+ };
+
+ hookManager = {
+ execute: jest.fn().mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', input: { chatId: '[email protected]', text: 'Hello' }, type: 'text' },
+ }),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ MessageService,
+ { provide: getRepositoryToken(Message, 'data'), useValue: repository },
+ { provide: SessionService, useValue: sessionService },
+ { provide: HookManager, useValue: hookManager },
+ ],
+ }).compile();
+
+ service = module.get<MessageService>(MessageService);
+ });
+
+ // ── sendText ──────────────────────────────────────────────────────
+
+ describe('sendText', () => {
+ it('should send text message and return messageId + timestamp', async () => {
+ const result = await service.sendText('sess-1', {
+ chatId: '[email protected]',
+ text: 'Hello',
+ });
+
+ expect(result.messageId).toBe('wa-msg-1');
+ expect(result.timestamp).toBe(1706868000);
+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');
+ });
+
+ it('should save outgoing message to DB', async () => {
+ await service.sendText('sess-1', {
+ chatId: '[email protected]',
+ text: 'Hello',
+ });
+
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: 'sess-1',
+ direction: MessageDirection.OUTGOING,
+ type: 'text',
+ body: 'Hello',
+ }),
+ );
+ expect(repository.save).toHaveBeenCalled();
+ });
+
+ it('should execute message:sending and message:sent hooks', async () => {
+ await service.sendText('sess-1', {
+ chatId: '[email protected]',
+ text: 'Hello',
+ });
+
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'message:sending',
+ expect.objectContaining({ type: 'text' }),
+ expect.any(Object),
+ );
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'message:sent',
+ expect.objectContaining({ result: mockEngineResult }),
+ expect.any(Object),
+ );
+ });
+
+ it('should throw BadRequestException when plugin blocks sending', async () => {
+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });
+
+ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'blocked' })).rejects.toThrow(
+ 'Message sending blocked by plugin',
+ );
+ });
+
+ it('should throw BadRequestException if session is not active', async () => {
+ (sessionService.getEngine as jest.Mock).mockReturnValue(undefined);
+
+ await expect(service.sendText('inactive', { chatId: '[email protected]', text: 'hello' })).rejects.toThrow(
+ BadRequestException,
+ );
+ });
+ });
+
+ // ── sendImage ─────────────────────────────────────────────────────
+
+ describe('sendImage', () => {
+ it('should send image via URL', async () => {
+ const result = await service.sendImage('sess-1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/img.jpg',
+ caption: 'My image',
+ });
+
+ expect(result.messageId).toBe('wa-msg-1');
+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ data: 'https://example.com/img.jpg', caption: 'My image' }),
+ );
+ });
+
+ it('should send image via base64 with mimetype', async () => {
+ await service.sendImage('sess-1', {
+ chatId: '[email protected]',
+ base64: 'iVBORw0KGgoAAAAN...',
+ mimetype: 'image/png',
+ });
+
+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...', mimetype: 'image/png' }),
+ );
+ });
+ });
+
+ // ── sendVideo / sendAudio / sendDocument / sendSticker ────────────
+
+ describe('sendVideo', () => {
+ it('should call engine.sendVideoMessage', async () => {
+ await service.sendVideo('sess-1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/video.mp4',
+ });
+ expect(mockEngine.sendVideoMessage).toHaveBeenCalled();
+ });
+ });
+
+ describe('sendAudio', () => {
+ it('should call engine.sendAudioMessage', async () => {
+ await service.sendAudio('sess-1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/audio.ogg',
+ });
+ expect(mockEngine.sendAudioMessage).toHaveBeenCalled();
+ });
+ });
+
+ describe('sendDocument', () => {
+ it('should call engine.sendDocumentMessage with filename', async () => {
+ await service.sendDocument('sess-1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/doc.pdf',
+ filename: 'report.pdf',
+ });
+ expect(mockEngine.sendDocumentMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'report.pdf' }),
+ );
+ });
+ });
+
+ describe('sendSticker', () => {
+ it('should call engine.sendStickerMessage', async () => {
+ await service.sendSticker('sess-1', {
+ chatId: '[email protected]',
+ url: 'https://example.com/sticker.webp',
+ });
+ expect(mockEngine.sendStickerMessage).toHaveBeenCalled();
+ });
+ });
+
+ // ── sendLocation ──────────────────────────────────────────────────
+
+ describe('sendLocation', () => {
+ it('should send location with lat/lng', async () => {
+ const result = await service.sendLocation('sess-1', {
+ chatId: '[email protected]',
+ latitude: -6.2088,
+ longitude: 106.8456,
+ description: 'Jakarta',
+ });
+
+ expect(result.messageId).toBe('wa-msg-1');
+ expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ latitude: -6.2088, longitude: 106.8456 }),
+ );
+ });
+ });
+
+ // ── sendContact ───────────────────────────────────────────────────
+
+ describe('sendContact', () => {
+ it('should send contact with name and number', async () => {
+ const result = await service.sendContact('sess-1', {
+ chatId: '[email protected]',
+ contactName: 'John Doe',
+ contactNumber: '+628123456789',
+ });
+
+ expect(result.messageId).toBe('wa-msg-1');
+ expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'John Doe', number: '+628123456789' }),
+ );
+ });
+ });
+
+ // ── reply / forward ───────────────────────────────────────────────
+
+ describe('reply', () => {
+ it('should call engine.replyToMessage with quotedMessageId', async () => {
+ await service.reply('sess-1', {
+ chatId: '[email protected]',
+ quotedMessageId: 'wa-quoted-1',
+ text: 'This is a reply',
+ });
+
+ expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'This is a reply');
+ });
+ });
+
+ describe('forward', () => {
+ it('should call engine.forwardMessage with from/to chats', async () => {
+ await service.forward('sess-1', {
+ fromChatId: '[email protected]',
+ toChatId: '[email protected]',
+ messageId: 'wa-msg-to-fwd',
+ });
+
+ expect(mockEngine.forwardMessage).toHaveBeenCalledWith('[email protected]', '[email protected]', 'wa-msg-to-fwd');
+ });
+
+ it('should save forwarded message with toChatId', async () => {
+ await service.forward('sess-1', {
+ fromChatId: '[email protected]',
+ toChatId: '[email protected]',
+ messageId: 'wa-msg-to-fwd',
+ });
+
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ chatId: '[email protected]',
+ body: '[Forwarded]',
+ type: 'forward',
+ }),
+ );
+ });
+ });
+
+ // ── saveIncomingMessage ───────────────────────────────────────────
+
+ describe('saveIncomingMessage', () => {
+ it('should save with INCOMING direction', async () => {
+ await service.saveIncomingMessage('sess-1', {
+ waMessageId: 'wa-in-1',
+ chatId: '[email protected]',
+ body: 'Hi there',
+ type: 'text',
+ });
+
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: 'sess-1',
+ direction: MessageDirection.INCOMING,
+ }),
+ );
+ });
+ });
+
+ // ── buildMediaInput (via sendImage) ───────────────────────────────
+
+ describe('buildMediaInput validation', () => {
+ it('should throw when neither url nor base64 is provided', async () => {
+ await expect(service.sendImage('sess-1', { chatId: '[email protected]' })).rejects.toThrow(
+ 'Either url or base64 must be provided',
+ );
+ });
+
+ it('should throw when base64 is provided without mimetype', async () => {
+ await expect(
+ service.sendImage('sess-1', {
+ chatId: '[email protected]',
+ base64: 'data...',
+ }),
+ ).rejects.toThrow('mimetype is required when using base64 data');
+ });
+ });
+
+ // ── reactToMessage / deleteMessage ────────────────────────────────
+
+ describe('reactToMessage', () => {
+ it('should call engine.reactToMessage', async () => {
+ await service.reactToMessage('sess-1', {
+ chatId: '[email protected]',
+ messageId: 'wa-msg-1',
+ emoji: '👍',
+ });
+
+ expect(mockEngine.reactToMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', '👍');
+ });
+ });
+
+ describe('deleteMessage', () => {
+ it('should call engine.deleteMessage with forEveryone default true', async () => {
+ await service.deleteMessage('sess-1', {
+ chatId: '[email protected]',
+ messageId: 'wa-msg-1',
+ });
+
+ expect(mockEngine.deleteMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', true);
+ });
+
+ it('should pass forEveryone=false when specified', async () => {
+ await service.deleteMessage('sess-1', {
+ chatId: '[email protected]',
+ messageId: 'wa-msg-1',
+ forEveryone: false,
+ });
+
+ expect(mockEngine.deleteMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', false);
+ });
+ });
+});
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
new file mode 100644
index 000000000..97efeb8aa
--- /dev/null
+++ b/src/modules/session/session.service.spec.ts
@@ -0,0 +1,382 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
+import { SessionService } from './session.service';
+import { Session, SessionStatus } from './entities/session.entity';
+import { EngineFactory } from '../../engine/engine.factory';
+import { EventsGateway } from '../events/events.gateway';
+import { WebhookService } from '../webhook/webhook.service';
+import { HookManager } from '../../core/hooks';
+
+function createMockSession(overrides: Partial<Session> = {}): Session {
+ return {
+ id: 'sess-uuid-1',
+ name: 'test-session',
+ status: SessionStatus.CREATED,
+ phone: null,
+ pushName: null,
+ config: {},
+ proxyUrl: null,
+ proxyType: null,
+ connectedAt: null,
+ lastActiveAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+}
+
+describe('SessionService', () => {
+ let service: SessionService;
+ let repository: jest.Mocked<Partial<Repository<Session>>>;
+ let engineFactory: jest.Mocked<Partial<EngineFactory>>;
+ let eventsGateway: jest.Mocked<Partial<EventsGateway>>;
+ let webhookService: jest.Mocked<Partial<WebhookService>>;
+ let hookManager: jest.Mocked<Partial<HookManager>>;
+ let mockEngine: Record<string, jest.Mock>;
+
+ beforeEach(async () => {
+ repository = {
+ count: jest.fn(),
+ find: jest.fn(),
+ findOne: jest.fn(),
+ create: jest.fn(),
+ save: jest.fn(),
+ remove: jest.fn(),
+ update: jest.fn(),
+ };
+
+ mockEngine = {
+ initialize: jest.fn().mockResolvedValue(undefined),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ getQRCode: jest.fn().mockReturnValue(null),
+ getGroups: jest.fn().mockResolvedValue([]),
+ };
+
+ engineFactory = {
+ create: jest.fn().mockReturnValue(mockEngine),
+ };
+
+ eventsGateway = {
+ emitSessionStatus: jest.fn(),
+ emitMessage: jest.fn(),
+ };
+
+ webhookService = {
+ dispatch: jest.fn().mockResolvedValue(undefined),
+ };
+
+ hookManager = {
+ execute: jest.fn().mockResolvedValue({ continue: true, data: {} }),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ SessionService,
+ {
+ provide: getRepositoryToken(Session, 'data'),
+ useValue: repository,
+ },
+ { provide: EngineFactory, useValue: engineFactory },
+ { provide: EventsGateway, useValue: eventsGateway },
+ { provide: WebhookService, useValue: webhookService },
+ { provide: HookManager, useValue: hookManager },
+ ],
+ }).compile();
+
+ service = module.get<SessionService>(SessionService);
+ });
+
+ // ── create ────────────────────────────────────────────────────────
+
+ describe('create', () => {
+ it('should create a new session with CREATED status', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(null); // no duplicate
+ (repository.create as jest.Mock).mockReturnValue(session);
+ (repository.save as jest.Mock).mockResolvedValue(session);
+
+ const result = await service.create({ name: 'test-session' });
+
+ expect(result.name).toBe('test-session');
+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ status: SessionStatus.CREATED }));
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'session:created',
+ session,
+ expect.objectContaining({ sessionId: session.id }),
+ );
+ });
+
+ it('should throw ConflictException if session name already exists', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+
+ await expect(service.create({ name: 'test-session' })).rejects.toThrow(ConflictException);
+ });
+ });
+
+ // ── findAll / findOne / findByName ────────────────────────────────
+
+ describe('findAll', () => {
+ it('should return all sessions ordered by createdAt DESC', async () => {
+ const sessions = [createMockSession(), createMockSession({ id: 'sess-2' })];
+ (repository.find as jest.Mock).mockResolvedValue(sessions);
+
+ const result = await service.findAll();
+
+ expect(result).toHaveLength(2);
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' } });
+ });
+ });
+
+ describe('findOne', () => {
+ it('should return session by id', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+
+ const result = await service.findOne('sess-uuid-1');
+ expect(result.id).toBe('sess-uuid-1');
+ });
+
+ it('should throw NotFoundException if session not found', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.findOne('nonexistent')).rejects.toThrow(NotFoundException);
+ });
+ });
+
+ describe('findByName', () => {
+ it('should return session by name', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+
+ const result = await service.findByName('test-session');
+ expect(result.name).toBe('test-session');
+ });
+
+ it('should throw NotFoundException if name not found', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.findByName('nonexistent')).rejects.toThrow(NotFoundException);
+ });
+ });
+
+ // ── delete ────────────────────────────────────────────────────────
+
+ describe('delete', () => {
+ it('should stop engine and remove session from DB', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.remove as jest.Mock).mockResolvedValue(session);
+
+ await service.delete('sess-uuid-1');
+
+ expect(repository.remove).toHaveBeenCalledWith(session);
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'session:deleted',
+ expect.objectContaining({ sessionId: 'sess-uuid-1' }),
+ expect.any(Object),
+ );
+ });
+
+ it('should destroy running engine before deleting', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.save as jest.Mock).mockImplementation(s => Promise.resolve(s));
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (repository.remove as jest.Mock).mockResolvedValue(session);
+
+ // Start the session first to create an engine
+ await service.start('sess-uuid-1');
+
+ // Now delete
+ await service.delete('sess-uuid-1');
+
+ expect(mockEngine.destroy).toHaveBeenCalled();
+ });
+ });
+
+ // ── start ─────────────────────────────────────────────────────────
+
+ describe('start', () => {
+ it('should create engine and set status to INITIALIZING', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+
+ expect(engineFactory.create).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'test-session' }));
+ expect(mockEngine.initialize).toHaveBeenCalled();
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {
+ status: SessionStatus.INITIALIZING,
+ });
+ });
+
+ it('should throw BadRequestException if session already started', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+
+ await expect(service.start('sess-uuid-1')).rejects.toThrow(BadRequestException);
+ });
+
+ it('should execute session:starting hook before initializing engine', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'session:starting',
+ expect.objectContaining({ sessionId: 'sess-uuid-1' }),
+ expect.any(Object),
+ );
+ });
+ });
+
+ // ── stop ──────────────────────────────────────────────────────────
+
+ describe('stop', () => {
+ it('should disconnect engine and set status to DISCONNECTED', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // Start first
+ await service.start('sess-uuid-1');
+
+ // Stop
+ await service.stop('sess-uuid-1');
+
+ expect(mockEngine.disconnect).toHaveBeenCalled();
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {
+ status: SessionStatus.DISCONNECTED,
+ });
+ });
+ });
+
+ // ── getQRCode ─────────────────────────────────────────────────────
+
+ describe('getQRCode', () => {
+ it('should throw BadRequestException if engine not started', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+
+ await expect(service.getQRCode('sess-uuid-1')).rejects.toThrow(BadRequestException);
+ });
+
+ it('should return QR code from engine', async () => {
+ const session = createMockSession({ status: SessionStatus.QR_READY });
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+ mockEngine.getQRCode.mockReturnValue('data:image/png;base64,iVBOR...');
+
+ const result = await service.getQRCode('sess-uuid-1');
+
+ expect(result.qrCode).toBe('data:image/png;base64,iVBOR...');
+ });
+
+ it('should throw if session is READY (already authenticated)', async () => {
+ const session = createMockSession({ status: SessionStatus.READY });
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+ mockEngine.getQRCode.mockReturnValue(null);
+
+ await expect(service.getQRCode('sess-uuid-1')).rejects.toThrow('already authenticated');
+ });
+ });
+
+ // ── getStats ──────────────────────────────────────────────────────
+
+ describe('getStats', () => {
+ it('should return correct session statistics', async () => {
+ const sessions = [
+ createMockSession({ status: SessionStatus.READY }),
+ createMockSession({ id: 'sess-2', status: SessionStatus.READY }),
+ createMockSession({ id: 'sess-3', status: SessionStatus.DISCONNECTED }),
+ ];
+ (repository.find as jest.Mock).mockResolvedValue(sessions);
+
+ const stats = await service.getStats();
+
+ expect(stats.total).toBe(3);
+ expect(stats.ready).toBe(2);
+ expect(stats.disconnected).toBe(1);
+ expect(stats.byStatus[SessionStatus.READY]).toBe(2);
+ expect(stats.memoryUsage).toBeDefined();
+ });
+ });
+
+ // ── getActiveCount / isActive ─────────────────────────────────────
+
+ describe('getActiveCount', () => {
+ it('should return 0 when no engines are running', () => {
+ expect(service.getActiveCount()).toBe(0);
+ });
+
+ it('should return correct count after starting sessions', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+
+ expect(service.getActiveCount()).toBe(1);
+ });
+ });
+
+ describe('isActive', () => {
+ it('should return false for inactive session', () => {
+ expect(service.isActive('nonexistent')).toBe(false);
+ });
+
+ it('should return true for active session', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+
+ expect(service.isActive('sess-uuid-1')).toBe(true);
+ });
+ });
+
+ // ── onModuleInit ──────────────────────────────────────────────────
+
+ describe('onModuleInit', () => {
+ it('should reset active sessions to DISCONNECTED on startup', async () => {
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 3 });
+
+ await service.onModuleInit();
+
+ expect(repository.update).toHaveBeenCalledWith(expect.objectContaining({ status: expect.anything() as string }), {
+ status: SessionStatus.DISCONNECTED,
+ });
+ });
+ });
+
+ // ── onModuleDestroy ───────────────────────────────────────────────
+
+ describe('onModuleDestroy', () => {
+ it('should destroy all running engines on shutdown', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+ await service.onModuleDestroy();
+
+ expect(mockEngine.destroy).toHaveBeenCalled();
+ expect(service.getActiveCount()).toBe(0);
+ });
+ });
+});
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
new file mode 100644
index 000000000..4bcefaf84
--- /dev/null
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -0,0 +1,406 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { getQueueToken } from '@nestjs/bullmq';
+import { Repository } from 'typeorm';
+import { NotFoundException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import * as crypto from 'crypto';
+import { WebhookService, WebhookPayload } from './webhook.service';
+import { Webhook } from './entities/webhook.entity';
+import { HookManager } from '../../core/hooks';
+import { QUEUE_NAMES } from '../queue/queue-names';
+import { Session } from '../session/entities/session.entity';
+
+function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {
+ return {
+ id: 'wh-uuid-1',
+ sessionId: 'sess-1',
+ url: 'https://example.com/webhook',
+ events: ['message.received'],
+ secret: null,
+ headers: {},
+ active: true,
+ retryCount: 3,
+ lastTriggeredAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ session: undefined as unknown as Session,
+ ...overrides,
+ };
+}
+
+describe('WebhookService', () => {
+ let service: WebhookService;
+ let repository: jest.Mocked<Partial<Repository<Webhook>>>;
+ let configService: jest.Mocked<Partial<ConfigService>>;
+ let hookManager: jest.Mocked<Partial<HookManager>>;
+ let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;
+
+ beforeEach(async () => {
+ repository = {
+ find: jest.fn(),
+ findOne: jest.fn(),
+ create: jest.fn(),
+ save: jest.fn(),
+ remove: jest.fn(),
+ update: jest.fn(),
+ };
+
+ configService = {
+ get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return false;
+ if (key === 'webhook.retryDelay') return 100;
+ if (key === 'webhook.timeout') return 10000;
+ return def as T;
+ }),
+ };
+
+ hookManager = {
+ execute: jest.fn().mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload: {} },
+ }),
+ };
+
+ webhookQueue = {
+ add: jest.fn().mockResolvedValue(undefined),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ WebhookService,
+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
+ { provide: ConfigService, useValue: configService },
+ { provide: HookManager, useValue: hookManager },
+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
+ ],
+ }).compile();
+
+ service = module.get<WebhookService>(WebhookService);
+ });
+
+ // ── create ────────────────────────────────────────────────────────
+
+ describe('create', () => {
+ it('should create a webhook with default events', async () => {
+ const webhook = createMockWebhook();
+ (repository.create as jest.Mock).mockReturnValue(webhook);
+ (repository.save as jest.Mock).mockResolvedValue(webhook);
+
+ const result = await service.create('sess-1', {
+ url: 'https://example.com/webhook',
+ });
+
+ expect(result.sessionId).toBe('sess-1');
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: 'sess-1',
+ events: ['message.received'],
+ }),
+ );
+ });
+
+ it('should create webhook with custom events and secret', async () => {
+ const webhook = createMockWebhook({
+ events: ['*'],
+ secret: 'my-secret',
+ });
+ (repository.create as jest.Mock).mockReturnValue(webhook);
+ (repository.save as jest.Mock).mockResolvedValue(webhook);
+
+ await service.create('sess-1', {
+ url: 'https://example.com/webhook',
+ events: ['*'],
+ secret: 'my-secret',
+ });
+
+ expect(repository.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ events: ['*'],
+ secret: 'my-secret',
+ }),
+ );
+ });
+ });
+
+ // ── findBySession / findAll / findOne ──────────────────────────────
+
+ describe('findBySession', () => {
+ it('should return webhooks for a session', async () => {
+ const webhooks = [createMockWebhook()];
+ (repository.find as jest.Mock).mockResolvedValue(webhooks);
+
+ const result = await service.findBySession('sess-1');
+
+ expect(result).toHaveLength(1);
+ expect(repository.find).toHaveBeenCalledWith(expect.objectContaining({ where: { sessionId: 'sess-1' } }));
+ });
+ });
+
+ describe('findAll', () => {
+ it('should return all webhooks ordered by createdAt DESC', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll();
+
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' } });
+ });
+ });
+
+ describe('findOne', () => {
+ it('should return webhook by id', async () => {
+ const webhook = createMockWebhook();
+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);
+
+ const result = await service.findOne('wh-uuid-1');
+ expect(result.id).toBe('wh-uuid-1');
+ });
+
+ it('should throw NotFoundException if not found', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.findOne('nonexistent')).rejects.toThrow(NotFoundException);
+ });
+ });
+
+ // ── update ────────────────────────────────────────────────────────
+
+ describe('update', () => {
+ it('should update only provided fields', async () => {
+ const webhook = createMockWebhook();
+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);
+ (repository.save as jest.Mock).mockImplementation(w => Promise.resolve(w));
+
+ const result = await service.update('wh-uuid-1', { url: 'https://new-url.com/hook' });
+
+ expect(result.url).toBe('https://new-url.com/hook');
+ expect(result.events).toEqual(['message.received']); // unchanged
+ });
+ });
+
+ // ── delete ────────────────────────────────────────────────────────
+
+ describe('delete', () => {
+ it('should remove the webhook', async () => {
+ const webhook = createMockWebhook();
+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);
+ (repository.remove as jest.Mock).mockResolvedValue(webhook);
+
+ await service.delete('wh-uuid-1');
+
+ expect(repository.remove).toHaveBeenCalledWith(webhook);
+ });
+ });
+
+ // ── dispatch (direct mode — queue disabled) ───────────────────────
+
+ describe('dispatch (direct mode)', () => {
+ const mockFetch = jest.fn();
+
+ beforeEach(() => {
+ global.fetch = mockFetch as typeof global.fetch;
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+ });
+
+ afterEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it('should dispatch to webhooks matching the event', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // Mock hook to return the payload properly
+ const mockPayload: WebhookPayload = {
+ event: 'message.received',
+ timestamp: new Date().toISOString(),
+ sessionId: 'sess-1',
+ idempotencyKey: 'test-key',
+ deliveryId: 'test-delivery',
+ data: { from: '[email protected]' },
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: mockPayload,
+ },
+ });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/webhook',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ it('should NOT dispatch to webhooks that do not match the event', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ await service.dispatch('sess-1', 'session.ready', { phone: '628123456789' });
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('should dispatch to webhooks with wildcard (*) event filter', async () => {
+ const webhook = createMockWebhook({ events: ['*'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const wildcardPayload: WebhookPayload = {
+ event: 'anything.goes',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: '',
+ deliveryId: '',
+ data: {},
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'anything.goes',
+ payload: wildcardPayload,
+ },
+ });
+
+ await service.dispatch('sess-1', 'anything.goes', {});
+
+ expect(mockFetch).toHaveBeenCalled();
+ });
+
+ it('should skip dispatch when plugin cancels via hook', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: false, data: {} });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+ });
+
+ // ── generateSignature (via dispatch) ──────────────────────────────
+
+ describe('generateSignature', () => {
+ it('should produce valid HMAC-SHA256 signature', async () => {
+ const webhook = createMockWebhook({
+ events: ['message.received'],
+ secret: 'test-secret-123',
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const capturedHeaders: Record<string, string> = {};
+ const mockFetch = jest.fn().mockImplementation((_url: string, opts: RequestInit) => {
+ Object.assign(capturedHeaders, opts.headers as Record<string, string>);
+ return Promise.resolve({ ok: true, status: 200 });
+ });
+ global.fetch = mockFetch as typeof global.fetch;
+
+ const sigPayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: sigPayload,
+ },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ // Verify signature format
+ expect(capturedHeaders['X-OpenWA-Signature']).toMatch(/^sha256=[a-f0-9]{64}$/);
+
+ // Verify signature correctness
+ const body = JSON.stringify({
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ });
+ const expected = `sha256=${crypto.createHmac('sha256', 'test-secret-123').update(body).digest('hex')}`;
+ expect(capturedHeaders['X-OpenWA-Signature']).toBe(expected);
+
+ mockFetch.mockReset();
+ });
+ });
+
+ // ── dispatch (queue mode) ─────────────────────────────────────────
+
+ describe('dispatch (queue mode)', () => {
+ it('should add job to queue when queue is enabled', async () => {
+ // Create a new service with queue enabled
+ const queueModule: TestingModule = await Test.createTestingModule({
+ providers: [
+ WebhookService,
+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
+ {
+ provide: ConfigService,
+ useValue: {
+ get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def as T;
+ }),
+ },
+ },
+ { provide: HookManager, useValue: hookManager },
+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
+ ],
+ }).compile();
+
+ const queueService = queueModule.get<WebhookService>(WebhookService);
+
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ const queuePayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: queuePayload,
+ },
+ });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ expect(webhookQueue.add).toHaveBeenCalledWith(
+ expect.stringContaining('webhook-'),
+ expect.objectContaining({
+ webhookId: 'wh-uuid-1',
+ url: 'https://example.com/webhook',
+ event: 'message.received',
+ }),
+ expect.objectContaining({
+ attempts: 3,
+ backoff: expect.objectContaining({ type: 'exponential' }),
+ }),
+ );
+ });
+ });
+});