Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

docs: reconcile documentation with the v0.7.3 implementation (#471)

Yudhi Armyndharisf96576aa19c7
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index fd5df9e72..f52883640 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -110,51 +110,56 @@ flowchart TB
| Principle | Description | Example |
|-----------|-------------|---------|
-| **Program to Interfaces** | Core code depends on abstract interfaces, not concrete implementations | `IStorageAdapter` instead of `S3Client` |
-| **Dependency Injection** | Adapters injected at runtime via NestJS DI container | `@Inject('STORAGE_ADAPTER')` |
-| **Configuration-driven** | Adapter selection via environment variables | `STORAGE_TYPE=s3` |
-| **Zero Code Changes** | Switch adapters without modifying application code | Change `.env`, restart |
+| **Program to Interfaces** | Core code depends on the `IWhatsAppEngine` abstraction, never on a concrete library | `IWhatsAppEngine` instead of `whatsapp-web.js` `Client` |
+| **Dependency Injection** | Services are wired via NestJS DI (constructor injection of `EngineFactory`, `StorageService`, `CacheService`) | `constructor(private engineFactory: EngineFactory)` |
+| **Configuration-driven** | Backend selection via environment variables | `STORAGE_TYPE=s3`, `ENGINE_TYPE=baileys` |
+| **Zero Code Changes** | Switch backends without modifying application code | Change `.env`, restart |
### Adapter Categories
+The WhatsApp engine is the one true plug-in interface (`IWhatsAppEngine`, with concrete
+adapters resolved through the plugin loader). The other "pluggable" backends are not behind a
+formal `I*Adapter` interface — they are single services that branch internally on a config value:
+`StorageService` (`storageType` = `local` | `s3`), `CacheService` (Redis or fail-open no-op), and
+the TypeORM `data` connection (`sqlite` | `postgres`).
+
```mermaid
flowchart LR
subgraph Core["Application Core"]
APP[Business Logic]
end
- subgraph Interfaces["Adapter Interfaces"]
- IE[IWhatsAppEngine]
- ID[IDatabaseAdapter]
- IS[IStorageAdapter]
- IC[ICacheAdapter]
+ subgraph Boundaries["Swappable Boundaries"]
+ IE[IWhatsAppEngine<br/>interface + plugin loader]
+ SS[StorageService<br/>storageType branch]
+ CS[CacheService<br/>Redis / no-op]
+ DC[TypeORM 'data' conn<br/>sqlite / postgres]
end
- subgraph Implementations["Concrete Implementations"]
+ subgraph Implementations["Backends"]
subgraph Engine
E1[whatsapp-web.js]
E2[Baileys]
- E3[MockEngine]
end
subgraph Database
D1[SQLite]
D2[PostgreSQL]
end
subgraph Storage
- S1[LocalFS]
- S2[S3/MinIO]
+ S1[Local FS]
+ S2[S3 / MinIO]
end
subgraph Cache
- C1[In-Memory]
- C2[Redis]
+ C1[Redis]
+ C2[Disabled - no-op]
end
end
- APP --> Interfaces
+ APP --> Boundaries
IE -.-> Engine
- ID -.-> Database
- IS -.-> Storage
- IC -.-> Cache
+ DC -.-> Database
+ SS -.-> Storage
+ CS -.-> Cache
```
### WhatsApp Identity Contract (engine-neutral ids)
@@ -184,160 +189,96 @@ contract is documented on the `IWhatsAppEngine` interface.
> read path** (message / revoked / reaction payloads). Outbound id de-normalization (neutral -> engine
> dialect on send) and contact/chat list ids are tracked follow-ups.
-### Adapter Lifecycle State Machine
+### Engine Lifecycle State Machine
-Each adapter follows a consistent lifecycle:
+A WhatsApp engine moves through the `EngineStatus` enum
+(`engine/interfaces/whatsapp-engine.interface.ts`). The adapter reports the current value via
+`getStatus()` and pushes transitions to the host through the `onStateChanged` callback supplied to
+`initialize()`:
```mermaid
stateDiagram-v2
- [*] --> Uninitialized: Create Instance
-
- Uninitialized --> Initializing: initialize()
- Initializing --> Ready: Success
- Initializing --> Failed: Error
-
- Ready --> Active: First operation
- Active --> Ready: Operation complete
- Active --> Degraded: Transient error
- Degraded --> Active: Auto-recover
- Degraded --> Failed: Max retries exceeded
-
- Ready --> Disconnecting: shutdown()
- Active --> Disconnecting: shutdown()
- Degraded --> Disconnecting: shutdown()
-
- Disconnecting --> Disconnected: Cleanup complete
- Failed --> Disconnecting: shutdown()
-
+ [*] --> Disconnected: Create instance
+ Disconnected --> Initializing: initialize(callbacks)
+ Initializing --> QrReady: QR emitted
+ QrReady --> Authenticating: QR scanned
+ Authenticating --> Ready: Auth success
+ Initializing --> Failed: Terminal error (onError)
+ Authenticating --> Failed: Credentials rejected
+ Ready --> Disconnected: disconnect() / dropped link
+ Ready --> Failed: Fatal error
Disconnected --> [*]
+ Failed --> [*]
```
```typescript
-// common/interfaces/adapter-lifecycle.interface.ts
-
-export enum AdapterState {
- UNINITIALIZED = 'uninitialized',
+// engine/interfaces/whatsapp-engine.interface.ts
+export enum EngineStatus {
+ DISCONNECTED = 'disconnected',
INITIALIZING = 'initializing',
+ QR_READY = 'qr_ready',
+ AUTHENTICATING = 'authenticating',
READY = 'ready',
- ACTIVE = 'active',
- DEGRADED = 'degraded',
FAILED = 'failed',
- DISCONNECTING = 'disconnecting',
- DISCONNECTED = 'disconnected',
}
+```
-export interface IAdapterLifecycle {
- /** Current adapter state */
- getState(): AdapterState;
-
- /** Initialize adapter with configuration */
- initialize(config: AdapterConfig): Promise<void>;
-
- /** Check if adapter is operational */
- isHealthy(): Promise<boolean>;
+There is no generic `IAdapterLifecycle`/`AdapterState` abstraction — only the engine carries an
+explicit status enum. Storage, cache, and the database connection have no separate lifecycle type;
+they follow the standard NestJS provider lifecycle (`OnModuleInit` / `OnModuleDestroy`).
- /** Graceful shutdown */
- shutdown(): Promise<void>;
+### Dependency Injection & Module Wiring
- /** State change event emitter */
- onStateChange(handler: (state: AdapterState) => void): void;
-}
-```
+OpenWA does **not** use a dynamic `AdaptersModule` or string DI tokens. `AppModule`
+(`src/app.module.ts`) imports concrete feature modules directly and configures two **named TypeORM
+connections**:
-### Dependency Injection Configuration
+- **`main`** — always SQLite (`./data/main.sqlite`); owns the auth (`api_keys`) and audit
+ (`audit_logs`) entities. Fixed boot config, not pluggable.
+- **`data`** — the pluggable user-data connection: `sqlite` (default) or `postgres`, selected by
+ `DATABASE_TYPE`. Owns the session/webhook/message/template/engine entities.
-OpenWA uses NestJS Dynamic Modules for adapter injection:
+The engine is provided by `EngineModule` as the `EngineFactory` **class** (a normal injectable, not a
+string token). Storage and cache are provided as the `StorageService` and `CacheService` classes by
+their respective modules.
```typescript
-// adapters/adapters.module.ts
-
-import { DynamicModule, Global, Module } from '@nestjs/common';
-import { ConfigService } from '@nestjs/config';
-
-@Global()
-@Module({})
-export class AdaptersModule {
- static forRoot(): DynamicModule {
- return {
- module: AdaptersModule,
- providers: [
- // Database Adapter
- {
- provide: 'DATABASE_ADAPTER',
- useFactory: (config: ConfigService) => {
- const type = config.get('database.type', 'sqlite');
- return DatabaseAdapterFactory.create(type, config);
- },
- inject: [ConfigService],
- },
-
- // Storage Adapter
- {
- provide: 'STORAGE_ADAPTER',
- useFactory: (config: ConfigService) => {
- const type = config.get('storage.type', 'local');
- return StorageAdapterFactory.create(type, config);
- },
- inject: [ConfigService],
- },
-
- // Cache Adapter
- {
- provide: 'CACHE_ADAPTER',
- useFactory: (config: ConfigService) => {
- const type = config.get('cache.type', 'memory');
- return CacheAdapterFactory.create(type, config);
- },
- inject: [ConfigService],
- },
-
- // Engine Adapter
- {
- provide: 'ENGINE_FACTORY',
- useFactory: (config: ConfigService) => {
- return new EngineFactory(config);
- },
- inject: [ConfigService],
- },
- ],
- exports: [
- 'DATABASE_ADAPTER',
- 'STORAGE_ADAPTER',
- 'CACHE_ADAPTER',
- 'ENGINE_FACTORY',
- ],
- };
- }
-}
+// src/app.module.ts (shape)
+@Module({
+ imports: [
+ ConfigModule.forRoot({ isGlobal: true, load: [configuration], validate: validateEnv }),
+
+ // Auth + audit — always SQLite
+ TypeOrmModule.forRootAsync({ name: 'main', /* ... ./data/main.sqlite ... */ }),
+
+ // Pluggable user data — sqlite | postgres via DATABASE_TYPE
+ TypeOrmModule.forRootAsync({ name: 'data', /* ... */ }),
+
+ CacheModule, // provides CacheService
+ StorageModule, // provides StorageService
+ EngineModule, // provides EngineFactory
+ SessionModule, MessageModule, WebhookModule, /* ...other feature modules... */
+ ],
+})
+export class AppModule {}
```
-### Using Adapters in Services
+### Using the Backends in Services
-```typescript
-// modules/message/message.service.ts
+Services receive the backends by **constructor injection of the concrete class** — there is no
+`@Inject('…_ADAPTER')` token:
+```typescript
@Injectable()
-export class MessageService {
+export class SomeService {
constructor(
- @Inject('STORAGE_ADAPTER')
- private readonly storage: IStorageAdapter,
-
- @Inject('CACHE_ADAPTER')
- private readonly cache: ICacheAdapter,
+ private readonly storage: StorageService, // branches local vs s3 internally
+ private readonly cache: CacheService, // Redis when enabled, else a no-op
) {}
- async saveMediaMessage(sessionId: string, media: Buffer, filename: string) {
- // Storage adapter handles whether it's local FS or S3
- const result = await this.storage.upload({
- buffer: media,
- filename,
- folder: `sessions/${sessionId}/media`,
- });
-
- // Cache adapter handles whether it's in-memory or Redis
- await this.cache.set(`media:${result.key}`, result.url, 3600);
-
- return result;
+ async saveMedia(filePath: string, data: Buffer) {
+ await this.storage.putFile(filePath, data); // path-safety guarded
+ await this.cache.setSessionStatus('id', 'READY'); // no-op if Redis disabled
}
}
```
@@ -348,27 +289,24 @@ export class MessageService {
sequenceDiagram
participant Env as .env File
participant Config as ConfigService
- participant Factory as AdapterFactory
- participant DI as NestJS DI Container
- participant Service as Application Service
+ participant Svc as StorageService
+ participant App as Application
Note over Env: STORAGE_TYPE=s3
- Env->>Config: Load configuration
- Config->>Factory: Get storage.type = 's3'
- Factory->>Factory: new S3StorageAdapter(config)
- Factory->>DI: Register as 'STORAGE_ADAPTER'
- DI->>Service: Inject IStorageAdapter
- Service->>Service: Use adapter (doesn't know it's S3)
+ Env->>Config: Load + validateEnv
+ Config->>Svc: storage.type = 's3'
+ Svc->>Svc: construct S3Client (forcePathStyle: true)
+ App->>Svc: putFile / getFile (unaware of backend)
```
-### Adapter Selection Matrix
+### Backend Selection Matrix
| Environment | Database | Storage | Cache | Engine | Use Case |
|-------------|----------|---------|-------|--------|----------|
-| **Development** | SQLite | Local | Memory | Mock | Fast iteration, testing |
-| **Testing** | SQLite | Local | Memory | Mock | CI/CD, unit tests |
+| **Development** | SQLite | Local | Disabled | whatsapp-web.js | Fast iteration, testing |
+| **Testing** | SQLite | Local | Disabled | whatsapp-web.js | CI/CD, unit tests |
| **Staging** | PostgreSQL | Local | Redis | whatsapp-web.js | Pre-production validation |
-| **Production (Small)** | SQLite | Local | Memory | whatsapp-web.js | 1-3 sessions, VPS |
+| **Production (Small)** | SQLite | Local | Disabled | whatsapp-web.js | 1-3 sessions, VPS |
| **Production (Medium)** | PostgreSQL | Local | Redis | whatsapp-web.js | 5-10 sessions |
| **Production (Large)** | PostgreSQL | S3/MinIO | Redis | whatsapp-web.js | 10+ sessions, HA |
@@ -557,11 +495,11 @@ classDiagram
class WhatsAppEngine {
<<interface>>
- +initialize(): void
- +sendMessage(chatId, content): MessageResult
- +onMessage(callback): void
- +getContacts(): Contact[]
- +disconnect(): void
+ +initialize(callbacks): Promise~void~
+ +sendTextMessage(chatId, text): Promise~MessageResult~
+ +getStatus(): EngineStatus
+ +getContacts(): Promise~Contact[]~
+ +disconnect(): Promise~void~
}
SessionManager --> Session
@@ -905,140 +843,159 @@ flowchart LR
classDiagram
class IWhatsAppEngine {
<<interface>>
- +initialize(config): Promise~void~
- +connect(): Promise~void~
+ +initialize(callbacks): Promise~void~
+disconnect(): Promise~void~
+ +logout(): Promise~void~
+ +destroy(): Promise~void~
+ +forceDestroy(): Promise~void~
+getStatus(): EngineStatus
+ +getQRCode(): string | null
+ +requestPairingCode(phone): Promise~string~
+sendTextMessage(chatId, text): Promise~MessageResult~
- +sendMediaMessage(chatId, media): Promise~MessageResult~
- +getQRCode(): Promise~string~
- +on(event, handler): void
- +off(event, handler): void
+ +sendImageMessage(chatId, media): Promise~MessageResult~
}
-
- class WhatsAppWebJSEngine {
+
+ class WhatsAppWebJsAdapter {
-client: Client
- +initialize(): Promise~void~
- +connect(): Promise~void~
+ +initialize(callbacks): Promise~void~
+sendTextMessage(): Promise~MessageResult~
}
-
- class BaileysEngine {
+
+ class BaileysAdapter {
-socket: WASocket
- +initialize(): Promise~void~
- +connect(): Promise~void~
- +sendTextMessage(): Promise~MessageResult~
- }
-
- class MockEngine {
- +initialize(): Promise~void~
+ +initialize(callbacks): Promise~void~
+sendTextMessage(): Promise~MessageResult~
}
-
+
class EngineFactory {
- +create(type: EngineType): IWhatsAppEngine
+ +create(options: EngineCreateOptions): IWhatsAppEngine
}
-
- IWhatsAppEngine <|.. WhatsAppWebJSEngine
- IWhatsAppEngine <|.. BaileysEngine
- IWhatsAppEngine <|.. MockEngine
+
+ IWhatsAppEngine <|.. WhatsAppWebJsAdapter
+ IWhatsAppEngine <|.. BaileysAdapter
EngineFactory --> IWhatsAppEngine
```
### Engine Interface Definition
+Events are **not** delivered through an `on`/`off`/`once` emitter. Instead, the host passes a single
+`EngineEventCallbacks` object to `initialize()`; the adapter invokes the registered callbacks for the
+lifetime of the engine. Status is an `EngineStatus` **enum** (not a string union), `getQRCode()` is
+**synchronous** (`string | null`), and there is no `connect()` / `isReady()` / `getAuthState()` — the
+adapter connects inside `initialize()`.
+
```typescript
// engine/interfaces/whatsapp-engine.interface.ts
+export enum EngineStatus {
+ DISCONNECTED = 'disconnected',
+ INITIALIZING = 'initializing',
+ QR_READY = 'qr_ready',
+ AUTHENTICATING = 'authenticating',
+ READY = 'ready',
+ FAILED = 'failed',
+}
+
+// All inbound signals arrive through callbacks supplied once to initialize().
+export interface EngineEventCallbacks {
+ onQRCode?: (qr: string) => void;
+ onReady?: (phone: string, pushName: string) => void;
+ onMessage?: (message: IncomingMessage) => void;
+ onMessageCreate?: (message: IncomingMessage) => void; // outgoing (incl. linked-phone sends)
+ onMessageAck?: (messageId: string, status: DeliveryStatus) => void;
+ onMessageRevoked?: (message: RevokedMessage) => void;
+ onMessageReaction?: (event: ReactionEvent) => void;
+ onHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatch
+ onDisconnected?: (reason: string) => void; // recoverable -> reconnect
+ onStateChanged?: (state: EngineStatus) => void;
+ onError?: (reason: string) => void; // terminal init/auth failure
+}
+
export interface IWhatsAppEngine {
- // Lifecycle
- initialize(config: EngineConfig): Promise<void>;
- connect(): Promise<void>;
- disconnect(): Promise<void>;
+ // Lifecycle — connecting happens inside initialize(); callbacks are registered here.
+ initialize(callbacks: EngineEventCallbacks): Promise<void>;
+ disconnect(): Promise<void>; // close, keep session (reconnect without QR)
+ logout(): Promise<void>; // clear session (requires QR scan again)
destroy(): Promise<void>;
-
- // Status
+ forceDestroy(): Promise<void>; // kill this engine's own resources, then graceful teardown
+
+ // Status / auth
getStatus(): EngineStatus;
- isReady(): boolean;
-
- // Authentication
- getQRCode(): Promise<string | null>;
- getAuthState(): AuthState;
-
- // Messaging
- sendTextMessage(chatId: string, text: string, options?: SendOptions): Promise<MessageResult>;
- sendMediaMessage(chatId: string, media: MediaInput, options?: SendOptions): Promise<MessageResult>;
+ getQRCode(): string | null; // synchronous
+ requestPairingCode(phoneNumber: string): Promise<string>;
+ getPhoneNumber(): string | null;
+ getPushName(): string | null;
+
+ // Messaging (selected)
+ sendTextMessage(chatId: string, text: string): Promise<MessageResult>;
+ sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult>;
sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult>;
- sendContactMessage(chatId: string, contact: ContactInput): Promise<MessageResult>;
-
- // Contacts
+ sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult>;
+
+ // Contacts / groups / chats — see the interface file for the full method set.
getContacts(): Promise<Contact[]>;
- getContactById(contactId: string): Promise<Contact | null>;
- getProfilePicture(contactId: string): Promise<string | null>;
-
- // Groups
getGroups(): Promise<Group[]>;
- getGroupById(groupId: string): Promise<Group | null>;
- createGroup(name: string, participants: string[]): Promise<Group>;
-
- // Events
- on<T extends EngineEvent>(event: T, handler: EventHandler<T>): void;
- off<T extends EngineEvent>(event: T, handler: EventHandler<T>): void;
- once<T extends EngineEvent>(event: T, handler: EventHandler<T>): void;
-}
-
-export type EngineStatus = 'initializing' | 'qr_ready' | 'connecting' | 'ready' | 'disconnected' | 'error';
-
-export interface EngineConfig {
- sessionId: string;
- authStatePath?: string;
- puppeteerOptions?: PuppeteerOptions;
- proxyUrl?: string;
+ getChats(): Promise<ChatSummary[]>;
+ // ...
}
-
-export type EngineEvent =
- | 'qr'
- | 'ready'
- | 'authenticated'
- | 'disconnected'
- | 'message'
- | 'message_ack'
- | 'message_revoke'
- | 'state_changed';
```
### Engine Factory
+The factory resolves the engine through the **plugin loader**, not a hard-coded `switch`. The
+configured engine (`engine.type`, default `'whatsapp-web.js'`) is read once in the constructor; the
+built-in `whatsapp-web.js` and `baileys` plugins are registered and the configured one is enabled in
+`onModuleInit()`. `create()` takes an **options object** (engine-neutral per-call config —
+`sessionId` / `proxyUrl` / `proxyType`), not a `type` argument. There is no `EngineType` union, no
+`switch`, and no `Unknown engine type` throw: if the plugin is unavailable it logs a warning and
+**falls back** to constructing a `WhatsAppWebJsAdapter` directly. (A typo in `ENGINE_TYPE` is rejected
+at boot by `validateEnv`, which whitelists `whatsapp-web.js` | `baileys`.)
+
```typescript
// engine/engine.factory.ts
-import { Injectable } from '@nestjs/common';
+import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';
-import { WhatsAppWebJSEngine } from './adapters/whatsapp-webjs.engine';
-import { BaileysEngine } from './adapters/baileys.engine';
-import { MockEngine } from './adapters/mock.engine';
+import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';
+import { PluginLoaderService, PluginType, IEnginePlugin } from '../core/plugins';
-export type EngineType = 'whatsapp-web.js' | 'baileys' | 'mock';
+export interface EngineCreateOptions {
+ sessionId: string;
+ proxyUrl?: string;
+ proxyType?: 'http' | 'https' | 'socks4' | 'socks5';
+}
@Injectable()
-export class EngineFactory {
- constructor(private config: ConfigService) {}
-
- create(type?: EngineType): IWhatsAppEngine {
- const engineType = type || this.config.get<EngineType>('engine.type', 'whatsapp-web.js');
-
- switch (engineType) {
- case 'whatsapp-web.js':
- return new WhatsAppWebJSEngine(this.config);
-
- case 'baileys':
- return new BaileysEngine(this.config);
-
- case 'mock':
- return new MockEngine();
-
- default:
- throw new Error(`Unknown engine type: ${engineType}`);
+export class EngineFactory implements OnModuleInit {
+ private readonly engineType: string;
+
+ constructor(
+ private readonly configService: ConfigService,
+ private readonly pluginLoader: PluginLoaderService,
+ /* ...message-store + lid-mapping deps... */
+ ) {
+ this.engineType = this.configService.get<string>('engine.type') ?? 'whatsapp-web.js';
+ }
+
+ async onModuleInit(): Promise<void> {
+ // Register the built-in whatsapp-web.js + baileys engine plugins, then enable the configured one.
+ await this.registerBuiltInEngines();
+ }
+
+ create(options: EngineCreateOptions): IWhatsAppEngine {
+ const enginePlugin = this.pluginLoader.getPlugin(this.engineType);
+
+ if (enginePlugin?.instance && this.isEnginePlugin(enginePlugin.instance)) {
+ // Engine-specific config (e.g. Puppeteer) was handed to the plugin as an opaque blob at
+ // registration, so the factory passes only engine-neutral per-call options here.
+ return enginePlugin.instance.createEngine({
+ sessionId: options.sessionId,
+ proxyUrl: options.proxyUrl,
+ proxyType: options.proxyType,
+ }) as IWhatsAppEngine;
}
+
+ // Plugin missing -> warn and fall back to the direct whatsapp-web.js adapter (no throw).
+ return this.createFallbackEngine(options);
}
}
```
@@ -1046,160 +1003,146 @@ export class EngineFactory {
### WhatsApp-Web.js Adapter
```typescript
-// engine/adapters/whatsapp-webjs.engine.ts
+// engine/adapters/whatsapp-web-js.adapter.ts
import { Client, LocalAuth } from 'whatsapp-web.js';
-import { IWhatsAppEngine, EngineConfig, EngineStatus } from '../interfaces/whatsapp-engine.interface';
+import {
+ IWhatsAppEngine,
+ EngineEventCallbacks,
+ EngineStatus,
+ MessageResult,
+} from '../interfaces/whatsapp-engine.interface';
-export class WhatsAppWebJSEngine implements IWhatsAppEngine {
+export class WhatsAppWebJsAdapter implements IWhatsAppEngine {
private client: Client | null = null;
- private status: EngineStatus = 'initializing';
- private eventEmitter = new EventEmitter();
-
- async initialize(config: EngineConfig): Promise<void> {
+ private status: EngineStatus = EngineStatus.DISCONNECTED;
+ private callbacks: EngineEventCallbacks = {};
+
+ // The host registers all event callbacks here; the adapter also connects inside initialize().
+ async initialize(callbacks: EngineEventCallbacks): Promise<void> {
+ this.callbacks = callbacks;
+ this.setStatus(EngineStatus.INITIALIZING);
+
this.client = new Client({
- authStrategy: new LocalAuth({
- clientId: config.sessionId,
- dataPath: config.authStatePath
- }),
- puppeteer: {
- headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox'],
- ...config.puppeteerOptions,
- },
+ authStrategy: new LocalAuth({ clientId: this.sessionId, dataPath: this.sessionDataPath }),
+ puppeteer: { headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] },
});
-
+
this.setupEventHandlers();
+ await this.client.initialize();
}
-
+
private setupEventHandlers(): void {
this.client!.on('qr', (qr) => {
- this.status = 'qr_ready';
- this.eventEmitter.emit('qr', qr);
+ this.setStatus(EngineStatus.QR_READY);
+ this.callbacks.onQRCode?.(qr);
});
-
this.client!.on('ready', () => {
- this.status = 'ready';
- this.eventEmitter.emit('ready');
+ this.setStatus(EngineStatus.READY);
+ this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');
});
-
this.client!.on('disconnected', (reason) => {
- this.status = 'disconnected';
- this.eventEmitter.emit('disconnected', reason);
+ this.setStatus(EngineStatus.DISCONNECTED);
+ this.callbacks.onDisconnected?.(String(reason));
});
-
this.client!.on('message', (message) => {
- this.eventEmitter.emit('message', this.transformMessage(message));
+ this.callbacks.onMessage?.(this.toIncomingMessage(message)); // mapped to the neutral shape
});
}
-
- async connect(): Promise<void> {
- this.status = 'connecting';
- await this.client!.initialize();
+
+ private setStatus(status: EngineStatus): void {
+ this.status = status;
+ this.callbacks.onStateChanged?.(status);
}
-
+
async disconnect(): Promise<void> {
- await this.client?.logout();
- this.status = 'disconnected';
+ await this.client?.destroy(); // keep session; logout() clears it
+ this.setStatus(EngineStatus.DISCONNECTED);
}
-
+
async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {
const message = await this.client!.sendMessage(chatId, text);
- return {
- messageId: message.id._serialized,
- timestamp: new Date(message.timestamp * 1000),
- status: 'sent',
- };
+ return { id: message.id._serialized, timestamp: message.timestamp };
}
-
- // ... other method implementations
+
+ // ... full method set per the interface
}
```
### Baileys Adapter (Alternative Engine)
```typescript
-// engine/adapters/baileys.engine.ts
-import makeWASocket, {
- DisconnectReason,
- useMultiFileAuthState
-} from '@whiskeysockets/baileys';
-import { IWhatsAppEngine, EngineConfig, EngineStatus } from '../interfaces/whatsapp-engine.interface';
-
-export class BaileysEngine implements IWhatsAppEngine {
+// engine/adapters/baileys.adapter.ts
+import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys';
+import {
+ IWhatsAppEngine,
+ EngineEventCallbacks,
+ EngineStatus,
+ MessageResult,
+} from '../interfaces/whatsapp-engine.interface';
+
+export class BaileysAdapter implements IWhatsAppEngine {
private socket: ReturnType<typeof makeWASocket> | null = null;
- private status: EngineStatus = 'initializing';
- private eventEmitter = new EventEmitter();
-
- async initialize(config: EngineConfig): Promise<void> {
- const { state, saveCreds } = await useMultiFileAuthState(
- config.authStatePath || `./.baileys_auth/${config.sessionId}`
- );
-
- this.socket = makeWASocket({
- auth: state,
- printQRInTerminal: false,
- });
-
+ private status: EngineStatus = EngineStatus.DISCONNECTED;
+ private callbacks: EngineEventCallbacks = {};
+
+ // Baileys connects during initialize(); callbacks are registered here, same as the wwebjs adapter.
+ async initialize(callbacks: EngineEventCallbacks): Promise<void> {
+ this.callbacks = callbacks;
+ this.setStatus(EngineStatus.INITIALIZING);
+
+ const { state, saveCreds } = await useMultiFileAuthState(`${this.authDir}/${this.sessionId}`);
+ this.socket = makeWASocket({ auth: state });
this.socket.ev.on('creds.update', saveCreds);
this.setupEventHandlers();
}
-
+
private setupEventHandlers(): void {
this.socket!.ev.on('connection.update', (update) => {
const { connection, lastDisconnect, qr } = update;
-
if (qr) {
- this.status = 'qr_ready';
- this.eventEmitter.emit('qr', qr);
+ this.setStatus(EngineStatus.QR_READY);
+ this.callbacks.onQRCode?.(qr);
}
-
if (connection === 'open') {
- this.status = 'ready';
- this.eventEmitter.emit('ready');
+ this.setStatus(EngineStatus.READY);
+ this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');
}
-
if (connection === 'close') {
- this.status = 'disconnected';
- const shouldReconnect = (lastDisconnect?.error as any)?.output?.statusCode !== DisconnectReason.loggedOut;
- this.eventEmitter.emit('disconnected', { shouldReconnect });
+ const loggedOut = (lastDisconnect?.error as any)?.output?.statusCode === DisconnectReason.loggedOut;
+ this.setStatus(loggedOut ? EngineStatus.FAILED : EngineStatus.DISCONNECTED);
+ this.callbacks.onDisconnected?.(loggedOut ? 'logged_out' : 'connection_closed');
}
});
-
+
this.socket!.ev.on('messages.upsert', ({ messages }) => {
for (const msg of messages) {
- if (!msg.key.fromMe) {
- this.eventEmitter.emit('message', this.transformMessage(msg));
- }
+ if (!msg.key.fromMe) this.callbacks.onMessage?.(this.toIncomingMessage(msg)); // neutral ids
}
});
}
-
- async connect(): Promise<void> {
- this.status = 'connecting';
- // Baileys connects during initialize
+
+ private setStatus(status: EngineStatus): void {
+ this.status = status;
+ this.callbacks.onStateChanged?.(status);
}
-
+
async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {
const result = await this.socket!.sendMessage(chatId, { text });
- return {
- messageId: result!.key.id!,
- timestamp: new Date(),
- status: 'sent',
- };
+ return { id: result!.key.id!, timestamp: Math.floor(Date.now() / 1000) };
}
-
- // ... other method implementations
+
+ // ... full method set per the interface
}
```
### Engine Selection Configuration
-```yaml
+```bash
# .env
-ENGINE_TYPE=whatsapp-web.js # Options: whatsapp-web.js, baileys, mock
+ENGINE_TYPE=whatsapp-web.js # Options: whatsapp-web.js (default), baileys
-# For testing
-ENGINE_TYPE=mock
+# Switch to the browser-free engine
+ENGINE_TYPE=baileys
```
### Migration Strategy
@@ -1247,10 +1190,10 @@ flowchart TB
### Benefits of Abstraction
1. **Risk Mitigation** - Swap engines without changing application code
-2. **Testing** - Use MockEngine for unit tests
-3. **Flexibility** - Run different engines per environment
-4. **Future-proof** - Easy to add new engine implementations
-5. **A/B Testing** - Compare engine performance in production
+2. **Testing** - The single `IWhatsAppEngine` boundary makes the engine trivial to stub/mock in unit tests
+3. **Flexibility** - Run different engines per deployment via `ENGINE_TYPE`
+4. **Future-proof** - New engines register as plugins; no changes to application code
+5. **Comparison** - Evaluate engine resource/behavior trade-offs per environment
---
@@ -1266,11 +1209,10 @@ flowchart TB
APP[Application Logic]
end
- subgraph Adapters["Pluggable Adapters"]
+ subgraph Adapters["Pluggable Backends"]
subgraph Engine["WhatsApp Engine"]
E1[whatsapp-web.js]
E2[Baileys]
- E3[Mock]
end
subgraph Database["Database"]
@@ -1280,13 +1222,12 @@ flowchart TB
subgraph Storage["Media Storage"]
S1[Local Filesystem]
- S2[S3]
- S3[MinIO]
+ S2[S3 / MinIO]
end
- subgraph Cache["Cache/Queue"]
- C1[In-Memory]
- C2[Redis]
+ subgraph Cache["Cache"]
+ C1[Redis]
+ C2[Disabled - no-op]
end
end
@@ -1298,254 +1239,63 @@ flowchart TB
### Adapter Options
-| Component | Options | Default | Notes |
+| Component | Options (`ENV`) | Default | Notes |
|-----------|---------|---------|-------|
-| **WhatsApp Engine** | whatsapp-web.js, Baileys, Mock | whatsapp-web.js | Mock for testing |
-| **Database** | SQLite, PostgreSQL | SQLite | PostgreSQL for large-scale production |
-| **Media Storage** | Local, S3, MinIO | Local | S3/MinIO for horizontal scaling |
-| **Cache/Queue** | In-Memory, Redis | In-Memory | Redis for multi-instance |
-
-### 3.13.1 Storage Adapter
-
-The media storage abstraction enables storing media files (images, videos, documents) across different backends.
-
-#### Interface Definition
-
-```typescript
-// storage/interfaces/storage-adapter.interface.ts
-export interface IStorageAdapter {
- /**
- * Upload file to storage
- */
- upload(file: UploadInput): Promise<StorageResult>;
-
- /**
- * Download file from storage
- */
- download(key: string): Promise<Buffer>;
-
- /**
- * Delete file from storage
- */
- delete(key: string): Promise<void>;
-
- /**
- * Get a public/signed URL for a file
- */
- getUrl(key: string, expiresIn?: number): Promise<string>;
+| **WhatsApp Engine** | whatsapp-web.js, Baileys (`ENGINE_TYPE`) | whatsapp-web.js | Baileys is browser-free |
+| **Database** | SQLite, PostgreSQL (`DATABASE_TYPE`) | SQLite | PostgreSQL for large-scale production |
+| **Media Storage** | local, s3 (`STORAGE_TYPE`) | local | MinIO is the `s3` backend (`forcePathStyle`) |
+| **Cache** | Redis or disabled (`REDIS_ENABLED`) | Disabled | When disabled/unreachable, cache fails open (no-op) |
- /**
- * Check whether a file exists
- */
- exists(key: string): Promise<boolean>;
-}
-
-export interface UploadInput {
- buffer: Buffer;
- filename: string;
- mimetype: string;
- folder?: string;
-}
-
-export interface StorageResult {
- key: string;
- url: string;
- size: number;
- mimetype: string;
-}
-```
+### 3.13.1 Storage Service
-#### Local Storage Adapter
+Media storage is a **single service** (`src/common/storage/storage.service.ts`) that branches
+internally on `storageType` — there is no `I*Adapter` interface, separate adapter classes, or a
+`StorageFactory`. The two backends are `local` (the default; files under `./data/media`) and `s3`.
+**MinIO is not a separate type** — it is the `s3` backend; the S3 client is always created with
+`forcePathStyle: true`, which MinIO requires, and any S3-compatible endpoint works. The public method
+set is `putFile` / `getFile` / `listFiles` / `createExportStream` (export) / `importFromStream`
+(import), plus `getFileCount` and `getCurrentStorageType`.
```typescript
-// storage/adapters/local-storage.adapter.ts
-import { Injectable } from '@nestjs/common';
-import { ConfigService } from '@nestjs/config';
-import * as fs from 'fs/promises';
-import * as path from 'path';
-import { IStorageAdapter, UploadInput, StorageResult } from '../interfaces/storage-adapter.interface';
-
+// src/common/storage/storage.service.ts
@Injectable()
-export class LocalStorageAdapter implements IStorageAdapter {
- private readonly basePath: string;
- private readonly baseUrl: string;
-
- constructor(private config: ConfigService) {
- this.basePath = config.get('storage.local.path', './media');
- this.baseUrl = config.get('storage.local.baseUrl', '/media');
- }
-
- async upload(input: UploadInput): Promise<StorageResult> {
- const folder = input.folder || 'uploads';
- const key = `${folder}/${Date.now()}-${input.filename}`;
- const fullPath = path.join(this.basePath, key);
-
- // Ensure directory exists
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
-
- // Write file
- await fs.writeFile(fullPath, input.buffer);
-
- return {
- key,
- url: `${this.baseUrl}/${key}`,
- size: input.buffer.length,
- mimetype: input.mimetype,
- };
- }
-
- async download(key: string): Promise<Buffer> {
- const fullPath = path.join(this.basePath, key);
- return fs.readFile(fullPath);
- }
-
- async delete(key: string): Promise<void> {
- const fullPath = path.join(this.basePath, key);
- await fs.unlink(fullPath).catch(() => {}); // Ignore if not exists
- }
-
- async getUrl(key: string): Promise<string> {
- return `${this.baseUrl}/${key}`;
- }
-
- async exists(key: string): Promise<boolean> {
- const fullPath = path.join(this.basePath, key);
- try {
- await fs.access(fullPath);
- return true;
- } catch {
- return false;
+export class StorageService {
+ private readonly storageType: string; // 'local' | 's3'
+ private readonly localPath: string;
+ private s3Client: S3Client | null = null;
+
+ constructor(private readonly configService: ConfigService) {
+ this.storageType = this.configService.get<string>('storage.type') || 'local';
+ this.localPath = this.configService.get<string>('storage.localPath') || './data/media';
+
+ if (this.storageType === 's3') {
+ const endpoint = process.env.S3_ENDPOINT; // S3 / MinIO endpoint
+ const accessKeyId = process.env.S3_ACCESS_KEY_ID; // legacy S3_ACCESS_KEY also read
+ const secretAccessKey = process.env.S3_SECRET_ACCESS_KEY;
+ if (endpoint && accessKeyId && secretAccessKey) {
+ this.s3Client = new S3Client({
+ endpoint,
+ region: process.env.S3_REGION || 'us-east-1',
+ credentials: { accessKeyId, secretAccessKey },
+ forcePathStyle: true, // Required for MinIO; harmless for AWS S3
+ });
+ // bucket auto-created if missing (HeadBucket -> CreateBucket)
+ }
}
+ if (!fs.existsSync(this.localPath)) fs.mkdirSync(this.localPath, { recursive: true });
}
-}
-```
-
-#### S3/MinIO Storage Adapter
-
-```typescript
-// storage/adapters/s3-storage.adapter.ts
-import { Injectable } from '@nestjs/common';
-import { ConfigService } from '@nestjs/config';
-import {
- S3Client,
- PutObjectCommand,
- GetObjectCommand,
- DeleteObjectCommand,
- HeadObjectCommand
-} from '@aws-sdk/client-s3';
-import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
-import { IStorageAdapter, UploadInput, StorageResult } from '../interfaces/storage-adapter.interface';
-
-@Injectable()
-export class S3StorageAdapter implements IStorageAdapter {
- private readonly client: S3Client;
- private readonly bucket: string;
-
- constructor(private config: ConfigService) {
- this.bucket = config.get('storage.s3.bucket');
-
- this.client = new S3Client({
- region: config.get('storage.s3.region', 'us-east-1'),
- endpoint: config.get('storage.s3.endpoint'), // For MinIO
- credentials: {
- accessKeyId: config.get('storage.s3.accessKeyId'),
- secretAccessKey: config.get('storage.s3.secretAccessKey'),
- },
- forcePathStyle: config.get('storage.s3.forcePathStyle', false), // true for MinIO
- });
- }
-
- async upload(input: UploadInput): Promise<StorageResult> {
- const folder = input.folder || 'uploads';
- const key = `${folder}/${Date.now()}-${input.filename}`;
-
- await this.client.send(new PutObjectCommand({
- Bucket: this.bucket,
- Key: key,
- Body: input.buffer,
- ContentType: input.mimetype,
- }));
-
- const url = await this.getUrl(key);
-
- return {
- key,
- url,
- size: input.buffer.length,
- mimetype: input.mimetype,
- };
- }
-
- async download(key: string): Promise<Buffer> {
- const response = await this.client.send(new GetObjectCommand({
- Bucket: this.bucket,
- Key: key,
- }));
-
- return Buffer.from(await response.Body!.transformToByteArray());
- }
-
- async delete(key: string): Promise<void> {
- await this.client.send(new DeleteObjectCommand({
- Bucket: this.bucket,
- Key: key,
- }));
- }
-
- async getUrl(key: string, expiresIn = 3600): Promise<string> {
- const command = new GetObjectCommand({
- Bucket: this.bucket,
- Key: key,
- });
- return getSignedUrl(this.client, command, { expiresIn });
+ // Both backends share one path-safety guard (isSafeStorageKey) at this boundary.
+ async putFile(filePath: string, data: Buffer): Promise<void> {
+ if (!isSafeStorageKey(filePath)) throw new Error(`Refusing unsafe storage key: ${filePath}`);
+ return this.storageType === 's3' && this.s3Client
+ ? this.putS3File(filePath, data) // keyed under media/<filePath>
+ : this.putLocalFile(filePath, data);
}
- async exists(key: string): Promise<boolean> {
- try {
- await this.client.send(new HeadObjectCommand({
- Bucket: this.bucket,
- Key: key,
- }));
- return true;
- } catch {
- return false;
- }
- }
-}
-```
-
-#### Storage Factory
-
-```typescript
-// storage/storage.factory.ts
-import { Injectable } from '@nestjs/common';
-import { ConfigService } from '@nestjs/config';
-import { IStorageAdapter } from './interfaces/storage-adapter.interface';
-import { LocalStorageAdapter } from './adapters/local-storage.adapter';
-import { S3StorageAdapter } from './adapters/s3-storage.adapter';
-
-export type StorageType = 'local' | 's3' | 'minio';
-
-@Injectable()
-export class StorageFactory {
- constructor(private config: ConfigService) {}
-
- create(type?: StorageType): IStorageAdapter {
- const storageType = type || this.config.get<StorageType>('storage.type', 'local');
-
- switch (storageType) {
- case 'local':
- return new LocalStorageAdapter(this.config);
-
- case 's3':
- case 'minio':
- return new S3StorageAdapter(this.config);
-
- default:
- throw new Error(`Unknown storage type: ${storageType}`);
- }
- }
+ async getFile(filePath: string): Promise<Buffer> { /* mirrors putFile */ }
+ async listFiles(): Promise<string[]> { /* local recurse, or S3 ListObjectsV2 under media/ */ }
+ // createExportStream(): tar.gz of all files; importFromStream(): extract with zip-bomb caps
}
```
@@ -1567,85 +1317,52 @@ OpenWA supports SQLite for lightweight deployments and PostgreSQL for high-volum
#### TypeORM Configuration
-```typescript
-// config/database.config.ts
-import { ConfigService } from '@nestjs/config';
-import { TypeOrmModuleOptions } from '@nestjs/typeorm';
-
-export const getDatabaseConfig = (config: ConfigService): TypeOrmModuleOptions => {
- const dbType = config.get<'sqlite' | 'postgres'>('database.type', 'sqlite');
-
- const baseConfig = {
- entities: [__dirname + '/../**/*.entity{.ts,.js}'],
- migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
- synchronize: false,
- logging: config.get('database.logging', false),
- };
+Database wiring lives inline in `AppModule` (`src/app.module.ts`) as two named
+`TypeOrmModule.forRootAsync` connections — there is no standalone `getDatabaseConfig` helper. The
+`data` connection is the one shown below; the `main` connection is always SQLite (auth + audit). The
+`data` connection's type comes from `DATABASE_TYPE` (`sqlite` default, or `postgres`):
- if (dbType === 'sqlite') {
- return {
- ...baseConfig,
- type: 'sqlite',
- database: config.get('database.sqlite.path', './data/openwa.db'),
- // SQLite specific optimizations
- extra: {
- // Enable WAL mode for better concurrent reads
- PRAGMA: 'journal_mode = WAL',
- },
- };
- }
+```typescript
+// shape of the 'data' connection useFactory in src/app.module.ts
+const dbType = configService.get<'sqlite' | 'postgres'>('dataDatabase.type', 'sqlite');
+const baseConfig = {
+ entities: [/* session, webhook, message, template, engine entities */],
+ migrations: [__dirname + '/database/migrations/*{.ts,.js}'],
+ logging: configService.get<boolean>('dataDatabase.logging', false),
+};
- // PostgreSQL
+if (dbType === 'postgres') {
return {
- ...baseConfig,
- type: 'postgres',
- url: config.get('database.url'),
- ssl: config.get('database.ssl', false)
- ? { rejectUnauthorized: false }
- : false,
- extra: {
- max: config.get('database.pool.max', 20),
- connectionTimeoutMillis: 5000,
- idleTimeoutMillis: 30000,
- },
+ ...baseConfig, name: 'data', type: 'postgres',
+ host: configService.get('dataDatabase.host'),
+ port: configService.get('dataDatabase.port'),
+ username: configService.get('dataDatabase.username'),
+ password: configService.get('dataDatabase.password'),
+ database: configService.get('dataDatabase.name', 'openwa'),
+ synchronize: configService.get('dataDatabase.synchronize', false), // migrations in prod
+ migrationsRun: true,
+ extra: { max: configService.get('dataDatabase.poolSize', 10) },
};
+}
+
+// SQLite (default): migration-managed unless DATABASE_SYNCHRONIZE=true
+const synchronize = configService.get<boolean>('dataDatabase.synchronize', false);
+return {
+ ...baseConfig, name: 'data', type: 'sqlite',
+ database: configService.get('dataDatabase.database', './data/openwa.sqlite'),
+ synchronize,
+ migrationsRun: !synchronize,
};
```
#### SQLite Considerations
-```typescript
-// database/sqlite-optimizations.ts
-
-/**
- * SQLite-specific optimizations and limitations
- */
-export const SQLITE_CONFIG = {
- // Recommendations
- maxConcurrentSessions: 5,
- maxMessagesBeforeCleanup: 100000,
-
- // Auto-cleanup settings (no partitioning available)
- messageRetentionDays: 30,
- logRetentionDays: 7,
-
- // Write queue to avoid SQLITE_BUSY
- enableWriteQueue: true,
- writeQueueConcurrency: 1,
-};
-
-/**
- * Middleware for SQLite write serialization
- */
-@Injectable()
-export class SqliteWriteQueueService {
- private writeQueue = new PQueue({ concurrency: 1 });
-
- async executeWrite<T>(operation: () => Promise<T>): Promise<T> {
- return this.writeQueue.add(operation);
- }
-}
-```
+> **Note:** OpenWA does not currently apply SQLite-specific concurrency hardening. There is **no**
+> `journal_mode = WAL` PRAGMA, no `SqliteWriteQueueService`, and no application-level write
+> serialization or session cap in the source. SQLite is used with TypeORM's defaults, so its standard
+> single-writer behavior applies. For high write-concurrency or multi-session deployments, use
+> PostgreSQL (`DATABASE_TYPE=postgres`). Cross-dialect schema differences are handled at migration
+> time (see below), not by a runtime optimizations layer.
#### Migration Strategy
@@ -1687,36 +1404,48 @@ export abstract class DatabaseAwareMigration {
}
```
-### 3.13.3 Cache Adapter
+### 3.13.3 Cache Service
-For minimal deployments, in-memory cache is sufficient. For multi-instance deployments, Redis is required.
+There is **no** cache-manager / `CacheModuleOptions` / `redisStore` setup and **no** in-memory cache.
+`CacheService` (`src/common/cache/cache.service.ts`) talks to **ioredis directly** and is gated by
+`REDIS_ENABLED` (falling back to the `cache.enabled` config flag). When caching is disabled — or Redis
+is unreachable — the service **fails open**: every read returns `null` and every write is a silent
+no-op, so the app keeps serving from its source of truth. In other words, "no cache configured" means
+**no cache** (recompute), not an in-process LRU. Cache is therefore a pure optimization layer (session
+status/info/QR/list/stats, each with its own short TTL); it is never the source of truth.
```typescript
-// cache/cache.factory.ts
-import { CacheModuleOptions } from '@nestjs/cache-manager';
-import { ConfigService } from '@nestjs/config';
-import { redisStore } from 'cache-manager-redis-store';
-
-export const getCacheConfig = async (
- config: ConfigService
-): Promise<CacheModuleOptions> => {
- const cacheType = config.get<'memory' | 'redis'>('cache.type', 'memory');
-
- if (cacheType === 'memory') {
- return {
- ttl: config.get('cache.ttl', 300) * 1000,
- max: config.get('cache.max', 1000),
- };
+// src/common/cache/cache.service.ts
+@Injectable()
+export class CacheService implements OnModuleDestroy {
+ private redis: Redis | null = null;
+ private readonly enabled: boolean;
+
+ constructor(private readonly configService: ConfigService) {
+ // REDIS_ENABLED is the primary switch; cache.enabled is the legacy fallback.
+ this.enabled = process.env.REDIS_ENABLED === 'true' || configService.get<boolean>('cache.enabled', false);
+ // Lazy connect: the first isAvailable() call dials Redis (bounded retries).
}
- // Redis
- return {
- store: await redisStore({
- url: config.get('redis.url'),
- ttl: config.get('cache.ttl', 300),
- }),
- };
-};
+ async isAvailable(): Promise<boolean> {
+ if (!this.enabled) return false; // disabled -> always "no cache"
+ if (!this.redis) await this.tryConnect(); // bounded attempts
+ return this.ping();
+ }
+
+ // Fail-open reads/writes: unavailable Redis is a no-op, never an error to the caller.
+ async getSessionStatus(id: string): Promise<string | null> {
+ if (!(await this.isAvailable())) return null;
+ try { return await this.redis!.get(`session:${id}:status`); }
+ catch { return null; }
+ }
+
+ async setSessionStatus(id: string, status: string): Promise<void> {
+ if (!(await this.isAvailable())) return; // no-op when disabled/unreachable
+ try { await this.redis!.setex(`session:${id}:status`, /* TTL */ 300, status); }
+ catch { /* logged + swallowed */ }
+ }
+}
```
### 3.13.4 Deployment Profiles
@@ -1728,7 +1457,7 @@ flowchart LR
subgraph Minimal["🪶 Minimal Profile"]
M1[SQLite]
M2[Local Storage]
- M3[In-Memory Cache]
+ M3[No Cache]
M4[Single Session]
end
@@ -1749,10 +1478,13 @@ flowchart LR
| Profile | Database | Storage | Cache | Sessions | RAM | Use Case |
|---------|----------|---------|-------|----------|-----|----------|
-| **Minimal** | SQLite | Local | In-Memory | 1-3 | 512MB | Personal bot, testing |
+| **Minimal** | SQLite | Local | None | 1-3 | 512MB | Personal bot, testing |
| **Standard** | PostgreSQL | Local | Redis | 5-10 | 2GB | Small business |
| **Enterprise** | PostgreSQL | S3/MinIO | Redis | 10+ | 4GB+ | Agency, high volume |
+> Session counts are guidance only — there is **no enforced session cap** in the code
+> (no `MAX_SESSIONS` env var is read anywhere).
+
### Configuration Examples
#### Minimal Profile (.env)
@@ -1760,39 +1492,35 @@ flowchart LR
```bash
# Database
DATABASE_TYPE=sqlite
-DATABASE_SQLITE_PATH=./data/openwa.db
+DATABASE_NAME=./data/openwa.sqlite
# Storage
STORAGE_TYPE=local
-STORAGE_LOCAL_PATH=./media
-
-# Cache (in-memory, no config needed)
-CACHE_TYPE=memory
+STORAGE_LOCAL_PATH=./data/media
-# Session
-MAX_SESSIONS=3
-
-# No Redis needed
-# REDIS_URL=
+# Cache: omit / leave Redis disabled -> the cache layer no-ops (no in-memory cache)
+REDIS_ENABLED=false
```
#### Standard Profile (.env)
```bash
-# Database
+# Database (Postgres uses discrete host/port/credentials, not a single URL)
DATABASE_TYPE=postgres
-DATABASE_URL=postgresql://openwa:password@localhost:5432/openwa
+DATABASE_HOST=localhost
+DATABASE_PORT=5432
+DATABASE_NAME=openwa
+DATABASE_USERNAME=openwa
+DATABASE_PASSWORD=password
# Storage
STORAGE_TYPE=local
-STORAGE_LOCAL_PATH=./media
+STORAGE_LOCAL_PATH=./data/media
# Cache
-CACHE_TYPE=redis
-REDIS_URL=redis://localhost:6379
-
-# Session
-MAX_SESSIONS=10
+REDIS_ENABLED=true
+REDIS_HOST=localhost
+REDIS_PORT=6379
```
#### Enterprise Profile (.env)
@@ -1800,62 +1528,46 @@ MAX_SESSIONS=10
```bash
# Database
DATABASE_TYPE=postgres
-DATABASE_URL=postgresql://openwa:password@db-cluster:5432/openwa
-DATABASE_POOL_MAX=50
-
-# Storage
+DATABASE_HOST=db-cluster
+DATABASE_PORT=5432
+DATABASE_NAME=openwa
+DATABASE_USERNAME=openwa
+DATABASE_PASSWORD=password
+DATABASE_POOL_SIZE=50
+
+# Storage (S3 or any S3-compatible endpoint; MinIO uses the same vars)
STORAGE_TYPE=s3
-STORAGE_S3_BUCKET=openwa-media
-STORAGE_S3_REGION=ap-southeast-1
-STORAGE_S3_ACCESS_KEY_ID=xxx
-STORAGE_S3_SECRET_ACCESS_KEY=xxx
-# For MinIO:
-# STORAGE_S3_ENDPOINT=http://minio:9000
-# STORAGE_S3_FORCE_PATH_STYLE=true
+S3_BUCKET=openwa-media
+S3_REGION=ap-southeast-1
+S3_ACCESS_KEY_ID=xxx
+S3_SECRET_ACCESS_KEY=xxx
+S3_ENDPOINT=https://s3.ap-southeast-1.amazonaws.com
+# For MinIO, point S3_ENDPOINT at it (path-style is always on):
+# S3_ENDPOINT=http://minio:9000
# Cache
-CACHE_TYPE=redis
-REDIS_URL=redis://redis-cluster:6379
-
-# Session
-MAX_SESSIONS=50
-
-# Scaling
-ENABLE_CLUSTER_MODE=true
+REDIS_ENABLED=true
+REDIS_HOST=redis-cluster
+REDIS_PORT=6379
```
-### Auto-Detection & Recommendations
+> OpenWA runs as a single API instance per session-data volume; there is no cluster-mode flag.
+> "Enterprise" here describes vertical headroom (RAM, Postgres, S3, Redis), not multi-replica
+> horizontal scaling — see the single-instance note in §3.2.
-```typescript
-// config/profile-detector.ts
-import { Logger } from '@nestjs/common';
+### Choosing a Profile
-interface SystemResources {
- totalMemoryMB: number;
- availableMemoryMB: number;
- cpuCores: number;
-}
+OpenWA does not auto-detect a profile at runtime; pick one by available resources and expected load:
-export function detectRecommendedProfile(resources: SystemResources): string {
- const logger = new Logger('ProfileDetector');
+| Available RAM | Suggested profile | Backends |
+|---------------|-------------------|----------|
+| < ~1 GB | Minimal | SQLite + Local Storage, Redis disabled (no cache) |
+| ~1–4 GB | Standard | PostgreSQL + Local Storage + Redis |
+| > ~4 GB | Enterprise | PostgreSQL + S3/MinIO + Redis |
- if (resources.totalMemoryMB < 1024) {
- logger.warn('Low memory detected. Using minimal profile.');
- logger.warn('Recommendation: SQLite + Local Storage + In-Memory Cache');
- return 'minimal';
- }
+All profiles still run as a single API instance per session-data volume (see §3.2). Enterprise here
+means more vertical headroom and external backends, not multi-replica clustering.
- if (resources.totalMemoryMB < 4096) {
- logger.log('Standard resources detected.');
- logger.log('Recommendation: PostgreSQL + Local Storage + Redis');
- return 'standard';
- }
-
- logger.log('High resources detected.');
- logger.log('Recommendation: PostgreSQL + S3 + Redis with clustering');
- return 'enterprise';
-}
-```
---
<div align="center">
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index a581fa9d3..a54dab23a 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -112,42 +112,23 @@ interface IpWhitelistEntry {
}
```
-### API Endpoints
+### Managing the whitelist
-#### Add IP to Whitelist
+There is **no `/whitelist` sub-resource**. A key's allowed source IPs are the `allowedIps` field on the API key itself, set when you create or update the key via the API-keys endpoints (see §6.4.9 in the [API Specification](./06-api-specification.md)):
```http
-POST /api/auth/api-keys/:apiKeyId/whitelist
+POST /api/auth/api-keys
+PUT /api/auth/api-keys/:id
```
-**Request Body:**
```json
{
- "ipAddress": "203.0.113.50",
- "description": "Production server"
+ "name": "production-server",
+ "allowedIps": ["203.0.113.50", "10.0.0.0/24"]
}
```
-**For CIDR Range:**
-```json
-{
- "ipAddress": "10.0.0.0",
- "cidrRange": "10.0.0.0/24",
- "description": "Internal network"
-}
-```
-
-#### List Whitelisted IPs
-
-```http
-GET /api/auth/api-keys/:apiKeyId/whitelist
-```
-
-#### Remove IP from Whitelist
-
-```http
-DELETE /api/auth/api-keys/:apiKeyId/whitelist/:entryId
-```
+`allowedIps` accepts exact IPs and CIDR ranges. An empty or absent list means the key is **not** IP-restricted; a non-empty list fails closed (a request whose client IP can't be determined, or isn't in the list, is rejected). To change the whitelist, `PUT` the key with the new `allowedIps` array.
### Implementation
@@ -246,39 +227,24 @@ For IPv6, use a library that supports IPv6 parsing (e.g., `ipaddr.js`) when perf
## 4.4 Data Encryption
-### Encryption Strategy
+### In Transit
-```mermaid
-flowchart LR
- subgraph Transit["In Transit"]
- TLS[TLS 1.3]
- end
-
- subgraph Rest["At Rest"]
- AES[AES-256-GCM]
- end
-
- subgraph Sensitive["Sensitive Data"]
- AUTH[Auth State]
- PROXY[Proxy Credentials]
- SECRET[Webhook Secrets]
- end
-
- Sensitive --> AES
- AES --> DB[(Database)]
- Client --> TLS --> Server
-```
+OpenWA serves plain HTTP on its port; terminate **TLS at your reverse proxy / load balancer** (nginx, Traefik, Caddy) and expose the gateway only over HTTPS in production. The API key is bearer-equivalent and is sent on every request, so it must never traverse plaintext `http://` outside local development.
+
+### At Rest
+
+> **There is currently no application-level encryption at rest.** API keys are stored **hashed** (one-way), but other sensitive values are stored as plaintext in the database / on disk and are protected by filesystem and database permissions, not by encryption. Encryption at rest for these fields is a roadmap item, not a shipped feature — do not assume it.
-### What Gets Encrypted
+| Data | At rest | How it is protected |
+|------|---------|---------------------|
+| API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. |
+| Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |
+| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by any API response (write-only response DTO). |
+| Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs. |
+| Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. |
+| Message content | Plaintext in the `messages` table | Database access control. |
-| Data | Encrypted | Method |
-|------|-----------|--------|
-| API Keys | Yes | SHA-256 hash |
-| Auth State | Yes | AES-256-GCM |
-| Webhook Secrets | Yes | AES-256-GCM |
-| Proxy Passwords | Yes | AES-256-GCM |
-| Message Content | Optional | AES-256-GCM |
-| Session Config | No | - |
+**Hardening you can apply today:** set `API_KEY_PEPPER`; restrict the data volume and database to the app's user; and encrypt at the infrastructure layer (LUKS / cloud-provider encrypted volumes / an encrypted managed Postgres) rather than relying on application-level field encryption, which is not implemented.
## 4.5 Input Validation
@@ -303,7 +269,7 @@ flowchart TB
| `chatId` | Pattern: `^\d+@(c\.us\|g\.us)$` |
| `phone` | Pattern: `^\d{10,15}$` |
| `url` | Valid URL, HTTPS only for webhooks |
-| `text` | Max 65536 chars, sanitized |
+| `text` | Max 4096 chars (`send-text`) |
| `sessionName` | Alphanumeric + hyphen, 3-50 chars |
### DTO Validation
@@ -320,7 +286,7 @@ export class SendTextDto {
chatId: string;
@IsString()
- @MaxLength(65536)
+ @MaxLength(4096)
text: string;
}
@@ -344,32 +310,28 @@ flowchart LR
RL -->|Under Limit| APP[Application]
RL -->|Over Limit| ERR[429 Too Many Requests]
- subgraph Limits["Limit Tiers"]
- T1[Global: 1000/min]
- T2[Per Key: 100/min]
- T3[Per Endpoint: varies]
+ subgraph Limits["Global windows (per client IP)"]
+ T1[short: 10 / 1s]
+ T2[medium: 100 / 60s]
+ T3[long: 1000 / 1h]
end
```
-### Endpoint Limits
+### Windows
-| Endpoint Category | Rate Limit | Window |
-|-------------------|------------|--------|
-| Session Create | 5 | 1 minute |
-| Session Read | 60 | 1 minute |
-| Message Send | 30 | 1 minute |
-| Message Read | 60 | 1 minute |
-| Webhook CRUD | 10 | 1 minute |
-| Health Check | 120 | 1 minute |
+All limits are **global and per client IP** (resolved through `TRUSTED_PROXIES`), applied by a global `ThrottlerGuard`. There is **no per-endpoint limit table** — these three windows apply to every non-exempt route, and exceeding any one returns `429 Too Many Requests`:
-### Response Headers
+| Window | Default limit | Window length | Env overrides |
+|--------|---------------|---------------|---------------|
+| `short` | 10 requests | 1 s | `RATE_LIMIT_SHORT_TTL` / `RATE_LIMIT_SHORT_LIMIT` |
+| `medium` | 100 requests | 60 s | `RATE_LIMIT_MEDIUM_TTL` / `RATE_LIMIT_MEDIUM_LIMIT` |
+| `long` | 1000 requests | 3600 s | `RATE_LIMIT_LONG_TTL` / `RATE_LIMIT_LONG_LIMIT` |
-```http
-X-RateLimit-Limit: 30
-X-RateLimit-Remaining: 25
-X-RateLimit-Reset: 1706868060
-Retry-After: 45
-```
+TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes are exempt (`@SkipThrottle`). To enforce tighter per-route limits, lower the global windows or add a limiter at your reverse proxy.
+
+### Response on limit
+
+Exceeding any window returns `429 Too Many Requests` with a `Retry-After` header. The `ThrottlerGuard` also sets `X-RateLimit-*` response headers (limit / remaining / reset) by default, and the API exposes them via CORS — but with three named windows in play, the `429` + `Retry-After` is the simplest backpressure signal to act on.
## 4.7 CORS Configuration
@@ -481,6 +443,8 @@ app.use(helmet({
### What Gets Logged
+> **Reality check:** audit entries are persisted to the `audit_logs` table, but **only session-lifecycle actions are emitted today** (`session_created` / `session_started` / `session_stopped` / `session_force_killed` / `session_deleted` / `session_qr_generated`). The `AuditAction` enum also defines `api_key_auth_failed`, `message_sent`, and `webhook_*`, but **no code path emits them** (there is no global audit interceptor) — so failed auth, message sends, and webhook changes are **not** in the audit log yet (a tracked enhancement). Failed authentication currently surfaces only as a `logger.warn` in the application log. The diagram below is the intended coverage.
+
```mermaid
flowchart TB
subgraph Events["Logged Events"]
@@ -500,24 +464,29 @@ flowchart TB
```json
{
- "timestamp": "2025-02-02T10:00:00.000Z",
- "level": "info",
- "event": "api.request",
- "requestId": "uuid",
+ "id": "uuid",
+ "action": "session_started",
+ "severity": "info",
"apiKeyId": "uuid",
+ "sessionId": "sess_123",
"ip": "192.168.1.1",
"method": "POST",
- "path": "/api/sessions/sess_123/messages/send-text",
- "statusCode": 200,
- "responseTime": 150,
- "userAgent": "MyApp/1.0"
+ "path": "/api/sessions/sess_123/start",
+ "statusCode": 201,
+ "userAgent": "MyApp/1.0",
+ "metadata": {},
+ "createdAt": "2026-02-02T10:00:00.000Z"
}
```
+`action` is an `AuditAction` enum value (snake_case); `severity` is `info` / `warn` / `error`. There is no `requestId` or `responseTime` field, and no global request-logging interceptor — entries are written explicitly by the code paths that emit them.
+
### Security Alerts
-| Event | Severity | Action |
-|-------|----------|--------|
+> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The only related runtime behavior today is a `logger.warn` when an IP-restricted key is used from a disallowed IP. Forward the audit log / application log to your SIEM to build these alerts.
+
+| Event | Severity | Intended action (roadmap) |
+|-------|----------|---------------------------|
| Multiple failed auth | High | Alert + temp block |
| Rate limit exceeded | Medium | Log + block |
| Invalid signature | Medium | Log |
@@ -557,14 +526,16 @@ flowchart TB
### Secrets Inventory
-| Secret Type | Storage | Rotation |
-|-------------|---------|----------|
+| Secret | Storage | Rotation guidance |
+|--------|---------|-------------------|
| Database credentials | Environment variable | 90 days |
| Redis password | Environment variable | 90 days |
-| Encryption key | Environment variable | 365 days |
-| API master key | Environment variable | 180 days |
-| Webhook secrets | Database (encrypted) | Per webhook |
-| Session auth state | File system (default) / Database (optional, encrypted) | Never (tied to WA session) |
+| API master key (`API_MASTER_KEY`) | Environment variable | 180 days |
+| API key pepper (`API_KEY_PEPPER`) | Environment variable | Rotating it invalidates all existing key hashes |
+| Webhook secrets | Database — **plaintext**; never returned by the API | Per webhook |
+| Session auth state | File system (data volume) — **not encrypted** | Never (tied to the WA session) |
+
+> There is no application `ENCRYPTION_KEY` — OpenWA does not encrypt data at rest (see §4.4). The rotation cadences above are operational recommendations, not enforced by the app.
### Environment Variables Security
@@ -581,6 +552,8 @@ docker secret create db_password ./secret.txt
### Docker Secrets
+> **Caveat:** the `*_FILE` convention shown below requires a secret-file reader in the app (see "Reading Secrets" below), which is **not currently implemented** — OpenWA reads secrets straight from environment variables. Until that helper exists, pass secrets as plain env vars (e.g. an `.env` file with restricted permissions) rather than `_FILE` paths.
+
```yaml
# docker-compose.prod.yml
version: '3.8'
@@ -607,6 +580,8 @@ secrets:
### Reading Secrets in Application
+> **Not implemented as shown.** OpenWA does **not** read `<NAME>_FILE` Docker-secret files — there is no `getSecret()` helper today. Secrets come straight from `process.env`, layered at boot as `process.env` → `.env` → `data/.env.generated` (`override:false`, so a real environment value wins). The function below is a suggested pattern to add if you want Docker-secret `_FILE` support; as-is, `DATABASE_PASSWORD_FILE` / `ENCRYPTION_KEY_FILE` are not consulted.
+
```typescript
// config/secrets.ts
import { readFileSync, existsSync } from 'fs';
@@ -634,6 +609,8 @@ const dbPassword = getSecret('DATABASE_PASSWORD');
### Key Rotation Procedure
+> **Not applicable today.** OpenWA stores no encrypted-at-rest data (see §4.4), so there is no data-encryption key to rotate and no `rotateEncryptionKey()` in the codebase. The flow below is illustrative for if/when field-level encryption is added. To rotate the `API_MASTER_KEY` or `API_KEY_PEPPER`, use the API-key endpoints (§4.2) — rotating the pepper invalidates existing key hashes.
+
```mermaid
flowchart TB
A[Generate New Key] --> B[Update Secret Store]
@@ -709,6 +686,8 @@ updates:
### Security Scanning in CI
+> **Aspirational template — not in the repo.** There is no `security.yml`, no Snyk, and no CodeQL workflow today. The actual dependency check is an inline step in `ci.yml` (`npm audit --audit-level=critical`, run on push/PR — not on a schedule). The workflow below is a recommended setup to add if you want scheduled scanning and SAST.
+
```yaml
# .github/workflows/security.yml
name: Security Scan
@@ -875,7 +854,7 @@ communication:
4. Snapshot affected database
### Evidence Collection
-- Export API access logs: `npm run logs:export --since="2h"`
+- Capture the audit log (the `audit_logs` table / audit query API) and the application logs (`docker compose logs openwa`) — there is no `logs:export` script
- Database query logs
- Network traffic captures
- System metrics at incident time
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 1feca13fc..876fd0452 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -25,7 +25,7 @@ OpenWA supports two database backends that can be selected at deployment time:
> SQLite can be used in production with limitations:
>
> - Maximum ~5 concurrent sessions (due to single-writer limitation)
-> - No table partitioning support (requires auto-cleanup for messages)
+> - Single-file storage — back up `./data/*.sqlite` rather than relying on a dump tool
> - No horizontal scaling support
> - Ideal for: personal bots, small businesses with 1-3 WhatsApp numbers
>
@@ -46,7 +46,8 @@ OpenWA v0.2+ implements a **dual-database architecture** that separates boot con
│ • audit_logs │ • webhooks │
│ │ • messages │
│ │ • message_batches │
-│ │ • contacts │
+│ │ • templates │
+│ │ • (engine: baileys_stored_messages, lid_mappings) │
└─────────────────────────────┴───────────────────────────────────┘
```
@@ -132,11 +133,6 @@ connectedAt: Date | null;
erDiagram
SESSION ||--o{ WEBHOOK : has
SESSION ||--o{ MESSAGE : contains
- SESSION ||--o{ CONTACT : stores
- SESSION ||--o{ SESSION_LOG : generates
- API_KEY ||--o{ SESSION : manages
- API_KEY ||--o{ API_KEY_LOG : generates
- WEBHOOK ||--o{ WEBHOOK_LOG : generates
SESSION {
uuid id PK
@@ -145,8 +141,10 @@ erDiagram
varchar phone
varchar push_name
json config
- json auth_state
+ varchar proxy_url
+ varchar proxy_type
timestamp connected_at
+ timestamp last_active_at
timestamp created_at
timestamp updated_at
}
@@ -158,6 +156,7 @@ erDiagram
json events
varchar secret
json headers
+ json filters
boolean active
int retry_count
timestamp last_triggered_at
@@ -168,75 +167,50 @@ erDiagram
MESSAGE {
uuid id PK
uuid session_id FK
- varchar wa_message_id UK
+ varchar wa_message_id
varchar chat_id
- varchar from_number
- varchar to_number
- varchar type
+ varchar from
+ varchar to
text body
- json media
- int ack
- boolean from_me
- boolean is_group
- timestamp wa_timestamp
- timestamp created_at
- }
-
- CONTACT {
- uuid id PK
- uuid session_id FK
- varchar wa_contact_id UK
- varchar name
- varchar push_name
- varchar phone
- boolean is_my_contact
- boolean is_blocked
- varchar profile_pic_url
+ varchar type
+ varchar direction
+ bigint timestamp
+ json metadata
+ varchar status
timestamp created_at
- timestamp updated_at
}
API_KEY {
uuid id PK
- varchar key_hash UK
varchar name
- json permissions
- boolean active
+ varchar key_hash UK
+ varchar key_prefix
+ varchar role
+ simple_array allowed_ips
+ simple_array allowed_sessions
+ boolean is_active
timestamp expires_at
timestamp last_used_at
+ int usage_count
timestamp created_at
+ timestamp updated_at
}
- SESSION_LOG {
- uuid id PK
- uuid session_id FK
- varchar event
- varchar status
- json data
- timestamp created_at
- }
-
- WEBHOOK_LOG {
- uuid id PK
- uuid webhook_id FK
- varchar event
- int status_code
- int attempt
- json payload
- json response
- text error
- timestamp created_at
- }
-
- API_KEY_LOG {
+ AUDIT_LOG {
uuid id PK
- uuid api_key_id FK
- varchar endpoint
- varchar method
+ varchar action
+ varchar severity
+ varchar api_key_id
+ varchar api_key_name
+ varchar session_id
+ varchar session_name
varchar ip_address
- text user_agent
+ varchar user_agent
+ varchar method
+ varchar path
int status_code
- int response_time
+ json metadata
+ text error_message
timestamp created_at
}
```
@@ -255,20 +229,20 @@ CREATE TABLE sessions (
phone VARCHAR(20),
push_name VARCHAR(100),
config JSONB NOT NULL DEFAULT '{}',
- auth_state JSONB,
+ proxy_url VARCHAR(255),
+ proxy_type VARCHAR(10),
connected_at TIMESTAMP WITH TIME ZONE,
+ last_active_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
-
--- Indexes
-CREATE INDEX idx_sessions_status ON sessions(status);
-CREATE INDEX idx_sessions_phone ON sessions(phone);
-CREATE INDEX idx_sessions_created_at ON sessions(created_at);
```
> [!NOTE]
-> `auth_state` is optional and engine-specific. By default, `whatsapp-web.js` stores auth state on the filesystem, while Baileys can store an encrypted blob in the database when enabled. This column can store the blob or an encrypted pointer/path.
+> The SQL above is illustrative — the schema is defined by the TypeORM entity (`src/modules/session/entities/session.entity.ts`), and column types are dialect-portable (`jsonColumnType()` → `simple-json`, dates via `DateTransformer`). The `sessions` entity declares only the index implied by the `UNIQUE` constraint on `name`; there are no separate `status`/`phone`/`created_at` indexes.
+
+> [!NOTE]
+> Auth state is **not** stored in this table. Both engines persist credentials on the **filesystem** (`whatsapp-web.js` LocalAuth; Baileys `useMultiFileAuthState`). The `baileys_stored_messages` table holds only Baileys' serialized message store (the library ships none), not credentials.
**Session Status Values:**
@@ -329,16 +303,13 @@ CREATE TABLE webhooks (
events JSONB NOT NULL DEFAULT '["message.received"]',
secret VARCHAR(255),
headers JSONB DEFAULT '{}',
+ filters JSONB, -- optional smart pre-filter; null = fire on every subscribed event
active BOOLEAN NOT NULL DEFAULT true,
retry_count INTEGER NOT NULL DEFAULT 3,
last_triggered_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
-
--- Indexes
-CREATE INDEX idx_webhooks_session_id ON webhooks(session_id);
-CREATE INDEX idx_webhooks_active ON webhooks(active);
```
**Events Schema (allowed values):**
@@ -364,298 +335,139 @@ CREATE INDEX idx_webhooks_active ON webhooks(active);
### 5.3.3 messages
-Stores message history (optional, can be disabled).
-
-```sql
--- Main table with partitioning support (PostgreSQL 12+)
-CREATE TABLE messages (
- id UUID NOT NULL DEFAULT gen_random_uuid(),
- session_id UUID NOT NULL,
- wa_message_id VARCHAR(100) NOT NULL,
- chat_id VARCHAR(100) NOT NULL,
- from_number VARCHAR(50) NOT NULL,
- to_number VARCHAR(50),
- type VARCHAR(50) NOT NULL,
- body TEXT,
- media JSONB,
- ack INTEGER DEFAULT 0,
- from_me BOOLEAN NOT NULL DEFAULT false,
- is_group BOOLEAN NOT NULL DEFAULT false,
- wa_timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
-
- PRIMARY KEY (id, created_at),
- UNIQUE(session_id, wa_message_id, created_at)
-) PARTITION BY RANGE (created_at);
-
-> [!NOTE]
-> In PostgreSQL, UNIQUE on a partitioned table must include the partition key (`created_at`), so uniqueness applies per partition. If you need global uniqueness for `wa_message_id`, use a separate reference table or store messages in a non-partitioned table.
-
--- Create partitions for each month (automated via pg_cron or application)
-CREATE TABLE messages_y2025m01 PARTITION OF messages
- FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');
-CREATE TABLE messages_y2025m02 PARTITION OF messages
- FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');
-CREATE TABLE messages_y2025m03 PARTITION OF messages
- FOR VALUES FROM ('2025-03-01') TO ('2025-04-01');
--- Continue for other months...
-
--- Default partition for future data
-CREATE TABLE messages_default PARTITION OF messages DEFAULT;
-
--- Indexes (created on each partition automatically)
-CREATE INDEX idx_messages_session_id ON messages(session_id);
-CREATE INDEX idx_messages_chat_id ON messages(chat_id);
-CREATE INDEX idx_messages_wa_timestamp ON messages(wa_timestamp);
-CREATE INDEX idx_messages_session_chat ON messages(session_id, chat_id);
-CREATE INDEX idx_messages_type ON messages(type);
-CREATE INDEX idx_messages_from_me ON messages(from_me) WHERE from_me = true;
-
--- Function to auto-create partitions
-CREATE OR REPLACE FUNCTION create_messages_partition()
-RETURNS void AS $$
-DECLARE
- partition_date DATE;
- partition_name TEXT;
- start_date DATE;
- end_date DATE;
-BEGIN
- -- Create partition for next month
- partition_date := DATE_TRUNC('month', NOW() + INTERVAL '1 month');
- partition_name := 'messages_y' || TO_CHAR(partition_date, 'YYYY') || 'm' || TO_CHAR(partition_date, 'MM');
- start_date := partition_date;
- end_date := partition_date + INTERVAL '1 month';
-
- -- Check if partition exists
- IF NOT EXISTS (
- SELECT 1 FROM pg_tables WHERE tablename = partition_name
- ) THEN
- EXECUTE format(
- 'CREATE TABLE %I PARTITION OF messages FOR VALUES FROM (%L) TO (%L)',
- partition_name, start_date, end_date
- );
- RAISE NOTICE 'Created partition: %', partition_name;
- END IF;
-END;
-$$ LANGUAGE plpgsql;
-
--- Schedule with pg_cron (run on 25th of each month)
--- SELECT cron.schedule('create-messages-partition', '0 0 25 * *', 'SELECT create_messages_partition()');
-```
-
-**Non-Partitioned Version (for SQLite or simpler installations):**
+Stores message history (optional, can be disabled). This is a **plain (non-partitioned)** table — the same schema on SQLite and PostgreSQL.
```sql
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
- wa_message_id VARCHAR(100) NOT NULL,
- chat_id VARCHAR(100) NOT NULL,
- from_number VARCHAR(50) NOT NULL,
- to_number VARCHAR(50),
- type VARCHAR(50) NOT NULL,
+ session_id UUID NOT NULL,
+ wa_message_id VARCHAR, -- nullable; transient outgoing rows have none yet
+ chat_id VARCHAR NOT NULL,
+ "from" VARCHAR NOT NULL,
+ "to" VARCHAR NOT NULL,
body TEXT,
- media JSONB,
- ack INTEGER DEFAULT 0,
- from_me BOOLEAN NOT NULL DEFAULT false,
- is_group BOOLEAN NOT NULL DEFAULT false,
- wa_timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
-
- UNIQUE(session_id, wa_message_id)
+ type VARCHAR NOT NULL DEFAULT 'text',
+ direction VARCHAR NOT NULL DEFAULT 'outgoing', -- 'incoming' | 'outgoing'
+ timestamp BIGINT, -- WhatsApp epoch seconds; read back as a JS number
+ metadata JSONB,
+ status VARCHAR NOT NULL DEFAULT 'sent', -- pending | sent | delivered | read | failed
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
+-- Indexes (declared on the entity)
CREATE INDEX idx_messages_session_id ON messages(session_id);
+CREATE INDEX idx_messages_session_created ON messages(session_id, created_at);
CREATE INDEX idx_messages_chat_id ON messages(chat_id);
-CREATE INDEX idx_messages_wa_timestamp ON messages(wa_timestamp);
-CREATE INDEX idx_messages_created_at ON messages(created_at);
-```
-
-**Media Schema:**
+CREATE INDEX idx_messages_status ON messages(status);
-```json
-{
- "mimetype": "image/jpeg",
- "filename": "image.jpg",
- "filesize": 102400,
- "url": "https://storage.example.com/...",
- "caption": "Check this out!"
-}
+-- Inbound dedup (issue #464): one row per (session_id, wa_message_id).
+-- NULL wa_message_id rows are exempt (SQL treats NULLs as distinct).
+CREATE UNIQUE INDEX "UQ_messages_sessionId_waMessageId"
+ ON messages(session_id, wa_message_id);
```
----
-
-### 5.3.4 contacts
+> [!NOTE]
+> There is **no** PostgreSQL RANGE partitioning, `create_messages_partition()` function, or `pg_cron` schedule in OpenWA. `messages` is a single plain table on both backends. The `timestamp` column uses a `bigint→number` value transformer so the REST/SDK/MCP contract returns a JS number on both SQLite and PostgreSQL.
-WhatsApp contacts cache.
+> [!NOTE]
+> Message rows carry no separate `media`/`ack`/`from_me`/`is_group` columns. Media and other engine-specific details are stored in the `metadata` JSON column; delivery state is the `status` enum and `direction` distinguishes inbound vs. outbound.
-```sql
-CREATE TABLE contacts (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
- wa_contact_id VARCHAR(100) NOT NULL,
- name VARCHAR(255),
- push_name VARCHAR(255),
- phone VARCHAR(20),
- is_my_contact BOOLEAN NOT NULL DEFAULT false,
- is_blocked BOOLEAN NOT NULL DEFAULT false,
- profile_pic_url TEXT,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+---
- UNIQUE(session_id, wa_contact_id)
-);
+### 5.3.4 (removed) contacts
--- Indexes
-CREATE INDEX idx_contacts_session_id ON contacts(session_id);
-CREATE INDEX idx_contacts_phone ON contacts(phone);
-```
+> [!NOTE]
+> **There is no `contacts` table.** Contacts are read live from the engine on demand (e.g. `GET /sessions/:id/contacts`) and are not persisted to the database.
---
### 5.3.5 api_keys
-Stores API keys for authentication.
+Stores API keys for authentication. Lives on the **main** (always-SQLite) connection.
```sql
CREATE TABLE api_keys (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- key_hash VARCHAR(64) NOT NULL UNIQUE,
+ id VARCHAR PRIMARY KEY,
name VARCHAR(100) NOT NULL,
- permissions JSONB NOT NULL DEFAULT '["*"]',
- active BOOLEAN NOT NULL DEFAULT true,
- expires_at TIMESTAMP WITH TIME ZONE,
- last_used_at TIMESTAMP WITH TIME ZONE,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ key_hash VARCHAR(64) NOT NULL, -- UNIQUE index
+ key_prefix VARCHAR(12) NOT NULL, -- shown in the UI; the full key is never stored
+ role VARCHAR(20) NOT NULL DEFAULT 'operator', -- admin | operator | viewer
+ allowed_ips TEXT, -- simple-array (comma-joined), null = any IP
+ allowed_sessions TEXT, -- simple-array, null = all sessions
+ is_active BOOLEAN NOT NULL DEFAULT 1,
+ expires_at DATETIME,
+ last_used_at DATETIME,
+ usage_count INTEGER NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL DEFAULT (datetime('now')),
+ updated_at DATETIME NOT NULL DEFAULT (datetime('now'))
);
--- Indexes
-CREATE INDEX idx_api_keys_key_hash ON api_keys(key_hash);
-CREATE INDEX idx_api_keys_active ON api_keys(active);
+CREATE UNIQUE INDEX "IDX_api_keys_keyHash" ON api_keys(key_hash);
```
-**Permissions Schema:**
-
-```json
-["sessions:read", "sessions:write", "messages:send", "webhooks:manage"]
-```
-
-| Permission | Description |
-| ----------------- | ---------------------- |
-| `*` | Full access |
-| `sessions:read` | Read session info |
-| `sessions:write` | Create/delete sessions |
-| `messages:send` | Send messages |
-| `messages:read` | Read message history |
-| `webhooks:manage` | Manage webhooks |
-| `contacts:read` | Read contacts |
-| `groups:read` | Read groups |
-| `groups:write` | Manage groups |
-
----
-
-### 5.3.6 session_logs
-
-Audit log for session events.
-
-```sql
-CREATE TABLE session_logs (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
- event VARCHAR(100) NOT NULL,
- status VARCHAR(50),
- data JSONB,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
-);
-
--- Indexes
-CREATE INDEX idx_session_logs_session_id ON session_logs(session_id);
-CREATE INDEX idx_session_logs_event ON session_logs(event);
-CREATE INDEX idx_session_logs_created_at ON session_logs(created_at);
-
--- Auto-cleanup old logs (PostgreSQL)
--- Consider pg_cron or application-level cleanup
-```
+> [!NOTE]
+> Access control is **role-based** (`admin` / `operator` / `viewer`), optionally scoped by `allowed_ips` and `allowed_sessions`. There is no granular `permissions` string array — see [04 - Security Design](./04-security-design.md) for what each role can do.
---
-### 5.3.7 webhook_logs
+### 5.3.6 audit_logs
-Log delivery webhook.
+Consolidated audit trail for API-key, session, message, and webhook events. This is the **only** audit table — there are no separate `session_logs`, `webhook_logs`, or `api_key_logs` tables. Lives on the **main** (always-SQLite) connection.
```sql
-CREATE TABLE webhook_logs (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- webhook_id UUID NOT NULL REFERENCES webhooks(id) ON DELETE CASCADE,
- event VARCHAR(100) NOT NULL,
+CREATE TABLE audit_logs (
+ id VARCHAR PRIMARY KEY,
+ action VARCHAR(50) NOT NULL, -- e.g. session_created, message_sent, webhook_failed
+ severity VARCHAR(10) NOT NULL DEFAULT 'info', -- info | warn | error
+ api_key_id VARCHAR(36),
+ api_key_name VARCHAR(100),
+ session_id VARCHAR(36),
+ session_name VARCHAR(100),
+ ip_address VARCHAR(45),
+ user_agent VARCHAR(500),
+ method VARCHAR(10),
+ path VARCHAR(500),
status_code INTEGER,
- attempt INTEGER NOT NULL DEFAULT 1,
- payload JSONB NOT NULL,
- response JSONB,
- error TEXT,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ metadata TEXT, -- simple-json
+ error_message TEXT,
+ created_at DATETIME NOT NULL DEFAULT (datetime('now'))
);
--- Indexes
-CREATE INDEX idx_webhook_logs_webhook_id ON webhook_logs(webhook_id);
-CREATE INDEX idx_webhook_logs_created_at ON webhook_logs(created_at);
-CREATE INDEX idx_webhook_logs_status_code ON webhook_logs(status_code);
+-- Indexes (declared on the entity)
+CREATE INDEX "IDX_audit_logs_action" ON audit_logs(action);
+CREATE INDEX "IDX_audit_logs_apiKeyId" ON audit_logs(api_key_id);
+CREATE INDEX "IDX_audit_logs_sessionId" ON audit_logs(session_id);
+CREATE INDEX "IDX_audit_logs_createdAt" ON audit_logs(created_at);
```
----
-
-### 5.3.8 api_key_logs
+**Audit actions** are an enum (`AuditAction`) spanning API-key lifecycle (`api_key_created`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`), session lifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`, `session_deleted`, `session_qr_generated`, `session_connected`, `session_disconnected`), messages (`message_sent`, `message_failed`), and webhooks (`webhook_created`, `webhook_deleted`, `webhook_triggered`, `webhook_failed`).
-Audit log for API access.
-
-```sql
-CREATE TABLE api_key_logs (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- api_key_id UUID REFERENCES api_keys(id) ON DELETE SET NULL,
- endpoint VARCHAR(255) NOT NULL,
- method VARCHAR(10) NOT NULL,
- ip_address VARCHAR(45),
- user_agent TEXT,
- status_code INTEGER NOT NULL,
- response_time INTEGER,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
-);
-
--- Indexes
-CREATE INDEX idx_api_key_logs_api_key_id ON api_key_logs(api_key_id);
-CREATE INDEX idx_api_key_logs_created_at ON api_key_logs(created_at);
-CREATE INDEX idx_api_key_logs_endpoint ON api_key_logs(endpoint);
-```
+> [!NOTE]
+> Audit-log retention is automatic: see [§5.7 Data Retention](#57-data-retention). Other event types (session logs, webhook delivery logs, API access logs) are surfaced via structured application logging, not dedicated database tables.
-### 5.3.9 batch_jobs
+### 5.3.7 message_batches
-Stores status for batch/bulk message jobs.
+Tracks bulk/batch message jobs. A single table holds the job state plus its messages, options, progress, and per-message results as JSON columns (there are **no** separate `batch_jobs` / `batch_job_messages` tables).
```sql
-CREATE TABLE batch_jobs (
+CREATE TABLE message_batches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- batch_id VARCHAR(100) NOT NULL UNIQUE,
- session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
- total_messages INTEGER NOT NULL,
- sent_count INTEGER NOT NULL DEFAULT 0,
- failed_count INTEGER NOT NULL DEFAULT 0,
- cancelled_count INTEGER NOT NULL DEFAULT 0,
- options JSONB NOT NULL DEFAULT '{}',
- error TEXT,
- started_at TIMESTAMP WITH TIME ZONE,
- completed_at TIMESTAMP WITH TIME ZONE,
+ batch_id VARCHAR NOT NULL UNIQUE,
+ session_id VARCHAR NOT NULL,
+ status VARCHAR NOT NULL DEFAULT 'pending', -- pending | processing | completed | cancelled | failed
+ messages JSONB NOT NULL, -- [{ chatId, type, content, variables? }]
+ options JSONB, -- { delayBetweenMessages, randomizeDelay, stopOnError }
+ progress JSONB, -- { total, sent, failed, pending, cancelled }
+ results JSONB, -- [{ chatId, status, messageId?, error?, sentAt? }]
+ current_index INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ started_at TIMESTAMP WITH TIME ZONE,
+ completed_at TIMESTAMP WITH TIME ZONE
);
-
--- Indexes
-CREATE INDEX idx_batch_jobs_session_id ON batch_jobs(session_id);
-CREATE INDEX idx_batch_jobs_status ON batch_jobs(status);
-CREATE INDEX idx_batch_jobs_created_at ON batch_jobs(created_at);
```
-**Batch Job Status Values:**
+**Batch Status Values:**
| Status | Description |
| ------------ | ------------------------------ |
@@ -667,90 +479,16 @@ CREATE INDEX idx_batch_jobs_created_at ON batch_jobs(created_at);
---
-### 5.3.10 batch_job_messages
-
-Details of each message in a batch job.
-
-```sql
-CREATE TABLE batch_job_messages (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- batch_job_id UUID NOT NULL REFERENCES batch_jobs(id) ON DELETE CASCADE,
- chat_id VARCHAR(100) NOT NULL,
- message_type VARCHAR(50) NOT NULL,
- content JSONB NOT NULL,
- variables JSONB,
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
- wa_message_id VARCHAR(100),
- error_code VARCHAR(100),
- error_message TEXT,
- sent_at TIMESTAMP WITH TIME ZONE,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
-);
-
--- Indexes
-CREATE INDEX idx_batch_job_messages_batch_job_id ON batch_job_messages(batch_job_id);
-CREATE INDEX idx_batch_job_messages_status ON batch_job_messages(status);
-```
-
----
-
-### 5.3.11 webhook_idempotency
-
-Idempotency tracking for webhook delivery.
-
-```sql
-CREATE TABLE webhook_idempotency (
- idempotency_key VARCHAR(255) PRIMARY KEY,
- webhook_id UUID REFERENCES webhooks(id) ON DELETE CASCADE,
- event_type VARCHAR(100) NOT NULL,
- processed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- response_status INTEGER,
- response_data JSONB
-);
-
--- Index for cleanup job
-CREATE INDEX idx_webhook_idempotency_processed_at ON webhook_idempotency(processed_at);
-
--- Auto-cleanup old entries (24 hours retention)
--- Run via pg_cron or application-level scheduler
--- DELETE FROM webhook_idempotency WHERE processed_at < NOW() - INTERVAL '24 hours';
-```
-
----
-
-### 5.3.12 ip_whitelist
-
-IP whitelist for API key restrictions.
-
-```sql
-CREATE TABLE ip_whitelist (
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- api_key_id UUID NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
- ip_address VARCHAR(45) NOT NULL,
- cidr_range VARCHAR(50),
- description VARCHAR(255),
- active BOOLEAN NOT NULL DEFAULT true,
- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
-
- UNIQUE(api_key_id, ip_address)
-);
+### 5.3.8 Other data-connection tables
--- Indexes
-CREATE INDEX idx_ip_whitelist_api_key_id ON ip_whitelist(api_key_id);
-CREATE INDEX idx_ip_whitelist_ip_address ON ip_whitelist(ip_address);
-```
+The data connection also owns:
-**IP Whitelist Examples:**
+- **`templates`** — reusable message templates (`src/modules/template/entities/template.entity.ts`), with a unique constraint on `(sessionId, name)` — one template name per session.
+- **`baileys_stored_messages`** — Baileys engine message store — the serialized WAMessage proto (`src/engine/adapters/baileys-stored-message.entity.ts`); present only when the Baileys engine is used. (Credentials live on the filesystem, not here.)
+- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).
-```sql
--- Allow specific IP
-INSERT INTO ip_whitelist (api_key_id, ip_address, description)
-VALUES ('uuid', '203.0.113.50', 'Production server');
-
--- Allow CIDR range
-INSERT INTO ip_whitelist (api_key_id, ip_address, cidr_range, description)
-VALUES ('uuid', '10.0.0.0', '10.0.0.0/24', 'Internal network');
-```
+> [!NOTE]
+> **Tables that do *not* exist.** Earlier drafts referenced `contacts`, `session_logs`, `webhook_logs`, `api_key_logs`, `webhook_idempotency`, and `ip_whitelist`. None of these are implemented. Contacts are read live from the engine; auditing is the single `audit_logs` table; webhook idempotency is not a persisted table; and per-key IP restrictions are stored inline on `api_keys.allowed_ips` (a `simple-array`), not in a separate `ip_whitelist` table.
---
@@ -758,38 +496,33 @@ VALUES ('uuid', '10.0.0.0', '10.0.0.0/24', 'Internal network');
### Query Pattern Analysis
-| Query Pattern | Indexes Used | Frequency |
-| ------------------------------- | ------------------------------------------------------------- | --------- |
-| Get session by ID | `sessions.id` (PK) | Very High |
-| Get sessions by status | `idx_sessions_status` | High |
-| Get messages by session + chat | `idx_messages_session_chat` | Very High |
-| Get messages by timestamp range | `idx_messages_wa_timestamp` + partition pruning | High |
-| Get webhooks by session | `idx_webhooks_session_id` | Medium |
-| Authenticate API key | `idx_api_keys_key_hash` | Very High |
-| Check IP whitelist | `idx_ip_whitelist_api_key_id` + `idx_ip_whitelist_ip_address` | High |
+These indexes are the ones declared on the entities (see §5.3); the rows below map them to the hot query paths.
-### Composite Index Guidelines
+| Query Pattern | Index Used | Frequency |
+| -------------------------------- | ----------------------------------------------------- | --------- |
+| Get session by ID | `sessions.id` (PK) | Very High |
+| Get session by name | `sessions.name` (UNIQUE) | High |
+| List messages by session (paged) | `(session_id, created_at)` composite | Very High |
+| Look up message by chat | `chat_id` | High |
+| Ack/dedup a message | `UQ_messages_sessionId_waMessageId` (UNIQUE) | Very High |
+| Authenticate API key | `IDX_api_keys_keyHash` (UNIQUE, main DB) | Very High |
+| Filter audit logs | `IDX_audit_logs_action` / `_apiKeyId` / `_sessionId` | Medium |
-```sql
--- For frequently joined queries
-CREATE INDEX idx_messages_session_chat_timestamp
- ON messages(session_id, chat_id, wa_timestamp DESC);
+### Composite & Unique Indexes (as implemented)
--- For filtering + sorting
-CREATE INDEX idx_session_logs_session_event_created
- ON session_logs(session_id, event, created_at DESC);
-
--- Partial indexes for common filters
-CREATE INDEX idx_sessions_ready
- ON sessions(id) WHERE status = 'ready';
-
-CREATE INDEX idx_webhooks_active
- ON webhooks(session_id) WHERE active = true;
+```sql
+-- messages: paged listing per session + ack-driven status update / inbound dedup
+CREATE INDEX idx_messages_session_created ON messages(session_id, created_at);
+CREATE UNIQUE INDEX "UQ_messages_sessionId_waMessageId" ON messages(session_id, wa_message_id);
-CREATE INDEX idx_api_keys_active_not_expired
- ON api_keys(key_hash) WHERE active = true AND (expires_at IS NULL OR expires_at > NOW());
+-- audit_logs (main DB): filter by action / key / session, ordered by time
+CREATE INDEX "IDX_audit_logs_action" ON audit_logs(action);
+CREATE INDEX "IDX_audit_logs_createdAt" ON audit_logs(created_at);
```
+> [!NOTE]
+> The partial/filtered indexes shown in earlier drafts (e.g. `WHERE status = 'ready'`, `WHERE active = true`) are not part of the current schema. Add them only if a real query pattern justifies the maintenance cost.
+
### Index Maintenance
```sql
@@ -818,7 +551,6 @@ ORDER BY pg_relation_size(i.indexrelid) DESC;
-- Reindex to reclaim space (run during maintenance window)
REINDEX TABLE messages;
-REINDEX TABLE webhook_logs;
```
## 5.5 Data Flow
@@ -856,127 +588,119 @@ flowchart LR
CONN[Connection Status]
end
- subgraph Persistent["Database State"]
+ subgraph Persistent["Database State (sessions row)"]
CONFIG[Session Config]
- AUTH[Auth State]
- LOGS[Session Logs]
+ META[status / phone / pushName]
+ TS[connectedAt / lastActiveAt]
+ end
+
+ subgraph FS["Engine Auth (not in sessions table)"]
+ FSAUTH[whatsapp-web.js: filesystem]
+ DBAUTH[Baileys: engine tables]
end
Memory -->|Sync| Persistent
Persistent -->|Restore| Memory
```
-## 5.5 Migration Strategy
+## 5.6 Migration Strategy
+
+OpenWA runs **two separate TypeORM connections**, each with its own migrations directory and CLI DataSource:
+
+| Connection | DataSource | Migrations dir | Owns |
+| ---------- | ----------------------- | --------------------------- | ---------------------------------------------------------------------- |
+| **main** | `data-source-main.ts` | `src/database/migrations-main/` | `api_keys`, `audit_logs` — always SQLite (`./data/main.sqlite`) |
+| **data** | `data-source.ts` | `src/database/migrations/` | `sessions`, `webhooks`, `messages`, `message_batches`, `templates`, engine tables — SQLite **or** PostgreSQL |
-### Migration Files Structure
+Migrations are hand-authored (TypeORM `synchronize` is off for both connections in production) and are idempotent (`IF NOT EXISTS`) so they are safe to adopt on a database originally created by `synchronize`.
+
+### Migration Files
```
-src/database/migrations/
-├── 1706868000000-CreateSessionsTable.ts
-├── 1706868000001-CreateWebhooksTable.ts
-├── 1706868000002-CreateMessagesTable.ts
-├── 1706868000003-CreateContactsTable.ts
-├── 1706868000004-CreateApiKeysTable.ts
-├── 1706868000005-CreateSessionLogsTable.ts
-├── 1706868000006-CreateWebhookLogsTable.ts
-└── 1706868000007-CreateApiKeyLogsTable.ts
+src/database/migrations-main/ # main connection (auth + audit, SQLite)
+└── 1779900000000-CreateAuthAuditTables.ts # creates api_keys + audit_logs
+
+src/database/migrations/ # data connection (pluggable)
+├── 1770108659848-AddMessageStatus.ts
+├── 1779235200000-AddUuidDefaultsForPostgres.ts # Postgres-only: gen_random_uuid() id DEFAULTs
+├── 1779840000000-AddTemplates.ts
+├── 1779900100000-AddMessageSessionWaIndex.ts
+├── 1781000000000-AddBaileysStoredMessages.ts
+├── 1781100000000-AddTemplateNameUnique.ts
+├── 1781200000000-AddLidMappings.ts
+├── 1781300000000-AddMessagesWaMessageIdUnique.ts # UNIQUE(sessionId, waMessageId) inbound dedup (#464)
+└── 1781500000000-AddWebhookFilters.ts
```
+> [!NOTE]
+> Run with `npm run migration:run` (data connection) and `npm run migration:run:main` (main connection). The `AddUuidDefaultsForPostgres` migration is dialect-guarded — it is a no-op on SQLite (TypeORM generates UUIDs in the driver layer) and only adds `DEFAULT gen_random_uuid()::varchar` on PostgreSQL.
+
### Sample Migration (TypeORM)
```typescript
-import { MigrationInterface, QueryRunner, Table } from 'typeorm';
+import { MigrationInterface, QueryRunner } from 'typeorm';
-export class CreateSessionsTable1706868000000 implements MigrationInterface {
- public async up(queryRunner: QueryRunner): Promise<void> {
- await queryRunner.createTable(
- new Table({
- name: 'sessions',
- columns: [
- {
- name: 'id',
- type: 'uuid',
- isPrimary: true,
- generationStrategy: 'uuid',
- default: 'gen_random_uuid()',
- },
- {
- name: 'name',
- type: 'varchar',
- length: '100',
- isUnique: true,
- },
- {
- name: 'status',
- type: 'varchar',
- length: '50',
- default: "'created'",
- },
- // ... more columns
- {
- name: 'created_at',
- type: 'timestamp with time zone',
- default: 'NOW()',
- },
- {
- name: 'updated_at',
- type: 'timestamp with time zone',
- default: 'NOW()',
- },
- ],
- }),
- true,
- );
+// Real migration: enforces inbound dedup on the data connection.
+export class AddMessagesWaMessageIdUnique1781300000000 implements MigrationInterface {
+ name = 'AddMessagesWaMessageIdUnique1781300000000';
- await queryRunner.createIndex(
- 'sessions',
- new TableIndex({
- name: 'idx_sessions_status',
- columnNames: ['status'],
- }),
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (!(await queryRunner.hasTable('messages'))) return;
+ // ... losslessly de-duplicate existing rows (keep earliest per sessionId+waMessageId) ...
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_sessionId_waMessageId"`);
+ await queryRunner.query(
+ `CREATE UNIQUE INDEX IF NOT EXISTS "UQ_messages_sessionId_waMessageId" ` +
+ `ON "messages" ("sessionId", "waMessageId")`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
- await queryRunner.dropTable('sessions');
+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_messages_sessionId_waMessageId"`);
}
}
```
-## 5.6 Data Retention
+## 5.7 Data Retention
### Retention Policies
-| Data Type | Default Retention | Configurable |
-| ------------ | ----------------- | ------------ |
-| Sessions | Indefinite | No |
-| Messages | 30 days | Yes |
-| Session Logs | 7 days | Yes |
-| Webhook Logs | 7 days | Yes |
-| API Key Logs | 30 days | Yes |
+Only **`audit_logs`** has an automated retention job. Everything else is kept indefinitely (sessions, webhooks, message history, batches) and is removed only by user action (e.g. deleting a session) or operational backup/restore — there is no message or log auto-purge.
-### Cleanup Job
+| Data Type | Default Retention | Configurable |
+| ------------------- | ----------------- | ------------------------------------- |
+| Sessions / Webhooks | Indefinite | No |
+| Messages / Batches | Indefinite | No (delete a session to drop its data) |
+| Audit logs | 90 days | Yes — `AUDIT_RETENTION_DAYS` (≤ 0 disables) |
-```typescript
-// Scheduled job to clean up old data
-@Cron('0 0 * * *') // Daily at midnight
-async cleanupOldData() {
- const messageRetention = config.get('retention.messages', 30);
- const logsRetention = config.get('retention.logs', 7);
+### Audit-Log Cleanup Job
- await this.messageRepo.delete({
- createdAt: LessThan(subDays(new Date(), messageRetention)),
- });
+`AuditService` prunes old `audit_logs` rows. It is **not** a `@Cron` — it runs once at startup, then on a 24-hour `setInterval` (`src/modules/audit/audit.service.ts`):
- await this.sessionLogRepo.delete({
- createdAt: LessThan(subDays(new Date(), logsRetention)),
- });
+```typescript
+// src/modules/audit/audit.service.ts (abridged)
+onModuleInit(): void {
+ const parsed = Number.parseInt(process.env.AUDIT_RETENTION_DAYS ?? '', 10);
+ const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;
+ if (retentionDays <= 0) return; // AUDIT_RETENTION_DAYS <= 0 disables retention
+
+ const runCleanup = () => this.cleanup(retentionDays).catch(/* best-effort */);
+ runCleanup(); // prune once at startup
+ this.cleanupTimer = setInterval(runCleanup, 24 * 60 * 60 * 1000); // then daily
+ this.cleanupTimer.unref?.();
+}
- // ... more cleanup
+async cleanup(olderThanDays = 30): Promise<number> {
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - olderThanDays);
+ const result = await this.auditRepository.delete({ createdAt: LessThan(cutoff) });
+ return result.affected || 0;
}
```
-## 5.7 Backup Strategy
+## 5.8 Backup Strategy
+
+> [!NOTE]
+> This section is **operational guidance**, not a built-in feature. OpenWA ships no scheduler, encryption step, or S3 uploader for backups — the diagram and script below are a recommended setup you wire up externally (cron, your host's backup tooling, etc.). For SQLite, back up the `./data/*.sqlite` files (including `./data/main.sqlite`); for PostgreSQL, use `pg_dump`. The JSON export/import endpoints in §5.1 are a portability path, not a backup mechanism.
### Backup Components
@@ -989,7 +713,7 @@ flowchart TB
ENCRYPT --> S3[S3/Cloud Storage]
end
- subgraph Schedule["Schedule"]
+ subgraph Schedule["Schedule (external, e.g. cron)"]
FULL[Full Backup<br/>Daily]
INCR[Incremental<br/>Hourly]
end
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index ec3aeaf11..c35460738 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3,124 +3,71 @@
## 6.1 API Overview
### Base URL
+
+Every REST route is mounted under the global `api` prefix:
+
```
-Production: https://your-domain.com/api
-Development: http://localhost:2785/api
+http://<host>:2785/api
```
+For local development that is `http://localhost:2785/api`; behind a reverse proxy substitute your public origin (the `/api` prefix is unchanged).
+
### Authentication
-```http
-# API Key in Header
-X-API-Key: your-api-key-here
-# Or in Query Parameter (not recommended)
-GET /api/sessions?apiKey=your-api-key-here
-```
+A global API-key guard protects every route unless it is explicitly marked **public** (`@Public()`). Send the key in the `X-API-Key` header:
-### Common Headers
```http
-Content-Type: application/json
-Accept: application/json
-X-API-Key: your-api-key
-X-Request-ID: optional-tracking-id (recommended)
+X-API-Key: owa_k1_your-api-key-here
```
-### API Key Management
-
-OpenWA creates an initial admin API key on first run. The key is printed in the
-startup logs and written to:
-
-- `data/.api-key` for local development
-- `/app/data/.api-key` inside the API container for Docker deployments
+> **REST auth is header-only.** A query-parameter API key is **not** accepted on REST routes. The only place an `?apiKey=` query value is honoured is the WebSocket (Socket.IO) handshake — see §6.5 Real-time API — which accepts the key via the handshake `auth.apiKey` field, the `X-API-Key` header, or an `?apiKey=` query string. Do not put the key in a REST URL.
-By default a random `owa_k1_...` admin key is generated on first run in all
-environments; set `ALLOW_DEV_API_KEY=true` to seed the well-known `dev-admin-key`
-for local development only. Use that admin key to create scoped keys for
-integrations. The full generated key is returned only once in the `apiKey`
-field of the create response.
+The metrics endpoint is the lone exception to the API-key scheme: it authenticates with `Authorization: Bearer <METRICS_TOKEN>` instead of `X-API-Key`.
-#### Create API Key
+### Common Headers
```http
-POST /api/auth/api-keys
+X-API-Key: owa_k1_your-api-key # required on every non-public REST route
+Content-Type: application/json # required on requests with a JSON body
```
-**Required role:** `admin`
+`Content-Type: application/json` is only needed when sending a body. There is no required `Accept` or `X-Request-ID` header.
-**Request Body:**
-```json
-{
- "name": "Production Bot",
- "role": "operator",
- "allowedIps": ["192.168.1.10", "10.0.0.0/8"],
- "allowedSessions": ["session-uuid-1"],
- "expiresAt": "2027-12-31T23:59:59Z"
-}
-```
+### Roles & Authorization
-Only `name` is required. `role` defaults to `operator`; valid roles are
-`admin`, `operator`, and `viewer`.
+API keys carry one of three roles, ordered by privilege:
-**Example:**
-```bash
-curl -X POST http://localhost:2785/api/auth/api-keys \
- -H "X-API-Key: $ADMIN_API_KEY" \
- -H "Content-Type: application/json" \
- -d '{
- "name": "n8n Integration",
- "role": "operator"
- }'
-```
+| Role | Rank | Can do |
+| --- | --- | --- |
+| `viewer` | 1 | Read-only routes (no `@RequireRole`, or routes that only need a valid key) |
+| `operator` | 2 | Everything a viewer can, plus write/action routes guarded by `@RequireRole(OPERATOR)` (send messages, group/contact mutations, etc.) |
+| `admin` | 3 | Everything, plus admin-only routes guarded by `@RequireRole(ADMIN)` (API-key management, settings) |
-**Response:**
-```json
-{
- "id": "2a8f41e3-3b9a-4a1d-b6d0-b9910df8f0be",
- "name": "n8n Integration",
- "keyPrefix": "owa_k1_abcd",
- "role": "operator",
- "isActive": true,
- "usageCount": 0,
- "createdAt": "2026-02-02T10:30:00.000Z",
- "apiKey": "owa_k1_abcd1234..."
-}
-```
+`@RequireRole(role)` enforces a **minimum** role using the hierarchy `VIEWER < OPERATOR < ADMIN`: a key satisfies the guard if its own rank is ≥ the required rank (so an `admin` key passes an `OPERATOR`-guarded route). A route with no `@RequireRole` accepts any valid key, including `viewer`. A key whose role is below the requirement gets `403 Forbidden`; a missing or invalid key gets `401 Unauthorized`.
+
+A key may additionally be scoped to specific sessions (`allowedSessions`) and/or source IPs (`allowedIps`). The scope/IP check runs in the guard **before** any role check, so a request outside that scope is rejected with `401` (not `403`) even if the role would otherwise allow it.
-#### API Key Endpoints
+### API-Key Lifecycle
-| Method | Endpoint | Description | Required role |
-|--------|----------|-------------|---------------|
-| `GET` | `/api/auth/api-keys` | List API keys | `admin` |
-| `POST` | `/api/auth/api-keys` | Create an API key | `admin` |
-| `GET` | `/api/auth/api-keys/:id` | Get API key details | `admin` |
-| `PUT` | `/api/auth/api-keys/:id` | Update API key metadata, role, IPs, sessions, or expiry | `admin` |
-| `DELETE` | `/api/auth/api-keys/:id` | Delete an API key | `admin` |
-| `POST` | `/api/auth/api-keys/:id/revoke` | Revoke an API key by setting it inactive | `admin` |
-| `POST` | `/api/auth/validate` | Validate the key in `X-API-Key` | Any key |
+OpenWA seeds an initial admin key on first run (printed to the startup log and written to `data/.api-key`, or `/app/data/.api-key` in Docker). Use it to mint scoped, lower-privilege keys for integrations. Full key creation, listing, rotation, and revocation are documented under the auth resource in **§6.4.9 (API Keys)**.
## 6.2 Response Format
-> **OpenWA returns the raw handler payload directly — there is NO `{success, data, meta}`
-> envelope.** A resource endpoint returns that resource object; a list endpoint returns a
-> bare array. Read fields directly (`response.id`, not `response.data.id`). Errors use the
-> NestJS default shape with the HTTP status in the status line.
->
-> *(The response examples elsewhere in this document predate this and may still show the
-> old wrapper; the shape described here is authoritative — see [the H8 finding](../_docs/2026-06-15-security-architecture-audit.md).)*
+> **OpenWA returns the raw handler payload directly — there is NO `{ success, data, meta }` envelope.** A resource route returns the resource object as-is; a list route returns a **bare JSON array**. Read fields directly (`response.id`, not `response.data.id`).
### Success Response
-A successful request returns the resource (or array) as-is:
+A successful request returns the resource (or array) exactly as the handler produced it:
```json
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "my-session",
- "status": "READY"
+ "status": "ready"
}
```
-List endpoints return a bare array:
+List endpoints return a bare array (some paginated list routes instead return a small wrapper such as `{ "messages": [...], "total": 42 }` — the per-endpoint docs state the exact shape):
```json
[
@@ -129,1858 +76,4477 @@ List endpoints return a bare array:
]
```
+Session `status` wire values are **lowercase**: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.
+
### Error Response
-Errors use the NestJS default shape (the HTTP status is on the status line, not in a `code` field):
+Errors use the NestJS default shape. The HTTP status is on the status line and mirrored in `statusCode`; there is no application-specific `code` field:
```json
{
"statusCode": 404,
- "message": "Webhook with id 'x' not found",
+ "message": "Session 'my-session' not found",
"error": "Not Found"
}
```
-Validation errors (`statusCode: 400`) return `message` as an array of field-level strings.
+Validation failures (`statusCode: 400`) return `message` as an **array** of field-level strings. A global `ValidationPipe` runs with `whitelist` + `forbidNonWhitelisted`, so any request-body field not declared on the DTO is rejected with `400`.
-### Timestamp Conventions
+### General Error Codes
-- All API timestamps use ISO 8601 UTC (example: `2026-02-02T10:00:00.000Z`).
-- If you need the original WhatsApp timestamp (epoch seconds), the field is named `waTimestamp`.
-
-### Error Codes
-
-#### General Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `VALIDATION_ERROR` | 400 | Invalid request parameters |
-| `UNAUTHORIZED` | 401 | Missing or invalid API key |
-| `FORBIDDEN` | 403 | Insufficient permissions |
-| `NOT_FOUND` | 404 | Resource not found |
-| `RATE_LIMITED` | 429 | Too many requests |
-| `INTERNAL_ERROR` | 500 | Server error |
-
-#### Session Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `SESSION_NOT_FOUND` | 404 | Session with the given ID was not found |
-| `SESSION_NOT_READY` | 400 | Session not authenticated/connected |
-| `SESSION_ALREADY_EXISTS` | 409 | Session with the given name already exists |
-| `SESSION_INITIALIZING` | 400 | Session is currently initializing |
-| `SESSION_QR_EXPIRED` | 400 | QR code expired, regeneration required |
-| `SESSION_AUTH_FAILED` | 401 | WhatsApp authentication failed |
-| `SESSION_DISCONNECTED` | 400 | Session disconnected from WhatsApp |
-| `SESSION_LOGGED_OUT` | 400 | Session already logged out from WhatsApp |
-| `SESSION_LIMIT_REACHED` | 403 | Maximum session limit reached |
-| `SESSION_BANNED` | 403 | WhatsApp number has been banned |
-
-#### Message Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `MESSAGE_SEND_FAILED` | 500 | Failed to send message to WhatsApp |
-| `MESSAGE_NOT_FOUND` | 404 | Message not found |
-| `MESSAGE_INVALID_CHAT_ID` | 400 | Invalid chatId format |
-| `MESSAGE_NUMBER_NOT_ON_WHATSAPP` | 400 | Number is not registered on WhatsApp |
-| `MESSAGE_MEDIA_TOO_LARGE` | 413 | Media size exceeds limit |
-| `MESSAGE_MEDIA_DOWNLOAD_FAILED` | 400 | Failed to download media from URL |
-| `MESSAGE_MEDIA_INVALID_FORMAT` | 400 | Unsupported media format |
-| `MESSAGE_TEXT_TOO_LONG` | 400 | Message text exceeds character limit |
-| `MESSAGE_BLOCKED_CONTACT` | 403 | Cannot send to a blocked contact |
-| `MESSAGE_RATE_LIMITED` | 429 | Too many messages in a short time |
-| `MESSAGE_QUOTED_NOT_FOUND` | 400 | Quoted message not found |
-
-#### Webhook Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `WEBHOOK_NOT_FOUND` | 404 | Webhook not found |
-| `WEBHOOK_URL_INVALID` | 400 | Invalid webhook URL |
-| `WEBHOOK_URL_UNREACHABLE` | 400 | Webhook URL is unreachable |
-| `WEBHOOK_DUPLICATE` | 409 | Webhook with this URL already exists |
-| `WEBHOOK_LIMIT_REACHED` | 403 | Maximum webhook limit per session reached |
-
-#### Group Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `GROUP_NOT_FOUND` | 404 | Group not found |
-| `GROUP_NOT_ADMIN` | 403 | Not a group admin |
-| `GROUP_PARTICIPANT_EXISTS` | 409 | Participant already exists in group |
-| `GROUP_PARTICIPANT_NOT_FOUND` | 404 | Participant not found in the group |
-| `GROUP_INVITE_INVALID` | 400 | Invalid invite link |
-| `GROUP_NAME_TOO_LONG` | 400 | Group name exceeds character limit |
-
-#### Contact Error Codes
-
-| Code | HTTP Status | Description |
-|------|-------------|-------------|
-| `CONTACT_NOT_FOUND` | 404 | Contact not found |
-| `CONTACT_BLOCKED` | 400 | Contact is already blocked |
-| `CONTACT_NOT_BLOCKED` | 400 | Contact is not blocked |
+| HTTP Status | Meaning | When |
+| --- | --- | --- |
+| `400` | Bad Request | DTO validation failed, unknown body field, or a business precondition not met (e.g. session not active, media over cap) |
+| `401` | Unauthorized | Missing/invalid/expired/revoked `X-API-Key` (or `METRICS_TOKEN` for metrics), a blocked source IP, or a key used outside its `allowedSessions` scope |
+| `403` | Forbidden | A valid, in-scope key whose **role** is below the route's `@RequireRole` requirement |
+| `404` | Not Found | The addressed resource (session, message, webhook, batch, …) does not exist |
+| `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name) |
+| `413` | Payload Too Large | Base64 media exceeds the media byte cap (see §6.3) |
+| `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |
-## 6.3 Media Specifications
+### Timestamp Conventions
-### Supported Media Types & Limits
+OpenWA uses **two** timestamp representations — be careful which a field is:
-```mermaid
-flowchart LR
- subgraph Media["Media Types"]
- IMG[Image]
- VID[Video]
- AUD[Audio]
- DOC[Document]
- STK[Sticker]
- end
+- **Message timestamps are epoch numbers (Unix seconds), not ISO strings.** This applies to the `timestamp` field on messages returned by send responses, history, and persisted message records (the persisted column is stored as a bigint and surfaced as a `number`).
+- **Entity audit fields use ISO-8601 UTC strings** (example: `2026-02-02T10:00:00.000Z`). This applies to `createdAt` / `updatedAt` on persisted entities, `expiresAt`, batch `startedAt` / `completedAt`, and similar metadata fields.
- subgraph Limits["Size Limits"]
- L1[16 MB]
- L2[64 MB]
- L3[16 MB]
- L4[100 MB]
- L5[500 KB]
- end
+## 6.3 Media Specifications
- IMG --> L1
- VID --> L2
- AUD --> L3
- DOC --> L4
- STK --> L5
-```
+### Media DTO (flat shape)
-### Image
+All media send routes (`send-image`, `send-video`, `send-audio`, `send-document`, `send-sticker`) share one **flat** request DTO — `SendMediaMessageDto`. There is **no** nested `{ image: { url } }` wrapper; the media source fields sit at the top level of the body:
-| Attribute | Value |
-|-----------|-------|
-| **Max File Size** | 16 MB |
-| **Supported Formats** | JPEG, PNG, WebP, GIF |
-| **Max Resolution** | 4096 x 4096 pixels |
-| **Recommended** | JPEG for photos, PNG for graphics |
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | yes | non-empty | Recipient — `<phone>@c.us` or `<groupId>@g.us` |
+| `url` | string | conditional | valid http/https URL; required when `base64` absent | Remote media URL. Fetched server-side through an SSRF guard; a blocked/internal URL yields `400` |
+| `base64` | string | conditional | required when `url` absent | Raw base64 media data. Decoded size is checked against the media cap |
+| `mimetype` | string | conditional | required when `base64` is used | MIME type, e.g. `image/jpeg`, `video/mp4`, `application/pdf` |
+| `filename` | string | no | max 255 chars | Optional file name (also used as the persisted body fallback for documents) |
+| `caption` | string | no | max 1024 chars | Optional caption (not persisted for audio) |
+
+Provide **exactly one** of `url` or `base64`. Omitting both, or supplying `base64` without `mimetype`, returns `400`.
```json
{
- "image": {
- "url": "https://example.com/image.jpg",
- "mimetype": "image/jpeg"
- },
- "caption": "Optional caption (max 1024 chars)"
+ "chatId": "[email protected]",
+ "url": "https://example.com/image.jpg",
+ "caption": "Check out this image!"
}
```
-### Video
-
-| Attribute | Value |
-|-----------|-------|
-| **Max File Size** | 64 MB (WhatsApp limit: 16 MB in many regions) |
-| **Supported Formats** | MP4, 3GP, AVI, MKV |
-| **Recommended Codec** | H.264 video, AAC audio |
-| **Max Duration** | ~3 menit (tergantung resolusi) |
-| **Recommended Resolution** | 720p or lower |
-
```json
{
- "video": {
- "url": "https://example.com/video.mp4",
- "mimetype": "video/mp4"
- },
- "caption": "Optional caption (max 1024 chars)",
- "gifPlayback": false
+ "chatId": "[email protected]",
+ "base64": "/9j/4AAQSkZJRg...",
+ "mimetype": "image/jpeg",
+ "filename": "photo.jpg"
}
```
-### Audio
-
-| Attribute | Value |
-|-----------|-------|
-| **Max File Size** | 16 MB |
-| **Supported Formats** | MP3, OGG, M4A, AMR, WAV |
-| **Voice Note (PTT)** | OGG Opus codec (auto-converted) |
-| **Max Duration** | ~15 menit |
+### Size Limit
-```json
-{
- "audio": {
- "url": "https://example.com/audio.mp3",
- "mimetype": "audio/mpeg"
- },
- "ptt": true
-}
-```
+There is a **single shared media byte cap**, not a per-type table. A base64 (or downloaded) media blob whose **decoded** size exceeds the cap is rejected with `413 Payload Too Large`. The cap is `MEDIA_DOWNLOAD_MAX_BYTES`, default **50 MiB (52,428,800 bytes)**; the same value bounds outbound base64 sends, remote-URL downloads, and inbound media. A non-positive or garbage override falls back to the default.
-### Document
+### Text Limit
-| Attribute | Value |
-|-----------|-------|
-| **Max File Size** | 100 MB |
-| **Supported Formats** | PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, ZIP, dll |
-| **Filename** | Max 100 karakter |
+`send-text` enforces a maximum body length of **4096 characters** (`text` is `@MaxLength(4096)`). Media captions are limited to **1024 characters**.
-```json
-{
- "document": {
- "url": "https://example.com/file.pdf",
- "mimetype": "application/pdf"
- },
- "filename": "report-2025.pdf",
- "caption": "Optional caption"
-}
-```
+## 6.4 REST API Reference
-### Sticker
+Every path below is prefixed with `/api`. Unless marked **public**, send `X-API-Key: <key>`; `OPERATOR`/`ADMIN` annotations require a key of at least that role. Responses are the raw payload (no envelope); list endpoints return a bare array.
-| Attribute | Value |
-|-----------|-------|
-| **Max File Size** | 500 KB |
-| **Format** | WebP |
-| **Dimensions** | 512 x 512 pixels |
-| **Animated** | Supported (WebP animated) |
+### 6.4.1 Sessions
-```json
-{
- "sticker": {
- "url": "https://example.com/sticker.webp",
- "mimetype": "image/webp"
- }
-}
-```
+Base path `/api/sessions`. Read routes return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config`, `proxyUrl`, and `proxyType` and renames the entity field `lastActiveAt` to `lastActive`. The one exception is `POST /api/sessions`, which returns the **raw `Session` entity** and therefore *does* expose `config`/`proxyUrl`/`proxyType`/`lastActiveAt`. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.
-### Media Input Options
+#### GET /api/sessions
-Media can be sent using three approaches:
+List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt` DESC.
-```typescript
-// Option 1: URL (recommended for large files)
-{
- "image": {
- "url": "https://example.com/image.jpg"
- }
-}
+**Auth:** API key · **Scope:** session-scoped (a scoped key sees only its `allowedSessions`; an ADMIN / null-allowlist key lists all)
-// Option 2: Base64 (for small files < 5MB)
-{
- "image": {
- "base64": "data:image/jpeg;base64,/9j/4AAQ..."
- }
-}
+**Response** `200`
-// Option 3: File path (for local files - server side only)
-{
- "image": {
- "path": "/uploads/image.jpg"
+```json
+[
+ {
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
+ "name": "my-bot",
+ "status": "ready",
+ "phone": "6281234567890",
+ "pushName": "My Bot",
+ "connectedAt": "2026-06-25T08:14:02.000Z",
+ "lastActive": "2026-06-25T09:01:55.000Z",
+ "createdAt": "2026-06-20T11:30:00.000Z",
+ "updatedAt": "2026-06-25T09:01:55.000Z",
+ "lastError": null
}
-}
+]
```
-### Text Message Limits
+`lastError` is non-null only when `status` is `failed`. `config`/`proxyUrl`/`proxyType` are not present (stripped by `fromEntity`).
-| Type | Max Length |
-|------|------------|
-| Regular text message | 65,536 characters |
-| Caption (image/video/document) | 1,024 characters |
-| Group name | 100 characters |
-| Group description | 2,048 characters |
-| Contact name | 100 characters |
+**Errors:** `401` missing/invalid `X-API-Key`
-## 6.4 API Endpoints
+#### GET /api/sessions/:id
-### 6.4.1 Sessions
+Get a single session by ID.
-#### Create Session
+**Auth:** API key · **Scope:** session-scoped (key's `allowedSessions` enforced against `:id`)
-```mermaid
-sequenceDiagram
- Client->>API: POST /sessions
- API->>Engine: Initialize
- Engine-->>API: QR Code
- API-->>Client: Session created + QR
-```
+**Path parameters**
-```http
-POST /api/sessions
-```
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | WhatsApp session UUID |
-**Request Body:**
-```json
-{
- "name": "my-bot",
- "webhook": {
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.sent"]
- }
-}
-```
+**Response** `200`
-**Response (201 Created):**
```json
{
- "id": "sess_abc123",
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
"name": "my-bot",
- "status": "INITIALIZING",
- "qr": null,
- "createdAt": "2025-02-02T10:00:00.000Z"
+ "status": "ready",
+ "phone": "6281234567890",
+ "pushName": "My Bot",
+ "connectedAt": "2026-06-25T08:14:02.000Z",
+ "lastActive": "2026-06-25T09:01:55.000Z",
+ "createdAt": "2026-06-20T11:30:00.000Z",
+ "updatedAt": "2026-06-25T09:01:55.000Z",
+ "lastError": null
}
```
----
-
-#### List Sessions
+**Errors:** `401` missing/invalid key, or key not scoped to this session · `404` session not found
-```http
-GET /api/sessions
-```
+#### GET /api/sessions/:id/qr
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `status` | string | Filter by status |
-| `page` | number | Page number (default: 1) |
-| `limit` | number | Items per page (default: 20) |
+Get the QR code (PNG data URL) for session authentication.
-**Response (200 OK):**
-```json
-[
- {
- "id": "sess_abc123",
- "name": "my-bot",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "createdAt": "2025-02-02T10:00:00.000Z"
- }
-]
-```
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
----
+**Path parameters**
-#### Get Session
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
-```http
-GET /api/sessions/:sessionId
-```
+**Response** `200` — `QRCodeResponseDto`
-**Response (200 OK):**
```json
{
- "id": "sess_abc123",
- "name": "my-bot",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "pushName": "My Bot",
- "platform": "android",
- "connectedAt": "2025-02-02T10:05:00.000Z",
- "createdAt": "2025-02-02T10:00:00.000Z"
+ "qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
+ "status": "qr_ready"
}
```
----
+`status` is the session's current lowercase status.
-**Session Status Values (API):**
+**Errors:** `400` session not started / QR not ready yet / already authenticated · `401` · `403` · `404` not found
-| Value | Description |
-|-------|-------------|
-| `INITIALIZING` | Session created, engine booting |
-| `SCAN_QR` | QR code ready / waiting for scan |
-| `CONNECTING` | QR scanned, connecting to WhatsApp |
-| `CONNECTED` | Connected and ready |
-| `DISCONNECTED` | Connection lost or logged out |
-| `FAILED` | Fatal error, manual intervention required |
+#### GET /api/sessions/:id/groups
-**Internal ↔ API Status Mapping:**
+Get all groups the session is a member of (paginated).
-| Internal Status (engine/db) | API Status |
-|-----------------------------|------------|
-| `initializing` | `INITIALIZING` |
-| `qr_ready` | `SCAN_QR` |
-| `connecting` | `CONNECTING` |
-| `ready` | `CONNECTED` |
-| `disconnected` | `DISCONNECTED` |
-| `error` | `FAILED` |
+**Auth:** API key · **Scope:** session-scoped
-> Internal statuses appear in engine logs and database records. API responses and webhooks always use the API status values above.
+**Path parameters**
----
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
-#### Get Session QR Code
+**Query parameters**
-```http
-GET /api/sessions/:sessionId/qr
-```
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `limit` | integer (1–1000) | No | `1000` | Max groups to return |
+| `offset` | integer | No | `0` | Number of groups to skip for paging |
+
+**Response** `200`
-**Response (200 OK):**
```json
-{
- "code": "2@ABC123...",
- "image": "data:image/png;base64,..."
-}
+[
+ { "id": "[email protected]", "name": "Project Team", "linkedParentJID": null }
+]
```
----
+Bare array mapped from the engine's group list then paginated. `linkedParentJID` is present for community-linked groups.
-#### Delete Session
+**Errors:** `400` session not started (engine not in memory) · `401` · `403` · `404` session not found
-```http
-DELETE /api/sessions/:sessionId
-```
+#### GET /api/sessions/:id/chats
-**Response (200 OK):**
-```json
-{
- "message": "Session deleted successfully"
-}
-```
+Get active chats for a session, most-recent first (paginated).
----
+**Auth:** API key · **Scope:** session-scoped
-#### Logout Session
+**Path parameters**
-```http
-POST /api/sessions/:sessionId/logout
-```
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `limit` | integer (1–1000) | No | `1000` | Max chats to return |
+| `offset` | integer | No | `0` | Chats to skip for paging |
+
+**Response** `200` — `ChatSummary[]`
-**Response (200 OK):**
```json
-{
- "message": "Session logged out successfully"
-}
+[
+ {
+ "name": "Alice",
+ "isGroup": false,
+ "unreadCount": 2,
+ "timestamp": 1719306115,
+ "lastMessage": "See you tomorrow"
+ }
+]
```
----
+Sorted by `timestamp` DESC (most recent first) then paginated. `timestamp` is an epoch number (seconds).
-### 6.4.2 Messages
+**Errors:** `400` session not started · `401` · `403` · `404` session not found
-#### Send Text Message
+#### GET /api/sessions/stats/overview
-```mermaid
-flowchart LR
- A[Client] -->|POST| B["/messages/send-text"]
- B --> C{Validate}
- C -->|OK| D[Queue]
- D --> E[Send]
- E --> F[Response]
-```
+Get session statistics for multi-session monitoring.
-```http
-POST /api/sessions/:sessionId/messages/send-text
-```
+**Auth:** API key · **Scope:** session-scoped (aggregate counts limited to the key's `allowedSessions`)
-**Request Body:**
-```json
-{
- "chatId": "[email protected]",
- "text": "Hello, World!",
- "options": {
- "quotedMessageId": "optional_message_id",
- "mentionedIds": ["[email protected]"]
- }
-}
-```
+**Response** `200`
-**Response (200 OK):**
```json
{
- "messageId": "[email protected]_3EB0ABC123",
- "status": "sent",
- "timestamp": "2025-02-02T10:00:00.000Z"
+ "total": 4,
+ "active": 2,
+ "ready": 2,
+ "disconnected": 1,
+ "byStatus": { "ready": 2, "disconnected": 1, "created": 1 },
+ "memoryUsage": { "heapUsed": 142, "heapTotal": 210, "rss": 318 }
}
```
----
+`byStatus` is keyed by lowercase status values. `memoryUsage` values are megabytes (`Math.round(bytes / 1024 / 1024)`). `active` = count of running engines. A scoped key sees only its `allowedSessions` stats.
-#### Send Image
+**Errors:** `401` missing/invalid `X-API-Key`
-```http
-POST /api/sessions/:sessionId/messages/send-image
-```
+#### POST /api/sessions
-**Request Body:**
-```json
-{
- "chatId": "[email protected]",
- "image": {
- "url": "https://example.com/image.jpg"
- },
- "caption": "Check this out!"
-}
-```
+Create a new WhatsApp session.
-**Alternative - Base64:**
-```json
-{
- "chatId": "[email protected]",
- "image": {
- "base64": "data:image/jpeg;base64,/9j/4AAQ..."
- },
- "caption": "Check this out!"
-}
-```
+**Auth:** API key (OPERATOR)
+
+**Request body** — `CreateSessionDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `name` | string | Yes | `@IsString`; length 3–50; `@Matches(/^[a-zA-Z0-9-]+$/)` (letters, numbers, hyphens only) | Unique session name; duplicate → `409` |
+| `config` | object | No | `@IsOptional` (arbitrary object, no shape validation) | Opaque engine config; defaults to `{}`; never returned by read routes |
+| `proxyUrl` | string | No | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed; not SSRF-blocked |
+| `proxyType` | `http` \| `https` \| `socks4` \| `socks5` | No | `@IsOptional`; `@IsIn([...])` | Proxy protocol |
-**Response (200 OK):**
```json
{
- "messageId": "[email protected]_3EB0ABC124",
- "status": "sent",
- "timestamp": "2025-02-02T10:00:00.000Z"
+ "name": "my-bot",
+ "config": { "autoReconnect": true },
+ "proxyUrl": "http://proxy.example.com:8080",
+ "proxyType": "http"
}
```
----
-
-#### Send Video
+Minimal: `{ "name": "my-bot" }`.
-```http
-POST /api/sessions/:sessionId/messages/send-video
-```
+**Response** `201`
-**Request Body:**
```json
{
- "chatId": "[email protected]",
- "video": {
- "url": "https://example.com/video.mp4"
- },
- "caption": "Watch this!"
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
+ "name": "my-bot",
+ "status": "created",
+ "phone": null,
+ "pushName": null,
+ "config": { "autoReconnect": true },
+ "proxyUrl": "http://proxy.example.com:8080",
+ "proxyType": "http",
+ "connectedAt": null,
+ "lastActiveAt": null,
+ "createdAt": "2026-06-25T09:00:00.000Z",
+ "updatedAt": "2026-06-25T09:00:00.000Z"
}
```
----
+This route returns the **raw `Session` entity** (not via `fromEntity`), so `config`/`proxyUrl`/`proxyType`/`lastActiveAt` are present here only. Newly created `status` is `created`.
-#### Send Audio
+**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role · `409` session name already exists
-```http
-POST /api/sessions/:sessionId/messages/send-audio
-```
+#### POST /api/sessions/:id/start
-**Request Body:**
-```json
-{
- "chatId": "[email protected]",
- "audio": {
- "url": "https://example.com/audio.mp3"
- },
- "ptt": true
-}
-```
+Start a session and initialize the WhatsApp connection.
-| Field | Type | Description |
-|-------|------|-------------|
-| `ptt` | boolean | Send as voice note (push-to-talk) |
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
----
+**Path parameters**
-#### Send Document
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
-```http
-POST /api/sessions/:sessionId/messages/send-document
-```
+No request body.
+
+**Response** `201`
-**Request Body:**
```json
{
- "chatId": "[email protected]",
- "document": {
- "url": "https://example.com/file.pdf"
- },
- "filename": "report.pdf",
- "caption": "Here is the document"
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
+ "name": "my-bot",
+ "status": "initializing",
+ "phone": null,
+ "pushName": null,
+ "connectedAt": null,
+ "lastActive": null,
+ "createdAt": "2026-06-20T11:30:00.000Z",
+ "updatedAt": "2026-06-25T09:05:00.000Z",
+ "lastError": null
}
```
----
+Returned via `transformSession`. Status typically transitions to `initializing` / `qr_ready`. Note: Swagger declares `200`, but with no `@HttpCode` override the runtime status is **`201`** (NestJS POST default).
-#### Send Location
+**Errors:** `400` session already started / already starting · `401` · `403` · `404` not found
-```http
-POST /api/sessions/:sessionId/messages/send-location
-```
+#### POST /api/sessions/:id/stop
-**Request Body:**
-```json
-{
- "chatId": "[email protected]",
- "latitude": -6.2088,
- "longitude": 106.8456,
- "description": "Jakarta, Indonesia"
-}
-```
+Stop a session and disconnect WhatsApp.
----
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
-#### Send Contact
+**Path parameters**
-```http
-POST /api/sessions/:sessionId/messages/send-contact
-```
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+No request body.
+
+**Response** `201`
-**Request Body:**
```json
{
- "chatId": "[email protected]",
- "contact": {
- "name": "John Doe",
- "phone": "628987654321"
- }
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
+ "name": "my-bot",
+ "status": "disconnected",
+ "phone": "6281234567890",
+ "pushName": "My Bot",
+ "connectedAt": null,
+ "lastActive": "2026-06-25T09:01:55.000Z",
+ "createdAt": "2026-06-20T11:30:00.000Z",
+ "updatedAt": "2026-06-25T09:10:00.000Z",
+ "lastError": null
}
```
----
+Returned via `transformSession`; status typically becomes `disconnected`. Swagger declares `200`; runtime status is **`201`**.
-#### Send Bulk Messages
+**Errors:** `401` · `403` · `404` not found
-Send messages to multiple recipients in a single request. The system processes them asynchronously with delays between messages to reduce ban risk.
+#### POST /api/sessions/:id/force-kill
-```mermaid
-flowchart LR
- A[Client] -->|POST| B[/messages/send-bulk]
- B --> C[Validate]
- C --> D[Create Batch Job]
- D --> E[Queue Messages]
- E --> F[Process with Delay]
- F --> G[Batch ID Response]
-```
+Force-kill a stuck session (SIGKILL the wedged engine, then tear it down).
-```http
-POST /api/sessions/:sessionId/messages/send-bulk
-```
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
-**Request Body:**
-```json
-{
- "batchId": "batch_custom_123",
- "messages": [
- {
- "chatId": "[email protected]",
- "type": "text",
- "content": {
- "text": "Hello {{name}}!"
- },
- "variables": {
- "name": "John"
- }
- },
- {
- "chatId": "[email protected]",
- "type": "image",
- "content": {
- "image": { "url": "https://example.com/promo.jpg" },
- "caption": "Special offer for {{name}}!"
- },
- "variables": {
- "name": "Jane"
- }
- }
- ],
- "options": {
- "delayBetweenMessages": 5000,
- "randomizeDelay": true,
- "stopOnError": false
- }
-}
-```
+**Path parameters**
-**Request Fields:**
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| `batchId` | string | No | Custom batch ID (auto-generated if not provided) |
-| `messages` | array | Yes | Array of messages (max 100 per request) |
-| `messages[].chatId` | string | Yes | Recipient chat ID |
-| `messages[].type` | string | Yes | Message type: `text`, `image`, `video`, `audio`, `document` |
-| `messages[].content` | object | Yes | Message content based on type |
-| `messages[].variables` | object | No | Variables substituted into `content` strings. Use canonical `{{name}}` placeholders (consistent with message templates); the legacy single-brace `{name}` is deprecated but still honored. Unknown placeholders are left literal. |
-| `options.delayBetweenMessages` | number | No | Delay in ms (default: 3000, min: 1000) |
-| `options.randomizeDelay` | boolean | No | Add random 0-2s to delay (default: true) |
-| `options.stopOnError` | boolean | No | Stop batch on first error (default: false) |
+No request body.
+
+**Response** `201`
-**Response (202 Accepted):**
```json
{
- "batchId": "batch_abc123xyz",
- "status": "processing",
- "totalMessages": 2,
- "estimatedCompletionTime": "2025-02-02T10:05:00.000Z",
- "statusUrl": "/api/sessions/sess_abc123/messages/batch/batch_abc123xyz"
+ "id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",
+ "name": "my-bot",
+ "status": "disconnected",
+ "phone": "6281234567890",
+ "pushName": "My Bot",
+ "connectedAt": null,
+ "lastActive": "2026-06-25T09:01:55.000Z",
+ "createdAt": "2026-06-20T11:30:00.000Z",
+ "updatedAt": "2026-06-25T09:12:00.000Z",
+ "lastError": null
}
```
----
-
-#### Get Batch Status
+Returned via `transformSession`. Swagger declares `200`; runtime status is **`201`**.
-```http
-GET /api/sessions/:sessionId/messages/batch/:batchId
-```
+**Errors:** `401` · `403` · `404` not found
-**Response (200 OK):**
-```json
-{
- "batchId": "batch_abc123xyz",
- "status": "completed",
- "progress": {
- "total": 100,
- "sent": 95,
- "failed": 5,
- "pending": 0
- },
- "results": [
- {
- "chatId": "[email protected]",
- "status": "sent",
- "messageId": "[email protected]_3EB0ABC123"
- },
- {
- "chatId": "[email protected]",
- "status": "failed",
- "error": {
- "code": "MESSAGE_NUMBER_NOT_ON_WHATSAPP",
- "message": "Number not registered on WhatsApp"
- }
- }
- ],
- "startedAt": "2025-02-02T10:00:00.000Z",
- "completedAt": "2025-02-02T10:08:30.000Z"
-}
-```
+#### POST /api/sessions/:id/pairing-code
----
+Request an 8-char pairing code to link via phone number (alternative to QR).
-#### Cancel Batch
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
-```http
-POST /api/sessions/:sessionId/messages/batch/:batchId/cancel
-```
+**Path parameters**
-**Response (200 OK):**
-```json
-{
- "batchId": "batch_abc123xyz",
- "status": "cancelled",
- "progress": {
- "total": 100,
- "sent": 45,
- "failed": 2,
- "cancelled": 53
- }
-}
-```
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
----
+**Request body** — `RequestPairingCodeDto`
-#### Get Messages
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `phoneNumber` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[0-9]{6,15}$/)` (digits only, 6–15, no `+`/spaces/dashes) | International format: country code + number, e.g. `628123456789` |
-```http
-GET /api/sessions/:sessionId/chats/:chatId/messages
+```json
+{ "phoneNumber": "628123456789" }
```
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `limit` | number | Number of messages (default: 50) |
-| `before` | string | Get messages before this ID |
+**Response** `201` — `PairingCodeResponseDto`
-**Response (200 OK):**
```json
-[
- {
- "id": "[email protected]_3EB0ABC123",
- "from": "[email protected]",
- "body": "Hello!",
- "type": "text",
- "waTimestamp": 1706868000,
- "timestamp": "2025-02-02T10:00:00.000Z",
- "fromMe": false,
- "hasMedia": false
- }
-]
+{ "pairingCode": "ABCD1234", "status": "qr_ready" }
```
----
+`status` is the lowercase session status.
-#### Send Template Message
+**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found
-Render a stored text template and send it as a regular text message. The
-template body (and optional header/footer) is rendered server-side by
-substituting `{{placeholder}}` tokens with the supplied `vars`. Rendering
-reuses the standard `send-text` path, so plugin hooks, message persistence, and
-delivery-status tracking behave identically to a direct text send.
+#### POST /api/sessions/:id/chats/read
-> **Scope (issue #69):** Only **Option B** — server-side text templates with
-> variable substitution — is supported. Interactive templates (buttons, list
-> messages, WhatsApp Business HSM / approved message templates) are **Option A**
-> and are **not supported** on any of the current engines (`whatsapp-web.js` or `baileys`).
+Mark a chat as read/seen.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Request body** — `MarkChatReadDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) |
+
+```json
+{ "chatId": "[email protected]" }
+```
+
+**Response** `201`
+
+```json
+{ "success": true }
+```
+
+Swagger declares `200`; runtime status is **`201`**.
+
+**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found
+
+#### POST /api/sessions/:id/chats/unread
+
+Mark a chat as unread.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Request body** — `MarkChatReadDto` (reused)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` | Engine-native JID, e.g. `[email protected]` |
+
+```json
+{ "chatId": "[email protected]" }
+```
+
+**Response** `201`
+
+```json
+{ "success": true }
+```
+
+Swagger declares `200`; runtime status is **`201`**.
+
+**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found
+
+#### POST /api/sessions/:id/chats/delete
+
+Delete a chat from the chat list (e.g. a group you have left).
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Request body** — `DeleteChatDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` |
+
+```json
+{ "chatId": "[email protected]" }
+```
+
+**Response** `201`
+
+```json
+{ "success": true }
+```
+
+Swagger declares `200`; runtime status is **`201`**.
+
+**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found
+
+#### POST /api/sessions/:id/chats/typing
+
+Send a typing/recording presence indicator to a chat (or clear it with `paused`).
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Request body** — `SendChatStateDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty` (no JID regex; engine-neutral, the adapter validates) | Engine-native chat id, e.g. `[email protected]` |
+| `state` | `typing` \| `recording` \| `paused` | Yes | `@IsIn(['typing','recording','paused'])` | `typing`/`recording` show the indicator; `paused` clears it |
+
+```json
+{ "chatId": "[email protected]", "state": "typing" }
+```
+
+**Response** `201`
+
+```json
+{ "success": true }
+```
+
+Always returns `{ "success": true }` (the service returns void; the controller hardcodes `true`). Swagger declares `200`; runtime status is **`201`**.
+
+**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found
+
+#### DELETE /api/sessions/:id
+
+Delete a session.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+
+**Response** `204` — empty body (`@HttpCode(204)`, returns void). A `findOne` lookup runs first, so a missing id yields `404`.
+
+**Errors:** `401` missing/invalid key, or key not scoped to this session · `403` key role below OPERATOR · `404` session not found
+
+### 6.4.2 Messages
+
+All routes are mounted under `/api/sessions/:sessionId/messages`. Reads (`GET` history, batch status, reactions) accept any valid API key (including VIEWER). All write/send routes require **API key (OPERATOR)** or higher. Send routes return `MessageResponseDto { messageId, timestamp }` (`timestamp` is an epoch **number** in seconds; there is no `status` field). The global ValidationPipe runs `whitelist` + `forbidNonWhitelisted`, so any body field not listed below is rejected with `400`.
+
+#### GET /api/sessions/:sessionId/messages
+
+Get persisted message history for a session from the local DB (paginated, filterable). Reads the DB only — does not hit WhatsApp.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |
+| from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. |
+| limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. |
+| offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |
+
+**Response** `200`
+
+```json
+{
+ "messages": [
+ {
+ "id": "9f1c2e7a-2b3d-4c5e-8a91-0d1e2f3a4b5c",
+ "sessionId": "my-session",
+ "waMessageId": "[email protected]_3EB0ABCD",
+ "chatId": "[email protected]",
+ "from": "[email protected]",
+ "body": "Hello from OpenWA!",
+ "type": "text",
+ "direction": "outgoing",
+ "timestamp": 1719312000,
+ "metadata": null,
+ "status": "sent",
+ "createdAt": "2026-06-25T09:20:00.000Z"
+ }
+ ],
+ "total": 1
+}
+```
+
+Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. Ordered by `createdAt` DESC. The response is the raw service object (no envelope).
+
+**Errors:** `401` missing/invalid API key
+
+#### GET /api/sessions/:sessionId/messages/:chatId/history
+
+Fetch chat history live from WhatsApp for a chat, bypassing the local DB.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| chatId | string | Chat ID, e.g. `[email protected]` or `[email protected]` |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| limit | integer | No | 50 | Clamped to `[1,100]`; when `deep=true` the ceiling rises to 2000. Non-finite falls back to 50. |
+| includeMedia | boolean | No | false | Truthy only for `true` or `1`. Downloads base64 media (slower). Forced OFF when `deep=true`. |
+| deep | boolean | No | false | Truthy only for `true` or `1`. Raises the limit ceiling 100→2000 (whatsapp-web.js only) and forces metadata-only. |
+
+**Response** `200`
+
+Returns a bare array of engine-neutral `IncomingMessage` objects:
+
+```json
+[
+ {
+ "id": "[email protected]_3EB0ABCD",
+ "from": "[email protected]",
+ "chatId": "[email protected]",
+ "body": "Hi there",
+ "type": "text",
+ "timestamp": 1719312000,
+ "fromMe": false,
+ "isGroup": false,
+ "author": "[email protected]",
+ "senderPhone": "628123456789"
+ }
+]
+```
+
+Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, and `location { latitude, longitude, description?, address?, url? }`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|revoked|unknown`.
+
+**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error
+
+#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/reactions
+
+Get reactions for a specific message, grouped by emoji with the senders.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| chatId | string | Chat ID containing the message |
+| messageId | string | Message ID to get reactions for |
+
+**Response** `200`
+
+Returns a bare array of `MessageReaction`:
+
+```json
+[
+ {
+ "emoji": "👍",
+ "senders": [
+ { "senderId": "[email protected]", "emoji": "👍", "timestamp": 1719312050 }
+ ]
+ }
+]
+```
+
+**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error
+
+#### GET /api/sessions/:sessionId/messages/batch/:batchId
+
+Get the processing status and progress of a bulk batch.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| batchId | string | Batch ID |
+
+**Response** `200`
+
+```json
+{
+ "batchId": "batch_a1b2c3d4",
+ "status": "processing",
+ "progress": { "total": 2, "sent": 1, "failed": 0, "pending": 1, "cancelled": 0 },
+ "results": [
+ {
+ "chatId": "[email protected]",
+ "status": "sent",
+ "messageId": "[email protected]_3EB0ABCD",
+ "sentAt": "2026-06-25T09:21:00.000Z"
+ },
+ { "chatId": "[email protected]", "status": "pending" }
+ ],
+ "startedAt": "2026-06-25T09:20:55.000Z",
+ "completedAt": null
+}
+```
+
+`status` is one of `pending|processing|completed|cancelled|failed`; per-result `status` is `pending|sent|failed|cancelled`. A failed result carries a sanitized `error { code, message }` (internals are not leaked).
+
+**Errors:** `401` missing/invalid API key · `404` batch not found for this session
+
+#### POST /api/sessions/:sessionId/messages/send-text
+
+Send a plain text message.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendTextMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | `[email protected]` or `[email protected]` |
+| text | string | Yes | non-empty, max 4096 | Message text |
+
+```json
+{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+`messageId` is the WhatsApp message id from the engine. An optional `SIMULATE_TYPING` humanising pause may run before send.
+
+**Errors:** `400` unknown body field, validation failure, or session not active / blocked by a plugin hook · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session not found · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-template
+
+Render a stored text template (header/body/footer joined by blank lines, `{{vars}}` substituted) and send it as text.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendTemplateMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| templateId | string | Conditional | non-empty; required when `templateName` is absent | Stored template id |
+| templateName | string | Conditional | non-empty; required when `templateId` is absent | Stored template name |
+| vars | Record\<string,string\> | No | object | Substituted into `{{placeholder}}` tokens; defaults to `{}` |
+
+```json
+{
+ "chatId": "[email protected]",
+ "templateName": "order-confirmation",
+ "vars": { "customer": "Alice", "orderId": "1234" }
+}
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+Delegates to the send-text path after rendering.
+
+**Errors:** `400` unknown body field, validation failure, or session not active · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session or template not found · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-image
+
+Send an image (by URL or base64) with an optional caption.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendMediaMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| url | string | Conditional | URL; required when `base64` is absent | http/https media URL (SSRF-guarded; a blocked internal URL maps to `400`) |
+| base64 | string | Conditional | string; required when `url` is absent | Base64 media data (capped to the media byte limit) |
+| mimetype | string | Conditional | string; required when using `base64` | MIME type of the media |
+| filename | string | No | max 255 | File name |
+| caption | string | No | max 1024 | Caption text |
+
+```json
+{ "chatId": "[email protected]", "url": "https://example.com/image.jpg", "caption": "Check out this image!" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` neither `url` nor `base64`, base64 without `mimetype`, base64 over media cap, SSRF-blocked URL, session not active, or unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-video
+
+Send a video (by URL or base64) with an optional caption. Uses the same `SendMediaMessageDto` (and the same validation rules and errors) as `send-image`.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendMediaMessageDto` (fields `chatId`, `url`, `base64`, `mimetype`, `filename`, `caption` — see `send-image`)
+
+```json
+{ "chatId": "[email protected]", "url": "https://example.com/clip.mp4", "caption": "video" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-audio
+
+Send an audio/voice message (by URL or base64). Uses `SendMediaMessageDto`. A `caption` is accepted by the DTO but not persisted for audio.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendMediaMessageDto` (fields `chatId`, `url`, `base64`, `mimetype`, `filename`, `caption` — see `send-image`)
+
+```json
+{ "chatId": "[email protected]", "url": "https://example.com/voice.ogg", "mimetype": "audio/ogg" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-document
+
+Send a document/file (by URL or base64). Uses `SendMediaMessageDto`; `filename` is used as the persisted body fallback.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendMediaMessageDto` (fields `chatId`, `url`, `base64`, `mimetype`, `filename`, `caption` — see `send-image`)
+
+```json
+{ "chatId": "[email protected]", "url": "https://example.com/report.pdf", "filename": "report.pdf", "mimetype": "application/pdf" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-location
+
+Send a location pin.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendLocationDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| latitude | number | Yes | valid latitude | Latitude (out-of-range → `400`) |
+| longitude | number | Yes | valid longitude | Longitude (out-of-range → `400`) |
+| description | string | No | string | Pin description |
+| address | string | No | string | Pin address |
+
+```json
+{ "chatId": "[email protected]", "latitude": -6.2088, "longitude": 106.8456, "description": "Jakarta", "address": "Central Jakarta" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` invalid coords / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-contact
+
+Send a contact card (vCard).
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendContactDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| contactName | string | Yes | non-empty | Display name for the contact card |
+| contactNumber | string | Yes | non-empty | Contact phone number |
+
+```json
+{ "chatId": "[email protected]", "contactName": "John Doe", "contactNumber": "628987654321" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-sticker
+
+Send a sticker (by URL or base64; typically webp). Reuses `SendMediaMessageDto`.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendMediaMessageDto` (fields `chatId`, `url`, `base64`, `mimetype`, `filename`, `caption` — see `send-image`)
+
+```json
+{ "chatId": "[email protected]", "url": "https://example.com/sticker.webp", "mimetype": "image/webp" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }
+```
+
+**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/reply
+
+Reply to a message, quoting a prior message.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `ReplyMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| quotedMessageId | string | Yes | non-empty | WhatsApp id of the message being quoted |
+| text | string | Yes | non-empty | Reply text |
+
+```json
+{ "chatId": "[email protected]", "quotedMessageId": "[email protected]_3EB0ABCD", "text": "Replying to you" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0EFGH", "timestamp": 1719312100 }
+```
+
+The quoted body is best-effort resolved from the DB for the reply preview.
+
+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/forward
+
+Forward a message from one chat to another.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `ForwardMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| fromChatId | string | Yes | non-empty | Source chat |
+| toChatId | string | Yes | non-empty | Destination chat |
+| messageId | string | Yes | non-empty | WhatsApp id of the message to forward |
+
+```json
+{ "fromChatId": "[email protected]", "toChatId": "[email protected]", "messageId": "[email protected]_3EB0XYZ" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "[email protected]_3EB0NEW", "timestamp": 1719312200 }
+```
+
+`messageId` may be an empty string when the engine could not recover the forwarded copy's id.
+
+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/react
+
+Add or remove a reaction to a message (an empty emoji removes the reaction).
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `ReactMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| messageId | string | Yes | non-empty | Message to react to |
+| emoji | string | Yes | string (may be empty) | Reaction emoji; an empty string removes the reaction. The field must be present. |
+
+```json
+{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "emoji": "👍" }
+```
+
+**Response** `200`
+
+The controller hardcodes the result after the engine call. Note the `200` status (via `@HttpCode`), not `201`.
+
+```json
+{ "success": true }
+```
+
+**Errors:** `400` session not active / message not found / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/delete
+
+Delete a message (for everyone by default); also flags the stored record as `revoked`.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `DeleteMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| chatId | string | Yes | non-empty | Target chat |
+| messageId | string | Yes | non-empty | Message to delete |
+| forEveryone | boolean | No | boolean (default `true`) | Delete for everyone; defaults to `true` in the service |
+
+```json
+{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "forEveryone": true }
+```
+
+**Response** `200`
+
+After the engine delete, the stored message body is cleared and its `type` set to `revoked`. Note the `200` status (via `@HttpCode`).
+
+```json
+{ "success": true }
+```
+
+**Errors:** `400` session not active / message not found / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-bulk
+
+Send messages to multiple recipients as an async batch — returns immediately and processes in the background.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `SendBulkMessageDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| batchId | string | No | string | Auto-generated `batch_<hex>` if omitted; a duplicate id returns `400` |
+| messages | BulkMessageItemDto[] | Yes | array, max 100, nested-validated | The batch items (see below) |
+| options | BulkMessageOptionsDto | No | nested-validated | Pacing/error options (see below) |
+
+Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename? }`, `caption?: string`.
+
+`BulkMessageOptionsDto`: `{ delayBetweenMessages?: number (1000–60000, default 3000), randomizeDelay?: boolean (default true), stopOnError?: boolean (default false) }`.
+
+```json
+{
+ "messages": [
+ { "chatId": "[email protected]", "type": "text", "content": { "text": "Hi {{name}}" }, "variables": { "name": "Alice" } },
+ { "chatId": "[email protected]", "type": "image", "content": { "image": { "url": "https://example.com/promo.jpg" }, "caption": "Promo" } }
+ ],
+ "options": { "delayBetweenMessages": 3000, "randomizeDelay": true, "stopOnError": false }
+}
+```
+
+**Response** `202`
+
+`202 Accepted` (via `@HttpCode`). `statusUrl` points at the batch-status route below.
+
+```json
+{
+ "batchId": "batch_a1b2c3d4",
+ "status": "pending",
+ "totalMessages": 2,
+ "estimatedCompletionTime": "2026-06-25T09:21:00.000Z",
+ "statusUrl": "/api/sessions/my-session/messages/batch/batch_a1b2c3d4"
+}
+```
+
+**Errors:** `400` session not active, duplicate `batchId`, base64 over media cap, or DTO/nested validation failure (unknown nested field rejected) · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/batch/:batchId/cancel
+
+Cancel a running (pending/processing) bulk batch. No request body.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| batchId | string | Batch ID |
+
+**Response** `200`
+
+`200` via `@HttpCode`. On cancel, the remaining pending count is moved to `cancelled`.
+
+```json
+{
+ "batchId": "batch_a1b2c3d4",
+ "status": "cancelled",
+ "progress": { "total": 2, "sent": 1, "failed": 0, "pending": 0, "cancelled": 1 }
+}
+```
+
+**Errors:** `400` batch already completed or cancelled · `401` missing/invalid API key · `403` key role below OPERATOR · `404` batch not found
+
+### 6.4.3 Contacts
+
+Contact endpoints are scoped under a session: `/api/sessions/:sessionId/contacts`. All read routes require a valid API key; the block/unblock writes require an `OPERATOR` key. Every route returns `400 "Session is not started"` when the target session exists but is not in a started/ready state, and `404` when the session itself does not exist. Responses are the raw handler payload (no envelope).
+
+The `Contact` object returned by the list and get-by-id routes has this shape:
+
+```json
+{
+ "name": "Jane Doe",
+ "pushName": "Jane",
+ "number": "6281234567890",
+ "isMyContact": true,
+ "isBlocked": false,
+ "profilePicUrl": "https://pps.whatsapp.net/v/..."
+}
+```
+
+`name`, `pushName`, and `profilePicUrl` are optional and may be absent.
+
+#### GET /api/sessions/:sessionId/contacts
+
+List all contacts for a session, returned as an in-memory paginated window.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| limit | integer | No | 1000 | Parsed with `parseInt(…,10)`; clamped to `[1, 1000]`. Omitted or non-finite values fall back to 1000. |
+| offset | integer | No | 0 | Parsed with `parseInt(…,10)`; non-finite values fall back to 0, then truncated to `>= 0`. |
+
+**Response** `200` — bare `Contact[]` array
+
+```json
+[
+ {
+ "name": "Jane Doe",
+ "pushName": "Jane",
+ "number": "6281234567890",
+ "isMyContact": true,
+ "isBlocked": false,
+ "profilePicUrl": "https://pps.whatsapp.net/v/..."
+ }
+]
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `404` session not found
+
+#### GET /api/sessions/:sessionId/contacts/check/:number
+
+Check whether a phone number exists on WhatsApp and return its canonical WhatsApp id when it does.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| number | string | Phone number to check, e.g. `628123456789` (digits, no `@c.us` suffix). |
+
+**Response** `200`
+
+```json
+{
+ "number": "628123456789",
+ "exists": true,
+ "whatsappId": "[email protected]"
+}
+```
+
+`whatsappId` is the canonical native chat id, or `null` when the number is not on WhatsApp; `exists` is `whatsappId !== null`.
+
+> Route-order caveat: the literal `check/` segment disambiguates this route from `GET /:contactId`. A contact whose id is literally `check` would be shadowed by this handler.
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+
+#### GET /api/sessions/:sessionId/contacts/:contactId
+
+Get a single contact by its WhatsApp id.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| contactId | string | Contact id / JID, e.g. `[email protected]` or an `@lid`. |
+
+**Response** `200` — `Contact`
+
+```json
+{
+ "name": "Jane Doe",
+ "pushName": "Jane",
+ "number": "6281234567890",
+ "isMyContact": true,
+ "isBlocked": false,
+ "profilePicUrl": "https://pps.whatsapp.net/v/..."
+}
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Contact <id> not found` (engine returned null), or session not found
+
+#### GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
+
+Get the profile picture URL for a contact (best-effort).
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| contactId | string | Contact id / JID, e.g. `[email protected]`. |
+
+**Response** `200`
+
+```json
+{ "url": "https://pps.whatsapp.net/v/..." }
+```
+
+`url` is `null` when there is no picture, the contact's privacy hides it, or it cannot be resolved.
+
+> The path segment is `profile-picture` (hyphenated), not `profile-pic`.
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+
+#### GET /api/sessions/:sessionId/contacts/:contactId/phone
+
+Resolve a contact id (e.g. an `@lid`) to a phone number (MSISDN digits), best-effort.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| contactId | string | Contact id / JID to resolve, e.g. an `@lid`. |
+
+**Response** `200`
+
+```json
+{ "contactId": "12345678901234@lid", "phone": "6281234567890" }
+```
+
+`phone` is `null` when the engine cannot map the id (e.g. an `@lid` the account has never seen).
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+
+#### POST /api/sessions/:sessionId/contacts/:contactId/block
+
+Block a contact.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| contactId | string | Contact id / JID, e.g. `[email protected]`. |
+
+This route takes no request body and binds no DTO. Send an empty body `{}` (the global `whitelist` + `forbidNonWhitelisted` ValidationPipe rejects any unexpected field with `400`).
+
+**Response** `200`
+
+This route is annotated `@HttpCode(200)`, so it returns `200` rather than the POST default `201`.
+
+```json
+{ "success": true, "message": "Contact blocked" }
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session not found
+
+#### DELETE /api/sessions/:sessionId/contacts/:contactId/block
+
+Unblock a contact.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| contactId | string | Contact id / JID, e.g. `[email protected]`. |
+
+No request body.
+
+**Response** `200`
+
+No `@HttpCode` override is present, so this DELETE returns the NestJS default `200` (not `204`).
+
+```json
+{ "success": true, "message": "Contact unblocked" }
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session not found
+
+### 6.4.4 Groups
+
+All group routes are nested under a session: base path `/api/sessions/:sessionId/groups`. Reads (`GET`) require a plain API key; writes (create/modify/leave/revoke) require an `OPERATOR` role key. All routes resolve the engine for the session first, so a session that is not started yields `400 Session is not started`.
+
+#### GET /api/sessions/:sessionId/groups
+
+List all groups for a session, with pagination.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| limit | string (parsed base-10 to number) | No | 1000 | Max groups to return; clamped to [1, 1000]. Omitted/non-finite → 1000. |
+| offset | string (parsed base-10 to number) | No | 0 | Groups to skip. Non-finite → 0; negative truncated to 0. |
+
+**Response** `200`
+
+Raw array (no envelope). The service calls `engine.getGroups()` then paginates to bound the window.
+
+```json
+[
+ {
+ "name": "Project Team",
+ "participantsCount": 12,
+ "isAdmin": true,
+ "linkedParentJID": null
+ }
+]
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key`
+
+#### GET /api/sessions/:sessionId/groups/:groupId
+
+Get detailed group info including participants.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID, e.g. `[email protected]` |
+
+**Response** `200`
+
+Raw object (no envelope). `engine.getGroupInfo()` returns `GroupInfo | null`; the service throws `404` when it is `null`.
+
+```json
+{
+ "name": "Project Team",
+ "description": "Internal coordination group.",
+ "owner": "[email protected]",
+ "createdAt": 1718900000,
+ "isReadOnly": false,
+ "isAnnounce": false,
+ "linkedParentJID": null,
+ "participants": [
+ {
+ "number": "628123456789",
+ "name": "Alice",
+ "isAdmin": true,
+ "isSuperAdmin": true
+ }
+ ]
+}
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `404` `Group <groupId> not found`
+
+#### GET /api/sessions/:sessionId/groups/:groupId/invite-code
+
+Get the group invite code and full invite link.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Response** `200`
+
+`inviteCode` comes from `engine.getGroupInviteCode()`; `inviteLink` is `https://chat.whatsapp.com/<inviteCode>`.
+
+```json
+{
+ "inviteCode": "AbCdEf123456",
+ "inviteLink": "https://chat.whatsapp.com/AbCdEf123456"
+}
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key`
+
+#### POST /api/sessions/:sessionId/groups
+
+Create a new group with an initial set of participants.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Request body** — `CreateGroupDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| name | string | Yes | `@IsString`, `@IsNotEmpty` | Group subject/name |
+| participants | string[] | Yes | `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Non-empty array of WhatsApp IDs, e.g. `[email protected]` |
+
+```json
+{
+ "name": "Project Team",
+ "participants": ["[email protected]", "[email protected]"]
+}
+```
+
+**Response** `201`
+
+Returns the created `Group` directly (raw).
+
+```json
+{
+ "name": "Project Team",
+ "participantsCount": 3,
+ "isAdmin": true,
+ "linkedParentJID": null
+}
+```
+
+**Errors:** `400` validation (missing/empty `name` or `participants`, or any non-DTO field) / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### POST /api/sessions/:sessionId/groups/:groupId/participants
+
+Add participants to a group.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `ParticipantsDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| participants | string[] | Yes | `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Non-empty array of WhatsApp IDs |
+
+```json
+{ "participants": ["[email protected]"] }
+```
+
+**Response** `200`
+
+Status is forced to `200` via `@HttpCode(HttpStatus.OK)` (overriding the POST default). The body is a fixed acknowledgement after the void engine call.
+
+```json
+{ "success": true, "message": "Participants added" }
+```
+
+**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### DELETE /api/sessions/:sessionId/groups/:groupId/participants
+
+Remove participants from a group. Note: this DELETE carries a JSON request body.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `ParticipantsDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| participants | string[] | Yes | `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Non-empty array of WhatsApp IDs |
+
+```json
+{ "participants": ["[email protected]"] }
+```
+
+**Response** `200`
+
+No `@HttpCode`, so NestJS uses the DELETE default of `200`.
+
+```json
+{ "success": true, "message": "Participants removed" }
+```
+
+**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### POST /api/sessions/:sessionId/groups/:groupId/participants/promote
+
+Promote participants to group admin.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `ParticipantsDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| participants | string[] | Yes | `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Non-empty array of WhatsApp IDs |
+
+```json
+{ "participants": ["[email protected]"] }
+```
+
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+
+```json
+{ "success": true, "message": "Participants promoted to admin" }
+```
+
+**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### POST /api/sessions/:sessionId/groups/:groupId/participants/demote
+
+Demote participants from group admin.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `ParticipantsDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| participants | string[] | Yes | `@IsArray`, `@ArrayNotEmpty`, `@IsString({each:true})` | Non-empty array of WhatsApp IDs |
+
+```json
+{ "participants": ["[email protected]"] }
+```
+
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+
+```json
+{ "success": true, "message": "Participants demoted from admin" }
+```
+
+**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### PUT /api/sessions/:sessionId/groups/:groupId/subject
+
+Change the group name/subject.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `GroupSubjectDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| subject | string | Yes | `@IsString`, `@IsNotEmpty` | New group subject/name |
+
+```json
+{ "subject": "New Team Name" }
+```
+
+**Response** `200`
+
+No `@HttpCode`; PUT default is `200`.
+
+```json
+{ "success": true, "message": "Group subject updated" }
+```
+
+**Errors:** `400` validation (empty `subject`) / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### PUT /api/sessions/:sessionId/groups/:groupId/description
+
+Change the group description. An empty string clears the description.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — `GroupDescriptionDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| description | string | Yes | `@IsString` (no `@IsNotEmpty`) | Must be present and a string, but `""` is valid and clears the description |
+
+```json
+{ "description": "Internal coordination group." }
+```
+
+**Response** `200`
+
+No `@HttpCode`; PUT default is `200`.
+
+```json
+{ "success": true, "message": "Group description updated" }
+```
+
+**Errors:** `400` validation (`description` missing / not a string) / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### POST /api/sessions/:sessionId/groups/:groupId/leave
+
+Leave a group.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — none (send an empty body).
+
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+
+```json
+{ "success": true, "message": "Left the group" }
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+#### POST /api/sessions/:sessionId/groups/:groupId/invite-code/revoke
+
+Revoke the current invite code and generate a new one.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID |
+
+**Request body** — none (send an empty body).
+
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+
+`inviteCode` is the **new** code from `engine.revokeGroupInviteCode()`; `inviteLink` is `https://chat.whatsapp.com/<newCode>`.
+
+```json
+{
+ "inviteCode": "XyZ987654321",
+ "inviteLink": "https://chat.whatsapp.com/XyZ987654321",
+ "message": "Invite code revoked and new one generated"
+}
+```
+
+**Errors:** `400` session is not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
+
+### 6.4.5 Message Templates
+
+Reusable message templates scoped to a session, with `{{variable}}` placeholders rendered at send time. All routes are nested under `/api/sessions/:sessionId/templates` and require an **OPERATOR** key. The `sessionId` is stored on the template but is **not** validated against an existing session in these handlers.
+
+#### GET /api/sessions/:sessionId/templates
+
+List all templates for a session, newest first.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID; filters templates by `sessionId`. |
+
+**Response** `200`
+
+Bare `Template[]` array (no pagination, no envelope). Ordered by `createdAt` DESC. Returns an empty array — not `404` — when the session has no templates.
+
+```json
+[
+ {
+ "id": "f1c2a3b4-5d6e-7f80-9a1b-2c3d4e5f6071",
+ "sessionId": "9b1c0e2a-3d4f-5a6b-7c8d-9e0f1a2b3c4d",
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe.",
+ "createdAt": "2026-06-25T10:15:00.000Z",
+ "updatedAt": "2026-06-25T10:15:00.000Z"
+ }
+]
+```
+
+**Errors:** `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role
+
+#### GET /api/sessions/:sessionId/templates/:id
+
+Get a single template by ID within the session.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID; combined with `id` in the lookup. |
+| id | string | Template UUID. |
+
+**Response** `200`
+
+Raw `Template` entity (no envelope).
+
+```json
+{
+ "id": "f1c2a3b4-5d6e-7f80-9a1b-2c3d4e5f6071",
+ "sessionId": "9b1c0e2a-3d4f-5a6b-7c8d-9e0f1a2b3c4d",
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe.",
+ "createdAt": "2026-06-25T10:15:00.000Z",
+ "updatedAt": "2026-06-25T10:15:00.000Z"
+}
+```
+
+**Errors:** `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `404` no row matches the `id`+`sessionId` pair (`{ "statusCode": 404, "message": "Template with id '<id>' not found", "error": "Not Found" }`)
+
+#### POST /api/sessions/:sessionId/templates
+
+Create a message template for the session (with `{{variable}}` placeholders in the body).
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID; stored as `template.sessionId`. Not validated against an existing session in this handler. |
+
+**Request body** — `CreateTemplateDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| name | string | yes | non-empty, max 100 chars | Unique template name within the session (DB unique index on `[sessionId, name]`). Duplicate → `409`. |
+| body | string | yes | non-empty, max 4096 chars | Template body containing `{{variable}}` placeholders rendered at send time. |
+| header | string | no | max 1024 chars | Optional header text; coerced to `null` when omitted. Prepended to rendered body. |
+| footer | string | no | max 1024 chars | Optional footer text; coerced to `null` when omitted. Appended to rendered body. |
+
+```json
+{
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe."
+}
+```
+
+**Response** `201`
+
+Returns the saved `Template` entity raw (no envelope). The lazy `session` relation is not loaded on a freshly saved entity, so it is absent from the JSON.
+
+```json
+{
+ "id": "f1c2a3b4-5d6e-7f80-9a1b-2c3d4e5f6071",
+ "sessionId": "9b1c0e2a-3d4f-5a6b-7c8d-9e0f1a2b3c4d",
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe.",
+ "createdAt": "2026-06-25T10:15:00.000Z",
+ "updatedAt": "2026-06-25T10:15:00.000Z"
+}
+```
+
+**Errors:** `400` validation failure (missing/empty `name`/`body`, over-length, or any extra field rejected by `forbidNonWhitelisted`) · `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `409` duplicate `name` for the session
+
+#### PUT /api/sessions/:sessionId/templates/:id
+
+Update a template's name/body/header/footer (partial; only provided fields change).
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| id | string | Template UUID to update. |
+
+**Request body** — `UpdateTemplateDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| name | string | no | if present: non-empty, max 100 chars | Applied only when not `undefined`. Duplicate name → `409`. |
+| body | string | no | if present: non-empty, max 4096 chars | Applied only when not `undefined`. |
+| header | string | no | max 1024 chars | Applied only when not `undefined`. The update path does **not** coerce to `null`, so passing explicit `null` fails `@IsString`; omit the key to leave it unchanged. |
+| footer | string | no | max 1024 chars | Applied only when not `undefined`. |
+
+```json
+{
+ "body": "Hi {{customer}}, your order {{orderId}} is out for delivery.",
+ "footer": "Thanks for shopping with us."
+}
+```
+
+**Response** `200`
+
+Loads via lookup (`404` if missing), patches the provided fields, saves, and returns the updated entity raw. `updatedAt` is refreshed.
+
+```json
+{
+ "id": "f1c2a3b4-5d6e-7f80-9a1b-2c3d4e5f6071",
+ "sessionId": "9b1c0e2a-3d4f-5a6b-7c8d-9e0f1a2b3c4d",
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} is out for delivery.",
+ "header": "OpenWA Store",
+ "footer": "Thanks for shopping with us.",
+ "createdAt": "2026-06-25T10:15:00.000Z",
+ "updatedAt": "2026-06-25T11:02:00.000Z"
+}
+```
+
+**Errors:** `400` validation / `forbidNonWhitelisted` · `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `404` `id`+`sessionId` not found (raised before any write) · `409` rename collides with another template name in the session
+
+#### DELETE /api/sessions/:sessionId/templates/:id
+
+Delete a template by ID.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+| id | string | Template UUID to delete. |
+
+**Response** `204`
+
+No content (empty body). The handler looks the template up first, so a missing template yields `404` rather than a silent `204`.
+
+**Errors:** `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `404` `id`+`sessionId` not found
+
+### 6.4.6 Catalog & Channels
+
+WhatsApp Business catalog browsing/sending and channel (newsletter) operations. Catalog read routes (`/catalog…`) require any valid API key; the two product/catalog **send** routes live under the `/messages` path and require an **OPERATOR** key. Channel read routes require any valid API key; subscribe/unsubscribe require **OPERATOR**.
+
+#### GET /api/sessions/:sessionId/catalog
+
+Get business catalog info for the session's WhatsApp Business account.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. |
+
+**Response** `200`
+
+```json
+{
+ "id": "1234567890123456",
+ "name": "My Storefront",
+ "description": "Best products in town",
+ "productCount": 12,
+ "url": "https://wa.me/c/6281234567890"
+}
+```
+
+Returns `null` when the account has no catalog (catalog is a WhatsApp Business-only feature; non-business accounts may yield `null`). The response is the raw `engine.getCatalog()` return — no envelope.
+
+**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+
+#### GET /api/sessions/:sessionId/catalog/products
+
+List catalog products with pagination.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `page` | integer | No | `1` | Page number. Coerced from string; must be an integer `>= 1` or `400`. |
+| `limit` | integer | No | `20` | Page size. Must be an integer `>= 1`. No upper cap declared on the DTO. |
+
+Validated against `ProductQueryDto` via the global ValidationPipe; any unknown query key is rejected with `400` (forbidNonWhitelisted).
+
+**Response** `200`
+
+```json
+{
+ "products": [
+ {
+ "id": "PROD_12345",
+ "name": "Wireless Earbuds",
+ "description": "Noise-cancelling, 24h battery",
+ "price": 49990,
+ "currency": "IDR",
+ "priceFormatted": "Rp 49.990",
+ "imageUrl": "https://example.com/img/earbuds.jpg",
+ "url": "https://wa.me/p/PROD_12345/6281234567890",
+ "isAvailable": true,
+ "retailerId": "SKU-EB-01"
+ }
+ ],
+ "pagination": { "page": 1, "limit": 20, "total": 1, "totalPages": 1 }
+}
+```
+
+**Errors:** `400` invalid `page`/`limit` or unknown query key · `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+
+#### GET /api/sessions/:sessionId/catalog/products/:productId
+
+Get a specific catalog product by id.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. |
+| `productId` | string | Catalog product id. |
+
+**Response** `200`
+
+```json
+{
+ "id": "PROD_12345",
+ "name": "Wireless Earbuds",
+ "description": "Noise-cancelling, 24h battery",
+ "price": 49990,
+ "currency": "IDR",
+ "priceFormatted": "Rp 49.990",
+ "imageUrl": "https://example.com/img/earbuds.jpg",
+ "url": "https://wa.me/p/PROD_12345/6281234567890",
+ "isAvailable": true,
+ "retailerId": "SKU-EB-01"
+}
+```
+
+An unknown `productId` returns `200` with body `null` — it is **not** a `404`. Only a missing/disconnected session yields `404`.
+
+**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-product
+
+Send a product message (catalog product card) to a chat. Note: this route lives under the `/messages` path but belongs to the catalog module.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. |
+
+**Request body** — `SendProductDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString` | Target chat/recipient id (e.g. `[email protected]`). |
+| `productId` | string | Yes | `@IsString` | Catalog product id to send. |
+| `body` | string | No | `@IsString` | Optional message body/caption. |
+
+```json
+{
+ "chatId": "[email protected]",
+ "productId": "PROD_12345",
+ "body": "Check out this item!"
+}
+```
+
+**Response** `201`
+
+```json
+{ "id": "[email protected]_3EB0...", "timestamp": 1719331200 }
+```
+
+`timestamp` is an epoch number (seconds).
+
+**Errors:** `400` missing `chatId`/`productId`, wrong types, or any field not on the DTO · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `500` engine error
+
+#### POST /api/sessions/:sessionId/messages/send-catalog
+
+Send the business catalog link to a chat. Note: this route lives under the `/messages` path but belongs to the catalog module.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. |
+
+**Request body** — `SendCatalogDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `chatId` | string | Yes | `@IsString` | Target chat/recipient id. |
+| `body` | string | No | `@IsString` | Optional message body/caption. |
+
+```json
+{
+ "chatId": "[email protected]",
+ "body": "Browse our full catalog here"
+}
+```
+
+**Response** `201`
+
+```json
+{ "id": "[email protected]_3EB0...", "timestamp": 1719331200 }
+```
+
+`timestamp` is an epoch number (seconds).
+
+**Errors:** `400` missing/invalid `chatId` or any non-DTO field · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `500` engine error
+
+#### GET /api/sessions/:sessionId/channels
+
+List all channels/newsletters the session is subscribed to.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. The engine must be started or the request fails with `400`. |
+
+**Response** `200`
+
+```json
+[
+ {
+ "id": "120363000000000000@newsletter",
+ "name": "OpenWA Updates",
+ "description": "Release notes and tips",
+ "inviteCode": "ABC123xyz",
+ "subscriberCount": 1042,
+ "picture": "https://example.com/ch.jpg",
+ "verified": true,
+ "createdAt": 1717200000
+ }
+]
+```
+
+Bare array, no envelope.
+
+**Errors:** `400` `Session is not started` · `401` missing/invalid API key
+
+#### GET /api/sessions/:sessionId/channels/:channelId
+
+Get a single channel/newsletter by its id.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. Engine must be started. |
+| `channelId` | string | Channel/newsletter id. |
+
+**Response** `200`
+
+```json
+{
+ "id": "120363000000000000@newsletter",
+ "name": "OpenWA Updates",
+ "description": "Release notes and tips",
+ "inviteCode": "ABC123xyz",
+ "subscriberCount": 1042,
+ "picture": "https://example.com/ch.jpg",
+ "verified": true,
+ "createdAt": 1717200000
+}
+```
+
+**Errors:** `400` `Session is not started` · `401` missing/invalid API key · `404` `Channel <channelId> not found` (engine returned null)
+
+#### GET /api/sessions/:sessionId/channels/:channelId/messages
+
+Get recent messages from a channel/newsletter.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. Engine must be started. |
+| `channelId` | string | Channel/newsletter id. |
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `limit` | number | No | engine default (Swagger notes 50) | Max messages to return. Taken as a raw query string and run through `parseInt(limit, 10)` when present, else `undefined` is passed to the engine. There is **no** DTO/ValidationPipe on this value — a non-numeric `limit` becomes `NaN` and is forwarded to the engine. |
+
+**Response** `200`
+
+```json
+[
+ {
+ "id": "false_120363000000000000@newsletter_3EB0...",
+ "body": "v0.7.3 is out!",
+ "timestamp": 1719331200,
+ "hasMedia": false,
+ "mediaUrl": null
+ }
+]
+```
+
+Bare array. `timestamp` is an epoch number (seconds).
+
+**Errors:** `400` `Session is not started` · `401` missing/invalid API key
+
+#### POST /api/sessions/:sessionId/channels/subscribe
+
+Subscribe to a channel using its invite code.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. Engine must be started. |
+
+**Request body** — `SubscribeChannelDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `inviteCode` | string | Yes | `@IsString` `@IsNotEmpty` | Channel invite code from the channel share link. |
+
+```json
+{ "inviteCode": "ABC123xyz" }
+```
+
+**Response** `201`
+
+```json
+{
+ "id": "120363000000000000@newsletter",
+ "name": "OpenWA Updates",
+ "description": "Release notes and tips",
+ "inviteCode": "ABC123xyz",
+ "subscriberCount": 1042,
+ "picture": "https://example.com/ch.jpg",
+ "verified": true,
+ "createdAt": 1717200000
+}
+```
+
+**Errors:** `400` `Session is not started`, missing/empty `inviteCode`, or any unknown body field · `401` missing/invalid API key · `403` API-key role below OPERATOR
+
+#### DELETE /api/sessions/:sessionId/channels/:channelId
+
+Unsubscribe from a channel.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | WhatsApp session id. Engine must be started. |
+| `channelId` | string | Channel id to unsubscribe from. |
+
+**Response** `200`
+
+```json
+{ "success": true }
+```
+
+Note: this is the one route in the module that returns a literal `{ success: true }` (hard-coded by the controller after the void engine call resolves) rather than the raw engine return. There is no `@HttpCode` override, so it returns `200`, not `204`.
+
+**Errors:** `400` `Session is not started` · `401` missing/invalid API key · `403` API-key role below OPERATOR
+
+### 6.4.7 Labels & Status
+
+Labels are a WhatsApp Business feature: every label route lives under a session and reads/writes the chat-label assignments exposed by the engine. Status routes manage the session's status feed (stories) — reading visible statuses and posting/deleting your own. Read routes require a base API key; all writes require `OPERATOR`.
+
+#### GET /api/sessions/:sessionId/labels
+
+List all labels defined for the session (WhatsApp Business accounts only).
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+
+**Response** `200`
+
+```json
+[
+ { "id": "1", "name": "New customer", "hexColor": "#FF9485" },
+ { "id": "5", "name": "Paid", "hexColor": "#25D366" }
+]
+```
+
+Bare array — raw return of `engine.getLabels()`; no envelope.
+
+**Errors:** `400` session is not started (no live engine), or the account is not a WhatsApp Business account · `401` missing/invalid API key
+
+#### GET /api/sessions/:sessionId/labels/:labelId
+
+Get a single label by its ID.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| labelId | string | Label ID |
+
+**Response** `200`
+
+```json
+{ "id": "5", "name": "Paid", "hexColor": "#25D366" }
+```
+
+The engine resolves `Label | null`; a `null` is mapped to `404` in the service, so a `200` always carries a label.
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Label <labelId> not found`
+
+#### GET /api/sessions/:sessionId/labels/chat/:chatId
+
+List the labels currently assigned to a specific chat.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| chatId | string | Chat ID (e.g. `[email protected]` or a group `…@g.us`) |
+
+**Response** `200`
+
+```json
+[
+ { "id": "5", "name": "Paid", "hexColor": "#25D366" }
+]
+```
+
+Bare array — raw return of `engine.getChatLabels(chatId)`.
+
+**Errors:** `400` session is not started · `401` missing/invalid API key
+
+#### POST /api/sessions/:sessionId/labels/chat/:chatId
+
+Add a label to a chat.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| chatId | string | Chat ID to label |
+
+**Request body** — `AddLabelDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| labelId | string | yes | non-empty string | Label ID to add to the chat |
+
+```json
+{ "labelId": "5" }
+```
+
+**Response** `201`
+
+```json
+{ "success": true }
+```
+
+The handler always returns the literal `{ "success": true }`. NestJS POST default status is `201` (the Swagger doc says `200`; the runtime code is `201`).
+
+**Errors:** `400` validation failure (missing/empty/non-string `labelId`, or any unknown body field — strict whitelist), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role
+
+#### DELETE /api/sessions/:sessionId/labels/chat/:chatId/:labelId
+
+Remove a label from a chat.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| chatId | string | Chat ID |
+| labelId | string | Label ID to remove |
+
+**Response** `200`
+
+```json
+{ "success": true }
+```
+
+The handler always returns `{ "success": true }`. DELETE default status is `200` (no `@HttpCode` override).
+
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role
+
+#### GET /api/sessions/:sessionId/status
+
+Get all contact status updates (stories) visible to the session.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+
+**Response** `200`
+
+```json
+{
+ "statuses": [
+ {
+ "id": "[email protected]_3A1F...",
+ "contact": { "id": "[email protected]", "name": "Alice", "pushName": "Alice" },
+ "type": "image",
+ "caption": "On the road",
+ "mediaUrl": "https://…",
+ "backgroundColor": "#25D366",
+ "font": 2,
+ "timestamp": "2026-06-25T08:30:00.000Z",
+ "expiresAt": "2026-06-26T08:30:00.000Z"
+ }
+ ]
+}
+```
+
+The controller wraps the engine array in `{ statuses }`. `type` is one of `text | image | video`; `caption`, `mediaUrl`, `backgroundColor`, `font` are optional. `timestamp` and `expiresAt` serialize to ISO strings (these are `Date` values, not the epoch-number convention used by message timestamps).
+
+**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404` `Session {id} not found or not connected`
+
+#### GET /api/sessions/:sessionId/status/:contactId
+
+Get status updates posted by a specific contact.
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+| contactId | string | Contact JID/id (e.g. `[email protected]`) |
+
+**Response** `200`
+
+```json
+{
+ "statuses": [
+ {
+ "id": "[email protected]_3A1F...",
+ "contact": { "id": "[email protected]", "pushName": "Alice" },
+ "type": "text",
+ "caption": "Hello!",
+ "backgroundColor": "#25D366",
+ "font": 0,
+ "timestamp": "2026-06-25T08:30:00.000Z",
+ "expiresAt": "2026-06-26T08:30:00.000Z"
+ }
+ ]
+}
+```
+
+Same `{ statuses }` wrapper and `Status` shape as the list-all route.
+
+**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404` session not found / not connected
+
+#### POST /api/sessions/:sessionId/status/send-text
+
+Post a text status (story) to the session's status feed.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+
+**Request body** — `SendTextStatusDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| text | string | yes | — | Status text body |
+| backgroundColor | string | no | 6-digit hex color matching `^#[0-9A-Fa-f]{6}$` | e.g. `#25D366`; bad value → `backgroundColor must be a hex color (e.g., #25D366)` |
+| font | integer | no | integer `0`–`4` | Font index |
+
+```json
+{ "text": "Hello from OpenWA!", "backgroundColor": "#25D366", "font": 2 }
+```
+
+**Response** `201`
+
+```json
+{
+ "statusId": "false_status@broadcast_3A1F...",
+ "timestamp": "2026-06-25T08:30:00.000Z",
+ "expiresAt": "2026-06-26T08:30:00.000Z"
+}
+```
+
+Returns the engine `StatusResult` directly (no wrapper). POST default status is `201`.
+
+**Errors:** `400` validation failure (unknown body field, bad `backgroundColor`/`font`), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+
+#### POST /api/sessions/:sessionId/status/send-image
+
+Post an image status (story) from a URL or base64 payload.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+
+**Request body** — `SendImageStatusDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| image | object (`MediaInput`) | yes | validated nested object (an empty `{}` passes — there is no `@IsNotEmpty`) | Media source wrapper |
+| image.url | string | no | — | Media source URL |
+| image.base64 | string | no | — | Base64-encoded media data |
+| caption | string | no | — | Optional caption |
+
+The service resolves the media as `image.url || image.base64 || ''` and hard-codes mimetype `image/jpeg`.
+
+```json
+{ "image": { "url": "https://example.com/photo.jpg" }, "caption": "My status" }
+```
+
+**Response** `201`
+
+```json
+{
+ "statusId": "false_status@broadcast_3A1F...",
+ "timestamp": "2026-06-25T08:30:00.000Z",
+ "expiresAt": "2026-06-26T08:30:00.000Z"
+}
+```
+
+Returns the engine `StatusResult` directly. POST default status is `201`.
+
+**Errors:** `400` unknown top-level body field (strict whitelist), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+
+#### POST /api/sessions/:sessionId/status/send-video
+
+Post a video status (story) from a URL or base64 payload.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+
+**Request body** — `SendVideoStatusDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| video | object (`MediaInput`) | yes | validated nested object (an empty `{}` passes) | Media source wrapper |
+| video.url | string | no | — | Media source URL |
+| video.base64 | string | no | — | Base64-encoded media data |
+| caption | string | no | — | Optional caption |
+
+The service resolves the media as `video.url || video.base64 || ''` and hard-codes mimetype `video/mp4`.
+
+```json
+{ "video": { "url": "https://example.com/clip.mp4" }, "caption": "Watch this" }
+```
+
+**Response** `201`
+
+```json
+{
+ "statusId": "false_status@broadcast_3A1F...",
+ "timestamp": "2026-06-25T08:30:00.000Z",
+ "expiresAt": "2026-06-26T08:30:00.000Z"
+}
+```
+
+Returns the engine `StatusResult` directly. POST default status is `201`.
+
+**Errors:** `400` unknown top-level body field, or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+
+#### DELETE /api/sessions/:sessionId/status/:statusId
+
+Delete one of the session's own posted statuses.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+| statusId | string | Id of the status to delete (the `statusId` returned by a `send-*` call) |
+
+**Response** `200`
+
+```json
+{ "message": "Status deleted successfully" }
+```
+
+The service returns `void`; the controller returns a fixed success object. DELETE default status is `200`.
+
+**Errors:** `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` `Session {id} not found or not connected`
+
+### 6.4.8 Webhooks (management)
+
+Webhooks are configured per session and managed under `/api/sessions/:sessionId/webhooks` (handled by `WebhookController`). A separate cross-session list endpoint lives at `/api/webhooks` (handled by `WebhooksListController`). Every route requires an API key with **OPERATOR** role or higher.
+
+Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.
+
+The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `group.join`, `group.leave`, `group.update`. The `group.*` events are **reserved** — accepted and validated but never dispatched (no engine emit source).
+
+#### GET /api/sessions/:sessionId/webhooks
+
+List all webhooks for a session, ordered by `createdAt` descending.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID to filter webhooks by. |
+
+**Response** `200`
+
+```json
+[
+ {
+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received", "session.status"],
+ "filters": null,
+ "active": true,
+ "retryCount": 3,
+ "lastTriggeredAt": null,
+ "createdAt": "2026-06-25T10:00:00.000Z",
+ "updatedAt": "2026-06-25T10:00:00.000Z"
+ }
+]
+```
+
+Returns a bare array; empty array if the session has no webhooks. `secret` and `headers` are never included. Not paginated.
+
+**Errors:** `401` missing/invalid API key · `403` insufficient role
+
+#### GET /api/sessions/:sessionId/webhooks/:id
+
+Get a single webhook by ID, scoped to the session.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. The lookup is `WHERE { id, sessionId }`, so a webhook belonging to a different session resolves to `404` (no cross-session existence oracle). |
+| id | string (uuid) | Webhook ID. |
+
+**Response** `200`
+
+```json
+{
+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received"],
+ "filters": null,
+ "active": true,
+ "retryCount": 3,
+ "lastTriggeredAt": "2026-06-25T11:30:00.000Z",
+ "createdAt": "2026-06-25T10:00:00.000Z",
+ "updatedAt": "2026-06-25T10:00:00.000Z"
+}
+```
+
+**Errors:** `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session (message `"Webhook with id '<id>' not found"`)
+
+#### GET /api/webhooks
+
+List webhooks visible to the calling API key, scoped to its allowed sessions.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped — derived from the authenticated key, not from any param/query
+
+**Response** `200`
+
+```json
+[
+ {
+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received"],
+ "filters": null,
+ "active": true,
+ "retryCount": 3,
+ "lastTriggeredAt": null,
+ "createdAt": "2026-06-25T10:00:00.000Z",
+ "updatedAt": "2026-06-25T10:00:00.000Z"
+ }
+]
+```
+
+Bare array, ordered by `createdAt` descending. If the calling key has a non-empty `allowedSessions` list, results are filtered to `WHERE sessionId IN (allowedSessions)`; a key with null/empty `allowedSessions` (e.g. an unrestricted ADMIN key) sees **all** webhooks. This is the cross-session list; the per-session list lives at `GET /api/sessions/:sessionId/webhooks`.
+
+**Errors:** `401` missing/invalid API key · `403` insufficient role
+
+#### POST /api/sessions/:sessionId/webhooks
+
+Create a webhook for the session.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session the webhook is scoped to; stored as `webhook.sessionId`. No session-existence check is performed at create time. |
+
+**Request body** — `CreateWebhookDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |
+| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |
+| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned. Used for `X-OpenWA-Signature`. Defaults to `null`. |
+| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned. At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |
+| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. |
+| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |
+
+```json
+{
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received", "session.status"],
+ "secret": "your-secret-key",
+ "headers": { "X-Custom-Header": "value" },
+ "filters": {
+ "conditions": [
+ { "field": "sender", "operator": "is", "value": ["[email protected]"] },
+ { "field": "body", "operator": "contains", "value": "invoice" }
+ ]
+ },
+ "retryCount": 3
+}
+```
+
+**Response** `201`
+
+```json
+{
+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received", "session.status"],
+ "filters": {
+ "conditions": [
+ { "field": "sender", "operator": "is", "value": ["[email protected]"] },
+ { "field": "body", "operator": "contains", "value": "invoice" }
+ ]
+ },
+ "active": true,
+ "retryCount": 3,
+ "lastTriggeredAt": null,
+ "createdAt": "2026-06-25T10:00:00.000Z",
+ "updatedAt": "2026-06-25T10:00:00.000Z"
+}
+```
+
+`secret` and `headers` are deliberately excluded from the response. `active` defaults to `true`, `lastTriggeredAt` is `null` on create.
+
+**Errors:** `400` validation failure, unknown body field (whitelist), or SSRF URL rejection · `401` missing/invalid API key · `403` insufficient role
+
+#### PUT /api/sessions/:sessionId/webhooks/:id
+
+Update a webhook. Partial — only fields present in the body are changed.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session scope; the webhook is looked up by `(sessionId, id)` first → `404` if not in this session. |
+| id | string (uuid) | Webhook ID. |
+
+**Request body** — `UpdateWebhookDto` (all fields optional; only fields where the value is not `undefined` are applied)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| url | string | no | `@IsOptional`, `@IsUrl({ require_tld: false })`; re-runs the SSRF guard when provided → `400` if blocked. | New URL. |
+| events | string[] | no | `@IsOptional`, `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Same allowed set as create (incl. `*` and reserved `group.*`). |
+| secret | string | no | `@IsOptional`, `@IsString`, `@MaxLength(255)` | **Write-only.** An empty string is normalized to `null`, which disables HMAC. |
+| headers | Record<string,string> | no | `@IsOptional`, `@IsHeaderMap()` (same constraints as create) | **Write-only.** Replaces existing headers wholesale when provided. |
+| filters | WebhookFilters \| null | no | `@IsOptional`, `@IsValidWebhookFilters()` | Set to `null` to clear filters. |
+| active | boolean | no | `@IsOptional`, `@IsBoolean` | Enable/disable the webhook. (Present only on update, not create.) |
+| retryCount | number (int) | no | `@IsOptional`, `@IsInt`, `@Min(0)`, `@Max(5)` | Retry attempts. |
+
+```json
+{
+ "events": ["*"],
+ "active": false,
+ "retryCount": 5,
+ "filters": null
+}
+```
+
+**Response** `200`
+
+```json
+{
+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "url": "https://your-server.com/webhook",
+ "events": ["*"],
+ "filters": null,
+ "active": false,
+ "retryCount": 5,
+ "lastTriggeredAt": null,
+ "createdAt": "2026-06-25T10:00:00.000Z",
+ "updatedAt": "2026-06-25T12:00:00.000Z"
+}
+```
+
+Returns the saved entity; `secret` and `headers` excluded.
+
+**Errors:** `400` validation failure, unknown body field (whitelist), or SSRF URL rejection · `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session
+
+#### POST /api/sessions/:sessionId/webhooks/:id/test
+
+Send a synthetic test payload to the webhook URL and report the result. No request body.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session scope; looked up first → `404` if not in this session. |
+| id | string (uuid) | Webhook ID. |
+
+**Response** `200`
+
+```json
+{ "success": true, "statusCode": 200 }
+```
+
+On a reachable endpoint the response is `{ success: <response.ok>, statusCode: <response.status> }` — so a non-2xx target returns `200` HTTP with `success: false` and the target's `statusCode`. On an SSRF/timeout/network error the response is `{ "success": false, "error": "<message>" }`. The endpoint never throws on delivery failure; the failure is reflected in the body, not the HTTP status. The test POST sends `{ "event": "test", ... }` with headers `Content-Type`, `User-Agent: OpenWA-Webhook/1.0.0`, `X-OpenWA-Event: test`, `X-OpenWA-Idempotency-Key`, `X-OpenWA-Delivery-Id`, `X-OpenWA-Retry-Count: 0`, and `X-OpenWA-Signature` when a secret is set. Timeout defaults to 10000 ms (`webhook.timeout` config).
+
+**Errors:** `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session
+
+#### DELETE /api/sessions/:sessionId/webhooks/:id
+
+Delete a webhook, scoped to the session.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session scope; looked up first → `404` if not in this session. |
+| id | string (uuid) | Webhook ID. |
+
+**Response** `204`
+
+No content (empty body; explicit `@HttpCode(204)`).
+
+**Errors:** `401` missing/invalid API key · `403` insufficient role · `404` webhook not found in this session
+
+### 6.4.9 API Keys
+
+API keys are managed under `/api/auth/api-keys`. All management routes (create/list/get/update/delete/revoke) require an **ADMIN** key. The plaintext key string is returned **only once**, at creation. Validation of the caller's own key lives at `POST /api/auth/validate` and accepts any valid key.
+
+#### GET /api/auth/api-keys
+
+List all API keys, newest first. The plaintext key is never returned.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
+Bare JSON array (no envelope), ordered by `createdAt` DESC. Null array/date fields are omitted.
+
+```json
+[
+ {
+ "id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
+ "name": "Production Bot",
+ "keyPrefix": "owa_k1_a1b2",
+ "role": "operator",
+ "allowedIps": ["192.168.1.1", "10.0.0.0/8"],
+ "allowedSessions": ["session-uuid-1"],
+ "isActive": true,
+ "expiresAt": "2027-12-31T23:59:59.000Z",
+ "lastUsedAt": "2026-06-25T08:14:00.000Z",
+ "usageCount": 42,
+ "createdAt": "2026-06-01T10:00:00.000Z"
+ }
+]
+```
+
+**Errors:** `401` missing/invalid `X-API-Key` · `403` key role below ADMIN
+
+#### GET /api/auth/api-keys/:id
+
+Get a single API key's details by id. No plaintext key.
+
+**Auth:** API key (ADMIN)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string (uuid) | API key id. Opaque resource id, not session-scoped. |
+
+**Response** `200`
+
+```json
+{
+ "id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
+ "name": "Production Bot",
+ "keyPrefix": "owa_k1_a1b2",
+ "role": "operator",
+ "allowedIps": ["192.168.1.1", "10.0.0.0/8"],
+ "allowedSessions": ["session-uuid-1"],
+ "isActive": true,
+ "expiresAt": "2027-12-31T23:59:59.000Z",
+ "lastUsedAt": "2026-06-25T08:14:00.000Z",
+ "usageCount": 42,
+ "createdAt": "2026-06-01T10:00:00.000Z"
+}
+```
+
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` `"API key with id '<id>' not found"`
+
+#### POST /api/auth/api-keys
+
+Create a new API key; returns the full plaintext key exactly once.
+
+**Auth:** API key (ADMIN)
+
+**Request body** — `CreateApiKeyDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `name` | string | yes | length 3–100 | Friendly name for the key. |
+| `role` | enum `admin` \| `operator` \| `viewer` | no | `@IsEnum` | Defaults to `operator` when omitted. |
+| `allowedIps` | string[] | no | each entry a valid **IPv4** address or IPv4 CIDR `/0-32`; IPv6 rejected | IP whitelist (IPv4-only by design). |
+| `allowedSessions` | string[] | no | each `@IsString` | Session IDs this key may access. |
+| `expiresAt` | string (ISO 8601 date) | no | `@IsDateString` | Stored as a `Date`. |
+
+```json
+{
+ "name": "Production Bot",
+ "role": "operator",
+ "allowedIps": ["192.168.1.1", "10.0.0.0/8"],
+ "allowedSessions": ["session-uuid-1"],
+ "expiresAt": "2027-12-31T23:59:59Z"
+}
+```
+
+**Response** `201` — `ApiKeyCreatedResponseDto`
+
+Same shape as the read DTO **plus** an `apiKey` field carrying the full plaintext key `owa_k1_<64 hex>`. This is the **only** time the plaintext key is returned. `keyPrefix` is the first 12 chars; `usageCount` starts at `0`, `isActive` is `true`. Null `allowedIps`/`allowedSessions`/`expiresAt`/`lastUsedAt` are omitted.
+
+```json
+{
+ "id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
+ "name": "Production Bot",
+ "keyPrefix": "owa_k1_a1b2",
+ "role": "operator",
+ "allowedIps": ["192.168.1.1", "10.0.0.0/8"],
+ "allowedSessions": ["session-uuid-1"],
+ "isActive": true,
+ "expiresAt": "2027-12-31T23:59:59.000Z",
+ "usageCount": 0,
+ "createdAt": "2026-06-25T09:30:00.000Z",
+ "apiKey": "owa_k1_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+}
+```
+
+**Errors:** `400` validation (bad `name` length, invalid `role` enum, non-IPv4 `allowedIps` entry, bad `expiresAt`, or any non-whitelisted body field) · `401` missing/invalid key · `403` key role below ADMIN
+
+#### PUT /api/auth/api-keys/:id
+
+Update mutable fields of an API key. `isActive` is **not** updatable here — use the revoke route to deactivate.
+
+**Auth:** API key (ADMIN)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string (uuid) | API key id. |
+
+**Request body** — `UpdateApiKeyDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `name` | string | no | length 3–100 | Applied only if truthy. |
+| `role` | enum `admin` \| `operator` \| `viewer` | no | `@IsEnum` | Applied only if truthy. |
+| `allowedIps` | string[] | no | IPv4 address / CIDR only | Applied if not `undefined` (can be set to `[]` to clear). |
+| `allowedSessions` | string[] | no | each `@IsString` | Applied if not `undefined`. |
+| `expiresAt` | string (ISO 8601 date) | no | `@IsDateString` | Applied if not `undefined`; empty/falsy clears to `null`. |
+
+```json
+{
+ "name": "Renamed Bot",
+ "role": "viewer",
+ "allowedIps": ["203.0.113.5"],
+ "expiresAt": "2028-01-01T00:00:00Z"
+}
+```
+
+**Response** `200` — `ApiKeyResponseDto`
+
+Returns the updated key (no plaintext).
+
+```json
+{
+ "id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
+ "name": "Renamed Bot",
+ "keyPrefix": "owa_k1_a1b2",
+ "role": "viewer",
+ "allowedIps": ["203.0.113.5"],
+ "isActive": true,
+ "expiresAt": "2028-01-01T00:00:00.000Z",
+ "usageCount": 42,
+ "createdAt": "2026-06-01T10:00:00.000Z"
+}
+```
+
+**Errors:** `400` validation (incl. `forbidNonWhitelisted` for unknown fields such as `isActive`) · `401` missing/invalid key · `403` key role below ADMIN · `404` not found
+
+#### POST /api/auth/api-keys/:id/revoke
+
+Revoke (deactivate) an API key without deleting it. No request body required.
+
+**Auth:** API key (ADMIN)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string (uuid) | API key id. |
+
+**Response** `200` — `ApiKeyResponseDto`
+
+Sets `isActive` to `false` and returns the key. Default POST status `200` (no `@HttpCode` override). After revoke, the key fails validation with `401 "API key is revoked"`.
+
+```json
+{
+ "id": "3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33",
+ "name": "Production Bot",
+ "keyPrefix": "owa_k1_a1b2",
+ "role": "operator",
+ "isActive": false,
+ "usageCount": 42,
+ "createdAt": "2026-06-01T10:00:00.000Z"
+}
+```
+
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` not found
+
+#### DELETE /api/auth/api-keys/:id
+
+Permanently delete an API key (hard delete). Also drops any un-flushed usage accumulator.
+
+**Auth:** API key (ADMIN)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string (uuid) | API key id. |
+
+**Response** `204`
+
+`@HttpCode(204)` — no response body.
+
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` `"API key with id '<id>' not found"`
+
+#### POST /api/auth/validate
+
+Validate the supplied `X-API-Key` and report its validity and role.
+
+**Auth:** API key (any valid role — VIEWER+)
+
+The key is read from the `X-API-Key` header, not the body; send an empty body. This route sits behind the global guard (it is not `@Public`), so a missing/invalid/revoked/expired key is rejected with `401` at the guard before the handler runs. On success it returns the caller's role.
+
+**Response** `200`
+
+```json
+{ "valid": true, "role": "operator" }
+```
+
+**Errors:** `401` missing/invalid/revoked/expired key (raised by the global guard before the handler)
+
+> Implemented by `AuthValidateController` (`@Controller('auth')`), sharing the same `/api/auth` base.
+
+### 6.4.10 System (Health, Metrics, Stats, Settings)
+
+System endpoints expose operational status, Prometheus metrics, aggregate statistics, and runtime settings. Health and metrics use non-standard auth (public / Bearer token); stats and settings use the API key, with several routes gated to `ADMIN`.
+
+#### GET /api/health
+
+Basic health check returning status, the current timestamp, and the running app version.
+
+**Auth:** public
+
+**Response** `200`
+
+```json
+{ "status": "ok", "timestamp": "2026-06-25T12:34:56.789Z", "version": "0.7.3" }
+```
+
+Notes: `timestamp` is an ISO-8601 string (`new Date().toISOString()`). `version` is read from `package.json` at module load. Exempt from rate limiting (`@SkipThrottle`).
+
+#### GET /api/health/live
+
+Kubernetes liveness probe — returns a deliberately static body reflecting only process liveness; it does NOT probe dependencies.
+
+**Auth:** public
+
+**Response** `200`
+
+```json
+{ "status": "ok" }
+```
+
+Notes: always `{ "status": "ok" }`. Intentionally static so a transient dependency outage does not trigger a pod kill. The handler never returns a non-200.
+
+#### GET /api/health/ready
+
+Readiness probe — verifies the `main` (auth/audit) and `data` TypeORM datasources respond to `SELECT 1` (each bounded to a 3000 ms timeout) and reports `503` while the app is draining/shutting down.
+
+**Auth:** public
+
+**Response** `200`
+
+```json
+{
+ "status": "ok",
+ "details": {
+ "mainDatabase": { "status": "up" },
+ "dataDatabase": { "status": "up" }
+ }
+}
+```
+
+**Errors:** `503` — either datasource fails or exceeds its 3 s `SELECT 1` timeout, or the app is shutting down. The handler throws `ServiceUnavailableException`, so NestJS wraps the custom `{ status, details }` object as the `message` field:
+
+```json
+{
+ "statusCode": 503,
+ "message": {
+ "status": "error",
+ "details": { "mainDatabase": { "status": "up" }, "dataDatabase": { "status": "down" } }
+ },
+ "error": "Service Unavailable"
+}
+```
+
+During shutdown the `details` instead read `{ "shutdown": { "status": "draining" } }`. Probes run in parallel via `Promise.all`. There is no `health/detailed` route.
+
+#### GET /api/metrics
+
+Prometheus exposition scrape of OpenWA process + session + message metrics; gated by a `METRICS_TOKEN` bearer (disabled when the token is unset).
+
+**Auth:** Bearer METRICS_TOKEN — `Authorization: Bearer <METRICS_TOKEN>`. This route is `@Public()` (it bypasses the `X-API-Key` guard); access is instead validated inside the service with a constant-time compare. The `Bearer ` prefix is stripped case-insensitively. Hidden from Swagger.
+
+**Response** `200`
+
+Content-Type `text/plain; version=0.0.4; charset=utf-8`, `Cache-Control: no-store`. Raw text (no JSON envelope):
-```http
-POST /api/sessions/:sessionId/messages/send-template
```
+# HELP openwa_up 1 if the OpenWA process is running
+# TYPE openwa_up gauge
+openwa_up 1
+# TYPE openwa_process_uptime_seconds gauge
+openwa_process_uptime_seconds 3600
+# TYPE openwa_process_resident_memory_bytes gauge
+openwa_process_resident_memory_bytes 187432960
+# TYPE openwa_process_heap_used_bytes gauge
+openwa_process_heap_used_bytes 64512000
+# TYPE openwa_sessions_total gauge
+openwa_sessions_total 3
+# TYPE openwa_sessions_active gauge
+openwa_sessions_active 2
+# TYPE openwa_sessions gauge
+openwa_sessions{status="ready"} 2
+openwa_sessions{status="disconnected"} 1
+# TYPE openwa_messages_total counter
+openwa_messages_total{direction="outgoing"} 1280
+openwa_messages_total{direction="incoming"} 940
+# TYPE openwa_messages_failed_total counter
+openwa_messages_failed_total 4
+```
+
+Values come from `StatsService.getOverview()` plus `process.memoryUsage()`/`process.uptime()`. The render is memoized for 5000 ms to avoid re-running the overview query on every scrape.
+
+**Errors:** `401` — `METRICS_TOKEN` is configured but the bearer is missing or does not match (`{ "statusCode": 401, "message": "Invalid metrics token", "error": "Unauthorized" }`) · `404` — `METRICS_TOKEN` is unset/blank, so the endpoint is disabled (`{ "statusCode": 404, "message": "Metrics endpoint is disabled (set METRICS_TOKEN to enable)", "error": "Not Found" }`).
+
+#### GET /api/stats/overview
+
+Get overall cross-session aggregate statistics (sessions by status + message totals + today's counts).
+
+**Auth:** API key (ADMIN) — deliberately ADMIN-only (global cross-tenant aggregate).
+
+**Response** `200`
-**Request Body:**
```json
{
- "chatId": "[email protected]",
- "templateName": "order-confirmation",
- "vars": {
- "customer": "Alice",
- "orderId": "1234"
+ "sessions": {
+ "active": 2,
+ "total": 3,
+ "byStatus": { "READY": 2, "DISCONNECTED": 1 }
+ },
+ "messages": {
+ "sent": 1280,
+ "received": 940,
+ "failed": 4,
+ "today": { "sent": 42, "received": 30 }
}
}
```
-**Request Fields:**
+Notes: raw handler return (no envelope). `sessions.byStatus` is keyed by `SessionStatus` enum values with per-status counts; `sessions.active` counts only `READY`. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `failed` is the `FAILED`-status COUNT; `today.*` are the same counts since local midnight. Side effect: caches the `sessions` block via `CacheService`.
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| `chatId` | string | Yes | Recipient chat ID |
-| `templateId` | string | Conditional | Template UUID. Provide either `templateId` or `templateName`. |
-| `templateName` | string | Conditional | Template name within the session. Provide either `templateId` or `templateName`. |
-| `vars` | object | No | Map of `{{placeholder}}` keys to substitution values. Unknown placeholders are left literal. |
+**Errors:** `401` — missing/invalid `X-API-Key` · `403` — key role below `ADMIN`.
+
+#### GET /api/stats/messages
+
+Get message statistics over a period: time series, counts by type, by session, and top chats.
+
+**Auth:** API key (ADMIN) — cross-session aggregate.
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `period` | `'24h' \| '7d' \| '30d'` | No | `24h` | Window for the report. `@IsIn(['24h','7d','30d'])` — any other value → `400`. Bucket interval is `hour` for `24h`, else `day`. |
+
+**Response** `200`
+
+```json
+{
+ "timeSeries": [
+ { "timestamp": "2026-06-25 10:00:00", "sent": 12, "received": 8 },
+ { "timestamp": "2026-06-25 11:00:00", "sent": 20, "received": 14 }
+ ],
+ "byType": { "chat": 180, "image": 24, "unknown": 3 },
+ "bySession": [
+ { "sessionId": "9f1c…", "name": "support-line", "sent": 200, "received": 140 }
+ ],
+ "topChats": [
+ { "chatId": "[email protected]", "messageCount": 320 }
+ ]
+}
+```
+
+Notes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket string — hourly `YYYY-MM-DD HH:00:00` for `24h`, daily `YYYY-MM-DD` for `7d`/`30d` — sorted ascending. `byType` keys are message-type strings (a null type becomes `unknown`). `bySession.name` is `Unknown` when the session is not found. `topChats` is the top 10 by `messageCount` DESC. All counts are numbers.
+
+**Errors:** `400` — `period` not in the enum, or any non-whitelisted query field (strict `whitelist` + `forbidNonWhitelisted`) · `401` — missing/invalid API key · `403` — role below `ADMIN`.
+
+#### GET /api/stats/sessions/:sessionId
+
+Get statistics for a single session: identity, message counts, top chats, and 24 h hourly activity.
+
+**Auth:** API key — any valid key (VIEWER and up); there is no `@RequireRole`. Note: the handler does NOT verify the key is scoped to this session, so any authenticated key can read any session's stats.
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `sessionId` | string | Session entity id. No format validation; `404` if no session matches. |
+
+**Response** `200`
+
+```json
+{
+ "session": { "id": "9f1c…", "name": "support-line", "status": "ready" },
+ "messages": { "sent": 200, "received": 140, "today": 18, "failed": 1 },
+ "topChats": [
+ { "chatId": "[email protected]", "count": 64, "lastActive": "2026-06-25 11:42:07" }
+ ],
+ "hourlyActivity": [
+ { "hour": 0, "sent": 0, "received": 0 },
+ { "hour": 1, "sent": 3, "received": 2 }
+ ]
+}
+```
+
+Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `today` is the total message count since local midnight; `failed` is the `FAILED`-status count. `topChats` is the top 10 by count DESC, with `lastActive` = `MAX(createdAt)` as a DB-native datetime string. `hourlyActivity` always has 24 entries (hour `0..23`), missing hours zero-filled, computed over the last 24 h.
+
+**Errors:** `401` — missing/invalid API key · `404` — session not found (`Session not found`).
+
+#### GET /api/settings
+
+Get application settings (environment-derived; `general`/`api`/`notifications` groups).
+
+**Auth:** API key — any valid role (no `@RequireRole`).
+
+**Response** `200`
+
+```json
+{
+ "general": {
+ "apiBaseUrl": "http://localhost:2785",
+ "sessionTimeout": 0,
+ "autoReconnect": false,
+ "debugMode": false
+ },
+ "api": {
+ "rateLimit": 100,
+ "rateLimitWindow": 60000,
+ "enableDocs": true
+ },
+ "notifications": {
+ "emailEnabled": false,
+ "notificationEmail": "",
+ "webhookAlerts": true
+ }
+}
+```
+
+Notes: raw return of an in-memory `Settings` object built once in the controller constructor from `ConfigService` (snapshotted at construction, not re-read per request). `general.sessionTimeout` is `floor(webhook.timeout / 60000)` minutes; `api.rateLimitWindow` is in ms; `enableDocs`/`notifications.*` are partly hardcoded (`enableDocs: true`, `emailEnabled: false`, `notificationEmail: ''`, `webhookAlerts: true`).
+
+**Errors:** `401` — missing/invalid `X-API-Key`.
+
+#### PUT /api/settings
+
+Update settings — intentionally not implemented; always returns `501` (settings are env-derived and read-only at runtime).
+
+**Auth:** API key (ADMIN)
+
+**Request body** — none. There is no request DTO; any body is ignored (the exception is thrown before validation matters).
+
+**Response** `501`
-**Response (201 Created):**
```json
{
- "messageId": "[email protected]_3EB0ABC123",
- "timestamp": "2025-02-02T10:00:00.000Z"
+ "statusCode": 501,
+ "message": "Settings are derived from environment configuration and are read-only at runtime. Change the corresponding environment variable and restart the service.",
+ "error": "Not Implemented"
}
```
-Returns `404 Not Found` when the session or the referenced template does not
-exist, and `400 Bad Request` when the session is not active.
+Notes: the handler unconditionally throws `NotImplementedException`. Even an ADMIN key always gets `501`; there is no success response.
+
+**Errors:** `401` — missing/invalid key · `403` — key lacks `ADMIN` · `501` — always (not implemented).
+
+### 6.4.11 Administration (Infrastructure, Plugins, MCP)
+
+Admin-facing operations: infrastructure status & config, the data/storage migration tooling, plugin lifecycle, and the optional MCP transport. Almost every route is **API key (ADMIN)**; the two exceptions are the public `GET /api/infra/health` and the `POST /mcp` JSON-RPC endpoint (see end of section).
+
+> Note on the infra/MCP request bodies: the `PUT /api/infra/config`, `POST /api/infra/restart`, `POST /api/infra/import-data`, `POST /api/infra/storage/import` bodies and the entire `POST /mcp` envelope are **plain TS interfaces, not class-validator DTOs** — the global `whitelist`/`forbidNonWhitelisted` ValidationPipe does **not** run on them. Unknown fields pass through silently and no type/constraint checks happen, except the few field-level guards noted per endpoint. Plugin DTOs (`InstallFromUrlDto`, `PluginConfigDto`, `PluginSessionsDto`) *are* class-validated and reject unknown fields with `400`.
---
-### 6.4.3 Templates
+#### GET /api/infra/health
-Server-side text message templates (issue #69, Option B). Templates are scoped
-to a session and rendered with `{{placeholder}}` substitution by the
-[Send Template Message](#send-template-message) endpoint. All endpoints require
-an API key with at least the `operator` role.
+Public liveness probe.
-> Interactive button / list / HSM templates (**Option A**) are out of scope on
-> all current engines and are not provided.
+**Auth:** public
-#### Create Template
+**Response** `200`
-```http
-POST /api/sessions/:sessionId/templates
+```json
+{ "status": "ok", "timestamp": "2026-06-25T12:00:00.000Z" }
```
-**Request Body:**
+---
+
+#### GET /api/infra/status
+
+Aggregate infrastructure status (database, Redis, queue, storage, engine).
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
```json
{
- "name": "order-confirmation",
- "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
- "header": "OpenWA Store",
- "footer": "Reply STOP to unsubscribe."
+ "database": { "connected": true, "type": "sqlite", "host": "" },
+ "redis": { "enabled": false, "connected": false, "host": "localhost", "port": 6379 },
+ "queue": {
+ "enabled": false,
+ "messages": { "pending": 0, "completed": 0, "failed": 0 },
+ "webhooks": { "pending": 0, "completed": 0, "failed": 0 }
+ },
+ "storage": { "type": "local", "path": "./data/media" },
+ "engine": {
+ "type": "whatsapp-web.js",
+ "headless": true,
+ "sessionDataPath": "./data/sessions",
+ "browserArgs": "--no-sandbox --disable-gpu"
+ }
+}
+```
+
+The `queue.messages`/`queue.webhooks` counters are hardcoded to zeros (not live job counts); `redis.connected` is a live probe. `storage` only ever returns `type`+`path` here (no `bucket`).
+
+**Errors:** `401` missing/invalid key · `403` key role < ADMIN
+
+---
+
+#### GET /api/infra/engines
+
+List available WhatsApp engine plugins.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200` — bare array
+
+```json
+[
+ {
+ "id": "whatsapp-web.js",
+ "name": "WhatsApp Web.js",
+ "enabled": true,
+ "features": ["send", "receive", "media", "groups"],
+ "library": { "name": "whatsapp-web.js", "version": "1.34.7" }
+ }
+]
+```
+
+`library` is optional and may be omitted per engine.
+
+**Errors:** `401` · `403`
+
+---
+
+#### GET /api/infra/engines/current
+
+Get the currently active engine type.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
+```json
+{ "engineType": "whatsapp-web.js" }
+```
+
+**Errors:** `401` · `403`
+
+---
+
+#### GET /api/infra/config
+
+Read the saved infrastructure config from `data/.env.generated` (used to hydrate the dashboard form). **Secrets are never returned** — only `*Set`/`*CredentialsSet` booleans indicate that a secret is stored.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200` — `SavedConfigResponse`
+
+```json
+{
+ "database": {
+ "type": "sqlite", "builtIn": false, "host": "", "port": "",
+ "username": "", "database": "", "poolSize": 10,
+ "sslEnabled": false, "sslRejectUnauthorized": true, "passwordSet": false
+ },
+ "redis": { "enabled": false, "builtIn": false, "host": "", "port": "", "passwordSet": false },
+ "queue": { "enabled": false },
+ "storage": {
+ "type": "local", "builtIn": false, "localPath": "./data/media",
+ "s3Bucket": "", "s3Region": "", "s3Endpoint": "", "s3CredentialsSet": false
+ },
+ "engine": {
+ "type": "whatsapp-web.js", "headless": true,
+ "sessionDataPath": "./data/sessions", "browserArgs": "--no-sandbox --disable-gpu"
+ }
+}
+```
+
+When `data/.env.generated` does not exist, empty-string/default values are returned (`poolSize=10`, `sslRejectUnauthorized=true`, `engine.type='whatsapp-web.js'`, `headless=true`).
+
+**Errors:** `401` · `403`
+
+---
+
+#### PUT /api/infra/config
+
+Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file). A partial payload preserves untouched keys; empty/omitted secret fields keep the existing stored secret.
+
+**Auth:** API key (ADMIN)
+
+**Request body** — `SaveConfigDto` (plain interface, **not** class-validated; only `engine.type` and CR/LF safety are enforced)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `database` | object | No | — | DB section (see nested) |
+| `database.type` | `'sqlite' \| 'postgres'` | No | — | `sqlite` drops stale postgres keys; `postgres` writes connection keys |
+| `database.builtIn` | boolean | No | — | When `true`+postgres, forces the bundled `postgres` container creds + pushes `postgres` Docker profile |
+| `database.host` / `.port` / `.username` / `.database` | string | No | `port` is a string | External postgres connection (defaults `localhost`/`5432`/`postgres`/`openwa`) |
+| `database.password` | string | No | secret | Empty/omitted keeps the existing stored secret |
+| `database.poolSize` | number | No | — | Default 10 |
+| `database.sslEnabled` | boolean | No | — | Default false |
+| `database.sslRejectUnauthorized` | boolean | No | — | Only written when `sslEnabled` is true; default true |
+| `redis.enabled` / `.builtIn` | boolean | No | — | `builtIn`+enabled forces `redis` container + profile |
+| `redis.host` / `.port` | string | No | `port` is a string | Defaults `localhost`/`6379` |
+| `redis.password` | string | No | secret | Empty keeps existing |
+| `queue.enabled` | boolean | No | — | Writes `QUEUE_ENABLED` |
+| `storage.type` | `'local' \| 's3'` | No | — | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH` |
+| `storage.builtIn` | boolean | No | — | `true`+s3 uses bundled MinIO defaults + pushes `minio` profile |
+| `storage.localPath` | string | No | — | Default `./data/media` |
+| `storage.s3Bucket` / `.s3Region` / `.s3Endpoint` | string | No | — | External S3 |
+| `storage.s3AccessKey` / `.s3SecretKey` | string | No | secret | Empty keeps existing |
+| `engine.type` | string | No | **must be a known engine id, else `400`** | The only validated field in the body |
+| `engine.headless` | boolean | No | — | Default true; saved as `PUPPETEER_HEADLESS` |
+| `engine.sessionDataPath` | string | No | — | Default `./data/sessions` |
+| `engine.browserArgs` | string | No | — | Saved as `PUPPETEER_ARGS` |
+
+```json
+{
+ "database": { "type": "postgres", "builtIn": false, "host": "db.example.com", "port": "5432", "username": "openwa", "password": "s3cret", "database": "openwa", "poolSize": 10, "sslEnabled": true, "sslRejectUnauthorized": false },
+ "redis": { "enabled": true, "builtIn": true },
+ "queue": { "enabled": true },
+ "storage": { "type": "s3", "builtIn": false, "s3Bucket": "my-bucket", "s3Region": "ap-southeast-1", "s3AccessKey": "AKIA...", "s3SecretKey": "...", "s3Endpoint": "https://s3.example.com" },
+ "engine": { "type": "whatsapp-web.js", "headless": true, "sessionDataPath": "./data/sessions", "browserArgs": "--no-sandbox --disable-gpu" }
+}
+```
+
+**Response** `200`
+
+```json
+{ "message": "Configuration saved. Server restart required.", "saved": true, "envPath": "data/.env.generated", "profiles": ["postgres", "redis"] }
+```
+
+This route **always returns HTTP 200**, even on failure: write/IO errors are caught and returned as `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. The only true `400` cases are an unknown `engine.type` or any value containing `\r`/`\n`. `profiles` lists newly-required Docker profiles.
+
+**Errors:** `400` unknown `engine.type` / CR-LF in a value · `401` · `403`
+
+---
+
+#### POST /api/infra/restart
+
+Request a graceful server restart, optionally orchestrating Docker profiles (add/remove services). Schedules process shutdown as a side-effect.
+
+**Auth:** API key (ADMIN)
+
+**Request body** — optional inline type (plain interface, not class-validated)
+
+| Field | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `profiles` | string[] | No | `[]` | Docker profiles to enable/start (e.g. `postgres`, `redis`, `minio`) |
+| `profilesToRemove` | string[] | No | `[]` | Docker profiles whose containers should be stopped/removed |
+
+```json
+{ "profiles": ["postgres", "redis"], "profilesToRemove": ["minio"] }
+```
+
+**Response** `200`
+
+```json
+{
+ "message": "Restarting…",
+ "restarting": true,
+ "profiles": ["postgres", "redis"],
+ "profilesToRemove": ["minio"],
+ "estimatedTime": 48
+}
+```
+
+`estimatedTime` (seconds) = base 15 + 20/postgres + 13/redis + 15/minio + 5/removal. `orchestration` is present only when Docker is available and `profiles` is non-empty; `removal` only when Docker is available and `profilesToRemove` is non-empty. Without Docker, a `data/.orchestration-request.json` signal file is written instead. After responding, `shutdownService.shutdown()` runs (default ~3s grace); readiness returns `503` during drain.
+
+**Errors:** `401` · `403`
+
+---
+
+#### GET /api/infra/export-data
+
+Export every row from the Data DB (sessions, webhooks, messages, batches, templates, Baileys stored messages) as JSON for migration. Read-only, but runs raw `SELECT *` on the `data` DataSource.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
+```json
+{
+ "exportedAt": "2026-06-25T12:00:00.000Z",
+ "dataDbType": "sqlite",
+ "tables": {
+ "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "webhooks": [],
+ "messages": [],
+ "messageBatches": [],
+ "templates": [],
+ "baileysStoredMessages": []
+ },
+ "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0 }
}
```
-**Request Fields:**
+Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows include `secret` in cleartext.** `messages`/`messageBatches`/`templates`/`baileysStoredMessages` default to `[]` if their table is missing; `sessions`/`webhooks` are not try-wrapped, so a hard DB error there yields `500`.
+
+**Errors:** `401` · `403` · `500` DB error
+
+---
+
+#### POST /api/infra/import-data
+
+Replace all Data DB rows with the supplied export. **Destructive and transactional (all-or-nothing).**
+
+**Auth:** API key (ADMIN)
+
+**Request body** — inline `{ tables: Partial<MigrationTables> }` (plain interface, not class-validated)
| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| `name` | string | Yes | Template name (max 100 chars), unique per session by convention |
-| `body` | string | Yes | Template body with `{{placeholder}}` tokens (max 4096 chars) |
-| `header` | string | No | Optional header, prepended to the rendered body |
-| `footer` | string | No | Optional footer, appended to the rendered body |
+| --- | --- | --- | --- |
+| `tables` | object | Yes | Container of per-table row arrays. Accessing `data.tables` directly means a missing/null value throws `500` |
+| `tables.sessions` | `SessionRow[]` | No | Inserted first; skipped if absent/empty |
+| `tables.webhooks` | `WebhookRow[]` | No | Includes `secret` |
+| `tables.messages` | `MessageRow[]` | No | — |
+| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |
+| `tables.templates` | `TemplateRow[]` | No | — |
+| `tables.baileysStoredMessages` | `BaileysStoredMessageRow[]` | No | — |
+
+```json
+{
+ "tables": {
+ "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": []
+ }
+}
+```
-When rendered, the header, body, and footer are joined with blank lines.
+**Response** `200`
-**Response (201 Created):**
```json
{
- "id": "b1c2d3e4-f5a6-7890-bcde-f01234567890",
- "sessionId": "sess_abc123",
- "name": "order-confirmation",
- "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
- "header": "OpenWA Store",
- "footer": "Reply STOP to unsubscribe.",
- "createdAt": "2025-02-02T10:00:00.000Z",
- "updatedAt": "2025-02-02T10:00:00.000Z"
+ "imported": true,
+ "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0 },
+ "warnings": []
}
```
+Inside a transaction it DELETEs all rows from webhooks/messages/message_batches/templates/baileys_stored_messages/sessions, then re-inserts. If **any** row insert fails, `warnings` is non-empty, the transaction is **rolled back**, and `imported:false` is returned (counts reflect rows inserted before the failure). JSON object/array fields are auto-stringified before insert.
+
+**Errors:** `401` · `403` · `500` `tables` missing/null or unrecoverable DB error
+
+---
+
+#### GET /api/infra/storage/files/count
+
+File count and total size in the active storage backend.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
+```json
+{ "storageType": "local", "count": 128, "sizeBytes": 5242880, "sizeMB": "5.00" }
+```
+
+**Errors:** `401` · `403` · `500`
+
+---
+
+#### GET /api/infra/storage/export
+
+Export all storage files into a `tar.gz` under `data/exports` and return its **server-side path** (not a download stream).
+
+**Auth:** API key (ADMIN)
+
+**Response** `200`
+
+```json
+{ "message": "Storage export completed", "download": "data/exports/storage-export-1750000000000-abc.tar.gz" }
+```
+
+`download` is a server filesystem path — feed it back to `POST /api/infra/storage/import`. The archive is auto-deleted after `STORAGE_EXPORT_TTL_MS` (default 1h).
+
+**Errors:** `401` · `403` · `500`
+
+---
+
+#### POST /api/infra/storage/import
+
+Import storage files from a `tar.gz` located inside the `data/` directory.
+
+**Auth:** API key (ADMIN)
+
+**Request body** — inline `{ filePath: string }` (plain interface, not class-validated; path-safety enforced manually)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `filePath` | string | Yes | Must resolve inside `<cwd>/data` **and** exist on disk, else `400` | Path to the archive (constrained to `data/` to block traversal) |
+
+```json
+{ "filePath": "./data/exports/storage-export-1750000000000-abc.tar.gz" }
+```
+
+**Response** `200`
+
+```json
+{ "imported": true, "count": 128, "storageType": "local" }
+```
+
+**Errors:** `400` missing/out-of-`data/`/not-found path · `401` · `403` · `500`
+
+---
+
+#### GET /api/plugins
+
+List all loaded plugins (built-in + installed), with secret config values redacted.
+
+**Auth:** API key (ADMIN)
+
+**Response** `200` — `PluginDto[]` (bare array, `[]` if none)
+
+```json
+[
+ {
+ "id": "chat-flow",
+ "name": "Chat Flow",
+ "version": "1.0.0",
+ "type": "extension",
+ "description": "Visual reply flows",
+ "author": "openwa-plugins",
+ "status": "enabled",
+ "config": { "apiKey": "********" },
+ "builtIn": false,
+ "provides": ["message-hook"],
+ "sessionScoped": true,
+ "activeSessions": ["*"],
+ "loadedAt": "2026-06-25T00:00:00.000Z",
+ "enabledAt": "2026-06-25T00:01:00.000Z"
+ }
+]
+```
+
+`type` is one of `engine | storage | queue | auth | extension`; `status` is `installed | enabled | disabled | error`. `activeSessions: ["*"]` means all sessions. Optional fields: `configSchema`, `configUi`, `i18n`, `sessionConfig` (secrets redacted), `error`.
+
+**Errors:** `401` · `403`
+
+---
+
+#### GET /api/plugins/catalog
+
+List the remote plugin catalog annotated with this instance's install state. (Declared before `:id` so `catalog` is not captured as an id.)
+
+**Auth:** API key (ADMIN)
+
+**Response** `200` — bare array
+
+```json
+[
+ {
+ "id": "group-translate",
+ "name": "Group Translate",
+ "version": "1.2.0",
+ "type": "extension",
+ "description": "Auto-translate group messages",
+ "author": "openwa-plugins",
+ "download": "https://github.com/openwa-plugins/group-translate/releases/download/v1.2.0/group-translate.zip",
+ "installed": true,
+ "installedVersion": "1.1.0",
+ "updateAvailable": true
+ }
+]
+```
+
+Returns `[]` when no `plugins.catalogUrl` is configured.
+
+**Errors:** `400` catalog fetch failed / not a JSON array · `401` · `403`
+
---
-#### List Templates
+#### GET /api/plugins/:id
-```http
-GET /api/sessions/:sessionId/templates
-```
+Get a single plugin by id.
-Returns all templates for the session, newest first.
+**Auth:** API key (ADMIN)
----
+**Path parameters**
-#### Get Template
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-```http
-GET /api/sessions/:sessionId/templates/:id
-```
+**Response** `200` — single `PluginDto` (same shape as the list element, secrets redacted).
-Returns `404 Not Found` when the template does not exist in the session.
+**Errors:** `401` · `403` · `404` `Plugin {id} not found`
---
-#### Update Template
+#### GET /api/plugins/:id/config-ui
-```http
-PUT /api/sessions/:sessionId/templates/:id
-```
+Serve a plugin's sandboxed config-UI entry HTML (for an iframe `srcdoc`).
-**Request Body:** any subset of `name`, `body`, `header`, `footer`.
+**Auth:** API key (ADMIN)
----
+**Path parameters**
-#### Delete Template
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-```http
-DELETE /api/sessions/:sessionId/templates/:id
-```
+**Response** `200` — raw HTML (not JSON). Headers: `Content-Type: text/html; charset=utf-8`, `Content-Security-Policy: sandbox`, `X-Content-Type-Options: nosniff`.
-**Response:** `204 No Content`.
+**Errors:** `401` · `403` · `404` plugin missing, no `configUi.entry`, file missing, or containment-check failure
---
-### 6.4.4 Contacts
+#### GET /api/plugins/:id/health
-#### Get All Contacts
+Check a plugin's health (delegates to the loader / sandboxed workers).
-```http
-GET /api/sessions/:sessionId/contacts
-```
+**Auth:** API key (ADMIN)
+
+**Path parameters**
-**Query parameters (optional):** `limit` — max items to return, clamped to `[1, 1000]` (default `1000`); `offset` — items to skip, for paging.
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
+
+**Response** `200`
-**Response (200 OK):**
```json
-[
- {
- "name": "John Doe",
- "pushName": "John",
- "isMyContact": true,
- "isBlocked": false
- }
-]
+{ "healthy": true }
```
+Internal failures are reported in-band as `{ "healthy": false, "message": "…" }` with HTTP 200.
+
+**Errors:** `401` · `403` · `404` unknown id
+
---
-#### Check Number Exists
+#### POST /api/plugins/install
-```http
-GET /api/sessions/:sessionId/contacts/check/:phone
-```
+Install a plugin from an uploaded `.zip` package.
-**Response (200 OK):**
-```json
-{
- "number": "628123456789",
- "exists": true,
- "whatsappId": "[email protected]"
-}
-```
+**Auth:** API key (ADMIN)
-> `whatsappId` is the engine's canonical WhatsApp ID for the number (and `null`
-> when `exists` is `false`). It is resolved by the engine, so it may be
-> normalized and differ from the submitted number's `@c.us` form (e.g. a `@lid`
-> identifier) — use it verbatim as the chat target rather than rebuilding it.
+**Request body** — `multipart/form-data` (no DTO)
----
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `file` | binary (`.zip`) | Yes | ≤ 5 MB; must contain a valid plugin manifest | Form field name is literally `file` |
-#### Get Profile Picture
+**Response** `201` — the newly installed `PluginDto`.
-```http
-GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
-```
+**Errors:** `400` no file / invalid package / install failed · `401` · `403` · `409` plugin id or directory already exists
-**Response (200 OK):**
-```json
-{
- "url": "https://pps.whatsapp.net/..."
-}
-```
+---
-#### Resolve a contact id to a phone number
+#### POST /api/plugins/install-url
-Resolve a contact identified by a WhatsApp privacy id (`@lid`) to its phone number. Pass the `@lid`
-JID as `:contactId`.
+Install a plugin by downloading its `.zip` from an HTTP(S) URL (SSRF-guarded fetch: host validated, redirects refused, size-capped at `plugins.downloadMaxBytes`, default 5 MB).
-```http
-GET /api/sessions/:sessionId/contacts/:contactId/phone
-```
+**Auth:** API key (ADMIN)
+
+**Request body** — `InstallFromUrlDto` (class-validated; extra fields → `400`)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute http(s) URL of the package |
-**Response (200 OK):**
```json
-{
- "contactId": "123456789@lid",
- "phone": "628123456789"
-}
+{ "url": "https://github.com/openwa-plugins/chat-flow/releases/download/v1.0.0/chat-flow.zip" }
```
-> **Best-effort.** `phone` is MSISDN digits when the account knows the mapping, or `null` otherwise —
-> `@lid` exists specifically to hide phone numbers, so a stranger you've never interacted with (or a
-> privacy-protected sender) won't resolve. This is a WhatsApp-engine limitation, not an OpenWA one.
+**Response** `201` — the newly installed `PluginDto`.
-To get this resolved automatically on each incoming message instead of calling the endpoint, see
-`RESOLVE_LID_TO_PHONE` under [message.received](#messagereceived).
+**Errors:** `400` invalid URL / download or package invalid · `401` · `403` · `409` already installed
---
-### 6.4.5 Groups
+#### POST /api/plugins/:id/enable
-#### Get All Groups
+Enable a plugin.
-```http
-GET /api/sessions/:sessionId/groups
-```
+**Auth:** API key (ADMIN)
+
+**Path parameters**
-**Query parameters (optional):** `limit` — max items to return, clamped to `[1, 1000]` (default `1000`); `offset` — items to skip, for paging.
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
+
+**Response** `200`
-**Response (200 OK):**
```json
-[
- {
- "name": "Family Group",
- "description": "Family chat",
- "participantsCount": 10,
- "createdAt": "2024-01-01T00:00:00.000Z"
- }
-]
+{ "success": true, "message": "Plugin enabled successfully" }
```
+Enable failures are returned in-band as `{ "success": false, "message": "…" }` (still HTTP 200).
+
+**Errors:** `401` · `403` · `404` unknown id
+
---
-#### Get Group Info
+#### POST /api/plugins/:id/disable
-```http
-GET /api/sessions/:sessionId/groups/:groupId
-```
+Disable a plugin.
-**Response (200 OK):**
-```json
-{
- "name": "Family Group",
- "description": "Family chat",
- "owner": "[email protected]",
- "participants": [
- {
- "isAdmin": true,
- "isSuperAdmin": true
- }
- ],
- "createdAt": "2024-01-01T00:00:00.000Z"
-}
-```
+**Auth:** API key (ADMIN)
----
+**Path parameters**
-#### Create Group
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-```http
-POST /api/sessions/:sessionId/groups
-```
+**Response** `200`
-**Request Body:**
```json
-{
- "name": "New Group",
- "participants": [
- ]
-}
+{ "success": true, "message": "Plugin disabled successfully" }
```
+**Errors:** `401` · `403` · `404` unknown id
+
---
-### 6.4.6 Webhooks
+#### PUT /api/plugins/:id/config
-#### Register Webhook
+Update a plugin's base configuration object.
-```http
-POST /api/sessions/:sessionId/webhooks
-```
+**Auth:** API key (ADMIN)
-**Request Body:**
-```json
-{
- "url": "https://your-server.com/webhook",
- "events": [
- "message.received",
- "message.sent",
- "message.ack",
- "session.status"
- ],
- "secret": "your-webhook-secret",
- "headers": {
- "X-Custom-Header": "value"
- },
- "filters": {
- "conditions": [
- { "field": "sender", "operator": "is", "value": ["[email protected]"] },
- { "field": "body", "operator": "contains", "value": "invoice" }
- ]
- }
-}
-```
+**Path parameters**
-**Smart filters (optional).** When `filters` is present, the webhook fires only if **all** conditions
-match (logical AND); a webhook with no filters behaves exactly as before. Conditions are evaluated per
-event before delivery and message-only fields are skipped for non-message events.
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-| Field | Kind | Operators | Notes |
-|-------|------|-----------|-------|
-| `sender`, `recipient`, `mentions` | id | `is`, `isNot` | Matched by engine-neutral `WaId`; a plain number or any dialect (`@c.us` / `@s.whatsapp.net` / `@lid`) matches the same contact. `value` is an array. |
-| `body` | text | `contains`, `equals` | Optional `caseSensitive` (default `false`). |
-| `type` | enum | `is`, `isNot` | `text` / `image` / `video` / `audio` / `voice` / `document` / `sticker` / `location` / `contact` / `revoked` / `unknown`. |
-| `fromMe`, `hasMedia`, `isGroup` | boolean | `is` | `value` is a boolean. |
+**Request body** — `PluginConfigDto` (class-validated; body must be exactly `{config:{…}}`)
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `config` | object | Yes | `@IsObject()` | Whole config object. Masked/sentinel secret values mean "unchanged" and are restored from the stored config |
-**Response (201 Created):**
```json
-{
- "id": "wh_xyz789",
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.sent"],
- "active": true,
- "createdAt": "2025-02-02T10:00:00.000Z"
-}
+{ "config": { "apiKey": "sk-...", "replyDelayMs": 1500 } }
```
----
-
-#### List Webhooks
+**Response** `200`
-```http
-GET /api/sessions/:sessionId/webhooks
+```json
+{ "success": true, "message": "Plugin configuration updated" }
```
----
-
-#### Delete Webhook
+Update failures are returned in-band as `{ "success": false, "message": "…" }` (HTTP 200).
-```http
-DELETE /api/sessions/:sessionId/webhooks/:webhookId
-```
+**Errors:** `400` extra top-level field · `401` · `403` · `404` unknown id
---
-### 6.4.7 Health
-
-#### Basic Health Check
+#### PUT /api/plugins/:id/config/:sessionId
-```http
-GET /health
-```
+Set (or clear) a plugin config override for a specific session.
-**Response (200 OK):**
-```json
-{
- "status": "ok",
- "timestamp": "2026-02-02T10:30:00Z"
-}
-```
+**Auth:** API key (ADMIN)
-The basic endpoint is public.
+**Path parameters**
-#### Readiness / Liveness
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
+| `sessionId` | string | Session the override applies to |
-```http
-GET /api/health/ready
-GET /api/health/live
-```
+**Request body** — `PluginConfigDto`
-`/api/health/ready` reports whether the service is ready to receive traffic;
-`/api/health/live` reports process liveness. (There is no `/health/detailed` route.)
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `config` | object | Yes | `@IsObject()` | Per-session override slice. Empty `{}` clears the override (falls back to base config). Masked secrets restored from the existing per-session value |
-**Response (200 OK):**
```json
-{
- "status": "ok",
- "details": { "database": { "status": "up" } }
-}
+{ "config": { "replyDelayMs": 3000 } }
```
-## 6.4 Webhook Events
-
-### Event Structure
+**Response** `200`
```json
-{
- "event": "message.received",
- "timestamp": "2025-02-02T10:00:00.000Z",
- "sessionId": "sess_abc123",
- "deliveryId": "dlv_550e8400e29b41d4a716446655440000",
- "idempotencyKey": "msg_628123456789_1706868000000",
- "data": {},
- "signature": "sha256=..."
-}
+{ "success": true, "message": "Plugin configuration for session session-1 updated" }
```
-### Webhook Idempotency
+**Errors:** `400` plugin is global (not session-scoped) / extra field · `401` · `403` · `404` unknown id
-OpenWA provides an idempotency mechanism to prevent duplicate processing on the client side.
+---
-#### Delivery Semantics
+#### PUT /api/plugins/:id/sessions
-Webhook delivery is **at-least-once**. WhatsApp engines can re-fire an event for a single message, and
-failed deliveries are retried, so a consumer can receive the same event more than once. **Design your
-handler to be idempotent**, keyed on the `X-OpenWA-Idempotency-Key` header (or the `idempotencyKey`
-field) — that key is content-based, so every duplicate of the same message carries the identical value;
-prefer it over hashing the payload yourself.
+Set which sessions a session-scoped plugin is activated for.
-As a safety net, OpenWA de-duplicates inbound `message.received` **server-side**: a re-fired event for a
-message already persisted is dropped before dispatch, so one registered webhook normally receives each
-inbound message once. This guard is best-effort defense-in-depth and does not remove the need for
-consumer-side idempotency on the key above.
+**Auth:** API key (ADMIN) · **Scope:** session-scoped (the key's `allowedSessions` is enforced)
-#### Idempotency Headers & Fields
+**Path parameters**
-| Field/Header | Description |
-|--------------|-------------|
-| `deliveryId` | Unique ID for each delivery attempt |
-| `idempotencyKey` | Unique key per event (same across retries) |
-| `X-OpenWA-Delivery-Id` | Header carrying the delivery ID |
-| `X-OpenWA-Idempotency-Key` | Header carrying the idempotency key |
-| `X-OpenWA-Retry-Count` | Retry attempt number (0 = first attempt) |
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-#### Idempotency Key Format
+**Request body** — `PluginSessionsDto` (class-validated)
-```
-Keys are content-based and do NOT include a timestamp, so a replayed/retried event with an
-identical payload produces the same key for correct de-duplication.
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `sessions` | string[] | Yes | `@IsArray()`, `@IsString({ each:true })` | Session ids to activate for. `["*"]` = all, `[]` = none |
-Examples:
-- message.received: msg_{sessionId}_{messageId}
-- message.sent: msg_{sessionId}_{messageId}
-- message.ack: ack_{sessionId}_{messageId}_{status}
-- message.failed: failed_{sessionId}_{messageId}_{status}
-- message.reaction: react_{sessionId}_{messageId}_{senderId}
-- session.status: sess_{sessionId}_{status}
-- group.join: grp_{groupId}_{participantId}_join
+```json
+{ "sessions": ["*"] }
```
-#### Client-Side Idempotency Implementation
-
-```typescript
-// Recommended: Store processed idempotency keys
-const processedEvents = new Map<string, number>(); // key -> timestamp
-const IDEMPOTENCY_TTL = 24 * 60 * 60 * 1000; // 24 hours
+**Response** `200` — the updated `PluginDto` (reflecting the new `activeSessions`).
-async function handleWebhook(req: Request, res: Response) {
- const idempotencyKey = req.headers['x-openwa-idempotency-key'] as string;
- const retryCount = parseInt(req.headers['x-openwa-retry-count'] as string) || 0;
+A session-restricted key requesting `"*"` or out-of-scope sessions gets `403 API key not authorized for session(s): …`.
- // Check if already processed
- if (processedEvents.has(idempotencyKey)) {
- console.log(`Duplicate event ignored: ${idempotencyKey} (retry: ${retryCount})`);
- return res.status(200).json({ status: 'duplicate_ignored' });
- }
+**Errors:** `400` plugin is global · `401` · `403` key not authorized for requested sessions · `404` unknown id
- try {
- // Process the webhook
- await processEvent(req.body);
+---
- // Mark as processed
- processedEvents.set(idempotencyKey, Date.now());
+#### POST /api/plugins/:id/update
- // Cleanup old entries periodically
- cleanupOldEntries();
+Update an installed plugin in place from a URL, preserving config + enabled state (old directory backed up and restored on failure).
- return res.status(200).json({ status: 'processed' });
- } catch (error) {
- // Return 500 to trigger retry
- return res.status(500).json({ error: error.message });
- }
-}
+**Auth:** API key (ADMIN)
-function cleanupOldEntries() {
- const now = Date.now();
- for (const [key, timestamp] of processedEvents.entries()) {
- if (now - timestamp > IDEMPOTENCY_TTL) {
- processedEvents.delete(key);
- }
- }
-}
-```
+**Path parameters**
-#### Database-Based Idempotency (Production)
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id (must match the package's manifest id) |
-```sql
--- Create idempotency table
-CREATE TABLE webhook_idempotency (
- idempotency_key VARCHAR(255) PRIMARY KEY,
- processed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- response_data JSONB
-);
+**Request body** — `InstallFromUrlDto` (class-validated)
--- Index for cleanup
-CREATE INDEX idx_webhook_idempotency_processed_at
- ON webhook_idempotency(processed_at);
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute http(s) URL of the new `.zip` (SSRF-guarded download) |
--- Cleanup job (run daily)
-DELETE FROM webhook_idempotency
-WHERE processed_at < NOW() - INTERVAL '24 hours';
+```json
+{ "url": "https://example.com/plugins/chat-flow-1.1.0.zip" }
```
-```typescript
-// Production implementation with PostgreSQL
-async function handleWebhookWithDB(req: Request, res: Response) {
- const idempotencyKey = req.headers['x-openwa-idempotency-key'] as string;
+**Response** `201` — the updated `PluginDto`.
- try {
- // Try to insert (will fail if duplicate)
- await db.query(`
- INSERT INTO webhook_idempotency (idempotency_key)
- VALUES ($1)
- ON CONFLICT (idempotency_key) DO NOTHING
- RETURNING idempotency_key
- `, [idempotencyKey]);
+**Errors:** `400` download/package invalid, manifest id mismatch, or built-in plugin · `401` · `403` · `404` unknown id
- const result = await db.query(
- 'SELECT 1 FROM webhook_idempotency WHERE idempotency_key = $1',
- [idempotencyKey]
- );
+---
- if (result.rowCount === 0) {
- // Already processed
- return res.status(200).json({ status: 'duplicate_ignored' });
- }
+#### DELETE /api/plugins/:id
- // Process the webhook
- await processEvent(req.body);
+Uninstall a plugin and delete its files. Built-in plugins are protected.
- return res.status(200).json({ status: 'processed' });
- } catch (error) {
- return res.status(500).json({ error: error.message });
- }
-}
-```
+**Auth:** API key (ADMIN)
-### Event Types
+**Path parameters**
-```mermaid
-flowchart TB
- subgraph Events["Webhook Events"]
- direction TB
-
- subgraph Message["Message Events"]
- MR[message.received]
- MS[message.sent]
- MA[message.ack]
- MRV[message.revoked]
- end
-
- subgraph Session["Session Events"]
- SS[session.status]
- SQ[session.qr]
- SA[session.authenticated]
- SD[session.disconnected]
- end
-
- subgraph Group["Group Events"]
- GJ[group.join]
- GL[group.leave]
- GU[group.update]
- end
- end
-```
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Plugin id |
-### message.received
+**Response** `200`
```json
-{
- "event": "message.received",
- "timestamp": "2025-02-02T10:00:00.000Z",
- "sessionId": "sess_abc123",
- "data": {
- "id": "[email protected]_3EB0ABC123",
- "from": "[email protected]",
- "body": "Hello!",
- "type": "text",
- "waTimestamp": 1706868000,
- "timestamp": "2025-02-02T10:00:00.000Z",
- "isGroup": false,
- "hasMedia": false,
- "contact": {
- "number": "628123456789",
- "name": "John Doe",
- "pushName": "John",
- "shortName": "John",
- "type": "in",
- "isMyContact": true,
- "isWAContact": true,
- "isBusiness": false,
- "isEnterprise": false,
- "verifiedName": null,
- "verifiedLevel": 0,
- "isBlocked": false,
- "labels": []
- }
- }
-}
+{ "success": true, "message": "Plugin uninstalled successfully" }
```
-> **`contact` fields (opt-in via `WEBHOOK_CONTACT_DETAILS`).** By default the `contact` object carries
-> only `name` and `pushName`. Set `WEBHOOK_CONTACT_DETAILS=true` to expose the full set shown above
-> (`id`, `number`, `shortName`, `type`, the business flags, `isBlocked`, `labels`, …). All fields are
-> optional and best-effort, read synchronously from the WhatsApp Web contact cache already fetched for
-> the message — **no extra WhatsApp API calls** are made. Profile picture and about/status are
-> intentionally not included (they require per-message network calls and risk rate-limiting/ban). For
-> an `@lid` privacy-id sender, `number` may be empty; use the top-level `senderPhone` field for the
-> resolved phone number.
+Note: this DELETE returns `200` with a body (not the usual `204`).
-> **Optional `senderPhone` (`@lid` resolution).** When a sender is identified by a WhatsApp privacy id
-> (`from`/`author` ends in `@lid`) and `RESOLVE_LID_TO_PHONE=true` is set, the payload also carries a
-> best-effort `senderPhone` (MSISDN digits, or `null` when the engine can't map it). Off by default
-> because it adds a per-sender lookup (results are cached). See also the on-demand
-> [resolve endpoint](#resolve-a-contact-id-to-a-phone-number). (#263)
+**Errors:** `400` cannot uninstall (e.g. built-in) · `401` · `403` · `404` unknown id
-### message.ack
+---
-```json
-{
- "event": "message.ack",
- "timestamp": "2025-02-02T10:00:00.000Z",
- "sessionId": "sess_abc123",
- "data": {
- "id": "[email protected]_3EB0ABC123",
- "messageId": "[email protected]_3EB0ABC123",
- "status": "read",
- "ack": 3
- }
-}
-```
+#### POST /mcp
+
+MCP Streamable-HTTP / JSON-RPC 2.0 transport that exposes the agent-tool registry over the Model Context Protocol. **This is a transport, not a REST resource** — there is no NestJS controller, no DTO, and no `{success,data}` shape.
-Read the engine-neutral **`status`** field — it is the canonical delivery state and is identical
-across engines. The legacy **`ack`** integer is **deprecated**, derived from `status` for backward
-compatibility only (a non-whatsapp-web.js engine still reports the same `status`).
+**Auth:** API key — sent as `X-Api-Key: <key>` **or** `Authorization: Bearer <key>`. Auth is enforced **per tool call** inside the MCP layer (not by the global Nest guard), so an auth failure surfaces in-band, not as an HTTP `401`.
-| `status` | `ack` (deprecated) | Description |
-|----------|--------------------|-------------|
-| `pending` | 0 | Queued, not yet sent to the server |
-| `sent` | 1 | Sent to the server |
-| `delivered` | 2 | Delivered to the recipient's device |
-| `read` | 3 | Read by the recipient (a played voice/video note also reports `read`) |
-| `failed` | -1 | Delivery failed (also dispatched as a separate `message.failed` event) |
+Key facts:
+- **Path is exactly `POST /mcp` — no `/api` prefix.** The global `api` prefix applies only to Nest controllers; this route is mounted straight on Express.
+- Gated by **`MCP_ENABLED=true`**. When off, the module/route is never mounted and `POST /mcp` returns `404`.
+- `MCP_READONLY=true` registers only read-tier tools. Per-key sliding-window rate limit: `MCP_RATE_LIMIT_MAX` (default 60) per `MCP_RATE_LIMIT_WINDOW_MS` (default 60000).
+- Stateless transport (no SSE/session id for normal calls).
-### session.status
+**Request body** — JSON-RPC 2.0 envelope (validated by the MCP SDK, **not** the Nest ValidationPipe)
+
+| Field | Type | Required | Description |
+| --- | --- | --- | --- |
+| `jsonrpc` | string | Yes | Must be `"2.0"` |
+| `id` | string \| number \| null | No | Request id echoed back; null/absent for notifications |
+| `method` | string | Yes | `initialize`, `tools/list`, `tools/call`, plus MCP lifecycle methods. Unknown → JSON-RPC error `-32601` |
+| `params` | object | No | Method-specific. For `tools/call`: `{ name, arguments }` where `arguments` must match the tool's zod `inputSchema` |
```json
-{
- "event": "session.status",
- "timestamp": "2025-02-02T10:00:00.000Z",
- "sessionId": "sess_abc123",
- "data": {
- "status": "CONNECTED",
- "phoneNumber": "628123456789"
- }
-}
+{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "session_send_text", "arguments": { "sessionId": "default", "to": "6281234567890", "text": "Hello from MCP" } } }
```
-## 6.5 Webhook Signature Verification
-
-```javascript
-const crypto = require('crypto');
+**Response** `200` — JSON-RPC 2.0 envelope
-function verifyWebhookSignature(payload, signature, secret) {
- const expected = 'sha256=' + crypto
- .createHmac('sha256', secret)
- .update(JSON.stringify(payload))
- .digest('hex');
-
- return crypto.timingSafeEqual(
- Buffer.from(signature),
- Buffer.from(expected)
- );
-}
-
-// Usage in Express
-app.post('/webhook', (req, res) => {
- const signature = req.headers['x-openwa-signature'];
-
- if (!verifyWebhookSignature(req.body, signature, WEBHOOK_SECRET)) {
- return res.status(401).send('Invalid signature');
- }
-
- // Process webhook...
- res.status(200).send('OK');
-});
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 3,
+ "result": { "content": [ { "type": "text", "text": "{\"success\":true,\"messageId\":\"…\"}" } ] }
+}
```
-## 6.6 Rate Limiting
+For `tools/call` the result is an MCP `CallToolResult` (`content` array of `text` or embedded base64 `resource` items — payloads over 4096 bytes become a `resource`). **Tool-level failures are returned in-band as `CallToolResult` with `isError:true`** (HTTP stays 200), including missing/invalid API key (`name:'UnauthorizedException'`) and rate-limit hits (`message:'MCP rate limit exceeded'`).
-| Endpoint Category | Rate Limit |
-|-------------------|------------|
-| Session management | 10 req/min |
-| Send message | 60 req/min |
-| Read operations | 120 req/min |
-| Webhook management | 10 req/min |
+**Errors:** in-band JSON-RPC errors `-32601` (unknown method), `-32602` (invalid params / unknown tool), `-32700` (parse error), all at HTTP 200 · `500` only if the transport throws before headers are sent · `404` when `MCP_ENABLED` is not `true`
-**Rate Limit Headers:**
-```http
-X-RateLimit-Limit: 60
-X-RateLimit-Remaining: 45
-X-RateLimit-Reset: 1706868060
-```
+> The full catalog of MCP tools (names, tiers, schemas) is documented separately — see **doc 24, MCP Integration**. This section documents only the transport endpoint.
-## 6.7 WebSocket Real-time API
+## 6.5 Real-time API (WebSocket)
-In addition to the REST API, OpenWA provides WebSocket for real-time updates.
+Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.
-> [!IMPORTANT]
-> The WebSocket format below is **canonical**. Client/server implementations must follow this `WSRequest/WSResponse` structure.
+### Connecting
-### Connection
+Point a Socket.IO client at `<host>:2785` with path-less namespace `/events`:
-**WebSocket URL:**
```
-wss://your-domain.com/ws
-wss://your-domain.com/ws?apiKey=your-api-key # browser fallback
+ws://<host>:2785/events (or wss:// behind TLS)
```
-**Header (recommended for non-browser clients):**
-```http
-X-API-Key: your-api-key
-```
+The client must authenticate during the Socket.IO handshake. Three sources are accepted, in this precedence order:
-```javascript
-// Browser (query param)
-const ws = new WebSocket('wss://your-domain.com/ws?apiKey=your-api-key');
-```
+1. **Handshake `auth` (recommended)** — `io(url, { auth: { apiKey } })`. Not written to URLs or access logs.
+2. **Header** — `x-api-key: <key>`.
+3. **Query param (deprecated fallback)** — `?apiKey=<key>`. The key leaks into access logs; avoid in production.
-### Message Protocol
+If no key is supplied, or validation fails, the server emits an `error` message (`code: "UNAUTHORIZED"`) on the `message` event and immediately disconnects the socket. CORS for the namespace reuses the HTTP `CORS_ORIGINS` policy (dev allows any origin; production uses the allowlist).
-All messages use JSON format:
+### Protocol — client → server
-```typescript
-// Client -> Server (Request)
-interface WSRequest {
- type: 'subscribe' | 'unsubscribe' | 'ping';
- payload?: {
- sessionId?: string;
- events?: string[];
- };
- requestId?: string; // For tracking responses
-}
+All client commands are sent on the Socket.IO event named **`message`** using a single **flat** envelope:
-// Server -> Client (Response/Event)
-interface WSResponse {
- type: 'subscribed' | 'unsubscribed' | 'event' | 'error' | 'pong';
- payload: any;
- requestId?: string;
- timestamp: string; // ISO 8601 UTC
-}
+```
+{ type, sessionId, events, requestId }
```
-### Subscribe / Unsubscribe
+| Field | Type | Applies to | Description |
+| --- | --- | --- | --- |
+| `type` | `"subscribe" \| "unsubscribe" \| "ping"` | all | Command discriminator. |
+| `sessionId` | string | subscribe, unsubscribe | A session id, or `"*"` for all sessions. |
+| `events` | string[] | subscribe | Event names to subscribe to, or `["*"]` for all. |
+| `requestId` | string (optional) | all | Echoed back on the matching server reply for correlation. |
-```javascript
-// Subscribe to specific session
-ws.send(JSON.stringify({
- type: 'subscribe',
- payload: {
- sessionId: 'sess_abc123',
- events: ['message.received', 'message.ack', 'session.status']
- },
- requestId: 'req_001'
-}));
-
-// Subscribe to all sessions
-ws.send(JSON.stringify({
- type: 'subscribe',
- payload: {
- sessionId: '*',
- events: ['*']
- }
-}));
+A `ping` carries only `{ type: "ping", requestId? }`.
-// Unsubscribe
-ws.send(JSON.stringify({
- type: 'unsubscribe',
- payload: { sessionId: 'sess_abc123' }
-}));
-```
+### Protocol — server → client
+
+All server replies and pushed events also arrive on the Socket.IO event named **`message`**.
+
+Command acknowledgements are **flat** and include an ISO-8601 `timestamp`:
-### Event Types
+```json
+{ "type": "subscribed", "sessionId": "main", "events": ["message.received", "session.status"], "requestId": "r1", "timestamp": "2026-06-25T10:00:00.000Z" }
+```
-| Event | Description |
-|-------|-------------|
-| `session.status` | Session status changed (INITIALIZING, SCAN_QR, CONNECTING, CONNECTED, DISCONNECTED, FAILED) |
-| `session.qr` | New QR code generated |
-| `session.authenticated` | Session authenticated |
-| `session.disconnected` | Session disconnected |
-| `message.received` | New incoming message |
-| `message.sent` | Message sent successfully |
-| `message.ack` | Message acknowledgment (delivered, read) |
-| `message.revoked` | Message was deleted |
-| `message.reaction` | A reaction was added, changed, or removed on a message |
-| `group.join` | Group join event |
-| `group.leave` | Group leave event |
-| `group.update` | Group info updated |
+```json
+{ "type": "unsubscribed", "sessionId": "main", "requestId": "r2", "timestamp": "2026-06-25T10:00:01.000Z" }
+```
-### Event Payload Examples
+```json
+{ "type": "pong", "requestId": "r3", "timestamp": "2026-06-25T10:00:02.000Z" }
+```
-**session.qr:**
```json
-{
- "type": "event",
- "payload": {
- "event": "session.qr",
- "sessionId": "sess_abc123",
- "data": {
- "code": "2@ABC123XYZ...",
- "image": "data:image/png;base64,..."
- }
- },
- "timestamp": "2026-02-02T10:00:00.000Z"
-}
+{ "type": "error", "code": "FORBIDDEN_SESSION", "message": "API key is not authorized for this session", "requestId": "r1", "timestamp": "2026-06-25T10:00:00.000Z" }
```
-**message.received:**
+Live events are pushed as a **nested** envelope (note: `data` is under `payload`, and there is no `requestId`):
+
```json
{
"type": "event",
+ "timestamp": "2026-06-25T10:00:05.000Z",
"payload": {
"event": "message.received",
- "sessionId": "sess_abc123",
- "data": {
- "messageId": "[email protected]_3EB0ABC",
- "chatId": "[email protected]",
- "from": "[email protected]",
- "type": "text",
- "body": "Hello!",
- "waTimestamp": 1706868000,
- "timestamp": "2026-02-02T10:00:00.000Z",
- "isGroup": false
- }
- },
- "timestamp": "2026-02-02T10:00:00.000Z"
+ "sessionId": "main",
+ "data": { "id": "ABCD1234", "from": "[email protected]", "body": "hi", "timestamp": 1750000000 }
+ }
}
```
-### Keep-Alive
+Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, and `FORBIDDEN_SESSION`.
+
+### Subscribable events
+
+`events` accepts the wildcard `"*"` (all of the below) or any of these exact names:
-```javascript
-// Client should send ping every 30 seconds
-setInterval(() => {
- ws.send(JSON.stringify({ type: 'ping', requestId: 'ping-001' }));
-}, 30000);
+```
+message.received
+message.sent
+message.ack
+message.revoked
+message.reaction
+session.status
+session.qr
+session.authenticated
+session.disconnected
```
-### Quick Client Example (JavaScript)
+A subscribe request whose `events` array contains no recognized name (after filtering) is rejected with `INVALID_EVENTS`. Unknown names mixed with valid ones are silently dropped; the `subscribed` reply echoes only the accepted events.
-```javascript
-const ws = new WebSocket('ws://localhost:2785/ws?apiKey=your-api-key');
-let pingInterval = null;
+> **`group.*` events are NOT subscribable on the socket.** They have no engine emit source and are never delivered over Socket.IO (they remain reserved only on the webhook side).
-ws.onopen = () => {
- ws.send(JSON.stringify({
- type: 'subscribe',
- payload: {
- sessionId: 'sess_abc123',
- events: ['message.received', 'session.status']
- },
- requestId: 'req_001'
- }));
+### Wildcards and scoping
+
+- **`sessionId: "*"`** subscribes to every session; **`events: ["*"]`** subscribes to every subscribable event. They combine (e.g. `"*"` + `["*"]` = every event of every session).
+- The API key is **re-validated on every `subscribe`** (not just at connect), so a key revoked or expired mid-connection is caught — the server replies `UNAUTHORIZED` and disconnects.
+- **Per-key session scope is enforced** against the fresh key: a key restricted via `allowedSessions` may NOT subscribe to `"*"` and may NOT subscribe to a session outside its allowlist — either is rejected with `FORBIDDEN_SESSION`. An unrestricted key (no `allowedSessions`) may subscribe to anything, including `"*"`.
+
+### Example (socket.io-client)
- pingInterval = setInterval(() => {
- ws.send(JSON.stringify({ type: 'ping', requestId: `ping_${Date.now()}` }));
- }, 30000);
-};
+```js
+import { io } from 'socket.io-client';
+
+const socket = io('ws://localhost:2785/events', {
+ auth: { apiKey: process.env.OPENWA_API_KEY },
+});
+
+socket.on('connect', () => {
+ socket.emit('message', {
+ type: 'subscribe',
+ sessionId: 'main',
+ events: ['message.received', 'message.ack', 'session.status'],
+ requestId: 'sub-1',
+ });
+});
-ws.onmessage = (event) => {
- const msg = JSON.parse(event.data);
+socket.on('message', (msg) => {
if (msg.type === 'event') {
- console.log('Event:', msg.payload.event, msg.payload.data);
+ console.log(`[${msg.payload.event}]`, msg.payload.sessionId, msg.payload.data);
+ } else {
+ console.log('reply:', msg); // subscribed | unsubscribed | pong | error
}
-};
-
-ws.onclose = () => {
- if (pingInterval) clearInterval(pingInterval);
-};
+});
```
-### Error Handling
+## 6.6 Webhook Events & Delivery Semantics
+
+Every registered webhook receives an HTTP `POST` with a JSON body of this shape:
```json
{
- "type": "error",
- "payload": {
- "code": "SESSION_NOT_FOUND",
- "message": "Session sess_xxx not found"
- },
- "requestId": "req_001",
- "timestamp": "2026-02-02T10:00:00.000Z"
+ "event": "message.received",
+ "timestamp": "2026-02-02T10:00:00.000Z",
+ "sessionId": "my-session",
+ "idempotencyKey": "msg_my-session_3EB0ABC123",
+ "deliveryId": "dlv_550e8400-e29b-41d4-a716-446655440000",
+ "data": { }
}
```
-## 6.8 OpenAPI/Swagger
+`event`, `timestamp` (ISO-8601 dispatch time), `sessionId`, `idempotencyKey`, and `deliveryId` are always present; `data` holds the event-specific payload. The same values are mirrored into request headers (below). The HMAC `signature` is **not** in the body — it travels in the `X-OpenWA-Signature` header.
-Swagger UI tersedia di:
-```
-http://localhost:2785/api/docs
-```
+### Event catalog
-OpenAPI JSON:
-```
-http://localhost:2785/api/docs-json
-```
+These are the events OpenWA actually emits. A webhook is registered with an `events` list; an event is delivered to a webhook when its `events` array includes the event name or `"*"`.
-## 6.9 SDK & Code Examples
+| Event | When it fires | `data` payload sketch |
+| --- | --- | --- |
+| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders) |
+| `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` |
+| `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it |
+| `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |
+| `message.revoked` | A message is deleted/recalled | The engine's revoked-message object (e.g. `{ id, … }`) |
+| `message.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot; `reaction` is empty when removed |
+| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` (raw QR string) |
+| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
+| `session.disconnected` | The session disconnects | `{ sessionId, reason }` |
+| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `failed` |
-### Official SDKs (Coming Soon)
+> **Reserved but not emitted.** `group.join`, `group.leave`, and `group.update` are accepted in a webhook's `events` list (and have reserved idempotency-key formats), but **no code path currently emits them** — registering for them is harmless but they will never be delivered. Likewise there is **no** `contact.update` or `presence.update` event.
-| Language | Package | Status |
-|----------|---------|--------|
-| JavaScript/TypeScript | `@openwa/sdk` | 🔜 Planned |
-| Python | `openwa-python` | 🔜 Planned |
-| PHP | `openwa/php-sdk` | 🔜 Planned |
-| Go | `openwa-go` | 🔜 Planned |
+### Delivery semantics — at-least-once
-### cURL Examples
+Webhook delivery is **at-least-once**. A consumer can legitimately receive the same logical event more than once because:
-```bash
-# Create session
-curl -X POST http://localhost:2785/api/sessions \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-api-key" \
- -H "X-Request-ID: req_1706868000000" \
- -d '{"name": "my-bot"}'
+- The underlying WhatsApp engine can re-fire an event for a single message.
+- A failed delivery (non-2xx response, timeout, or network error) is retried.
+
+**Design your handler to be idempotent**, keyed on the `X-OpenWA-Idempotency-Key` header (see below). As a server-side safety net, OpenWA de-duplicates inbound `message.received` before dispatch (a re-fired event for an already-persisted message is dropped), so one webhook normally sees each inbound message once — but this is best-effort defense-in-depth and does not remove the need for consumer-side idempotency.
+
+### HMAC signature
+
+When a webhook is registered with a `secret`, each delivery carries:
-# Send text message
-curl -X POST http://localhost:2785/api/sessions/sess_abc123/messages/send-text \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-api-key" \
- -H "X-Request-ID: req_1706868000001" \
- -d '{
- "chatId": "[email protected]",
- "text": "Hello from OpenWA!"
- }'
-
-# Send image
-curl -X POST http://localhost:2785/api/sessions/sess_abc123/messages/send-image \
- -H "Content-Type: application/json" \
- -H "X-API-Key: your-api-key" \
- -H "X-Request-ID: req_1706868000002" \
- -d '{
- "chatId": "[email protected]",
- "image": {"url": "https://example.com/image.jpg"},
- "caption": "Check this out!"
- }'
+```
+X-OpenWA-Signature: sha256=<hex>
```
-### JavaScript/Node.js Example
+The hex is an HMAC-SHA256 computed over the **raw JSON request body** (exactly the bytes sent) using the webhook's `secret`. Verify by recomputing over the raw body — not over a re-serialized parse — and compare in constant time:
```javascript
-const axios = require('axios');
-
-const api = axios.create({
- baseURL: 'http://localhost:2785/api',
- headers: {
- 'X-API-Key': 'your-api-key',
- 'Content-Type': 'application/json',
- 'X-Request-ID': `req_${Date.now()}`
- }
-});
+const crypto = require('crypto');
-// Send message
-async function sendMessage(sessionId, chatId, text) {
- const response = await api.post(
- `/sessions/${sessionId}/messages/send-text`,
- { chatId, text }
- );
- return response.data;
-}
-
-// Usage
-sendMessage('sess_abc123', '[email protected]', 'Hello!')
- .then(result => console.log('Sent:', result.messageId))
- .catch(err => console.error('Error:', err.response?.data));
-```
-
-### Python Example
-
-```python
-import time
-import requests
-
-class OpenWA:
- def __init__(self, base_url, api_key):
- self.base_url = base_url
- self.headers = {
- 'X-API-Key': api_key,
- 'Content-Type': 'application/json',
- 'X-Request-ID': f'req_{int(time.time() * 1000)}'
- }
-
- def send_text(self, session_id, chat_id, text):
- response = requests.post(
- f'{self.base_url}/sessions/{session_id}/messages/send-text',
- headers=self.headers,
- json={'chatId': chat_id, 'text': text}
- )
- return response.json()
-
- def send_image(self, session_id, chat_id, image_url, caption=None):
- response = requests.post(
- f'{self.base_url}/sessions/{session_id}/messages/send-image',
- headers=self.headers,
- json={
- 'chatId': chat_id,
- 'image': {'url': image_url},
- 'caption': caption
- }
- )
- return response.json()
-
-# Usage
-client = OpenWA('http://localhost:2785/api', 'your-api-key')
-result = client.send_text('sess_abc123', '[email protected]', 'Hello from Python!')
-print(f"Message ID: {result['messageId']}")
-```
-
-### WebSocket Client Example (JavaScript)
+function verify(rawBody, header, secret) {
+ const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
+ return crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
+}
+```
-```javascript
-const ws = new WebSocket('ws://localhost:2785/ws?apiKey=your-api-key');
-let pingInterval = null;
+If no `secret` is configured the `X-OpenWA-Signature` header is omitted entirely.
-ws.onopen = () => {
- ws.send(JSON.stringify({
- type: 'subscribe',
- payload: {
- sessionId: 'sess_abc123',
- events: ['message.received', 'session.status']
- },
- requestId: 'req_001'
- }));
+### Idempotency & delivery headers
- pingInterval = setInterval(() => {
- ws.send(JSON.stringify({ type: 'ping', requestId: `ping_${Date.now()}` }));
- }, 30000);
-};
+Every delivery includes:
-ws.onmessage = (event) => {
- const msg = JSON.parse(event.data);
- if (msg.type === 'event') {
- console.log('Event:', msg.payload.event, msg.payload.data);
- }
-};
+| Header | Meaning |
+| --- | --- |
+| `X-OpenWA-Event` | The event name (mirrors `event`) |
+| `X-OpenWA-Idempotency-Key` | Content-derived key; **stable across retries** of the same occurrence — dedupe on this |
+| `X-OpenWA-Delivery-Id` | A fresh `dlv_<uuid>` generated **per delivery** (differs per retry and per webhook) — for tracing, not dedup |
+| `X-OpenWA-Retry-Count` | Retry attempt number (`0` = first attempt) |
+| `X-OpenWA-Signature` | HMAC (only when a secret is set) |
-ws.onclose = () => {
- if (pingInterval) clearInterval(pingInterval);
-};
-```
----
+**Idempotency key derivation.** The key is content-derived so duplicates of the same logical event collapse to one value:
+
+- `message.received` / `message.sent`: `msg_{sessionId}_{messageId}`
+- `message.ack`: `ack_{sessionId}_{messageId}_{status}`
+- `message.failed`: `failed_{sessionId}_{messageId}_{status}`
+- `message.revoked`: `rev_{sessionId}_{messageId}`
+- `message.reaction`: `react_{sessionId}_{messageId}_{senderId}_{occurredAt}`
+- `session.qr`: `qr_{sessionId}_{hash(qr)}`
+- `session.status`: `sess_{sessionId}_{status}_{occurredAt}`
+- `session.authenticated`: `auth_{sessionId}_{hash(data)}_{occurredAt}`
+- `session.disconnected`: `disc_{sessionId}_{hash(reason)}_{occurredAt}`
+
+Recurring lifecycle events (and `message.reaction`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji — so they are salted with an `occurredAt` timestamp captured **once per dispatch and reused across that dispatch's retries**. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.
+
+### Retries with exponential backoff
-<div align="center">
+When the queue is enabled, a non-2xx response, timeout (`WEBHOOK_TIMEOUT`, default `10000` ms), or network error schedules a retry. The number of attempts comes from the webhook's `retryCount` (default `3`) and the delay grows **exponentially** from a base of `WEBHOOK_RETRY_DELAY` (default `5000` ms). Each retry reuses the same `idempotencyKey` and increments `X-OpenWA-Retry-Count`. When the queue is disabled, delivery is direct with the same retry budget applied inline.
-[← 05 - Database Design](./05-database-design.md) · [Documentation Index](./README.md) · [Next: 07 - API Collection →](./07-api-collection.md)
+### SSRF guard on registration
-</div>
+Webhook URLs are validated at **registration time**, not just at delivery. When SSRF protection is enabled (the default), creating or updating a webhook with a URL that resolves to a private/internal/loopback address is rejected synchronously with `400 Bad Request` instead of failing silently later at delivery. The `SSRF_ALLOWED_HOSTS` escape-hatch applies equally to registration and delivery. Operator-supplied custom headers that target reserved names (`Content-Type` or any `X-OpenWA-*`) are stripped, so a webhook config cannot forge the signature, event, or idempotency headers.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 42623a8bd..ec1e78786 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -2,1302 +2,1412 @@
## 07.1 Overview
-This document provides a complete collection of OpenWA API endpoints with request/response examples for each endpoint. It can be used as a quick reference or imported into tools such as Postman, Insomnia, or Bruno.
+This collection gives a runnable cURL for every OpenWA REST endpoint. The examples assume two environment variables — set them once and reuse them:
-### Base URL
-
-```
-Development: http://localhost:2785
-Production: https://api.your-domain.com
+```bash
+export BASE=http://localhost:2785
+export API_KEY=owa_k1_your-api-key-here
```
+(For the metrics endpoint also `export METRICS_TOKEN=...`.)
+
### Authentication
-All endpoints (except `/health`) require an API Key:
+Every request carries the key in the `X-API-Key` header — REST auth is **header-only**, an `?apiKey=` query value is not accepted. Routes that mutate state need an `operator` key; API-key and settings management need an `admin` key; read-only routes accept any valid key. The metrics endpoint uses `Authorization: Bearer $METRICS_TOKEN` instead.
-```http
-X-API-Key: your-api-key-here
+```bash
+# the auth header that prefixes nearly every call below
+-H "X-API-Key: $API_KEY"
```
-### Response Format
+### Responses
-Responses are the **raw handler payload** — there is no `{success, data, meta}` envelope.
-A successful response is the resource itself (object) or a bare array for lists.
+Responses are the **raw payload** — no `{ success, data }` envelope. A resource route returns the object directly; a list route returns a bare JSON array. Errors return the NestJS default shape `{ "statusCode", "message", "error" }`. Add `Content-Type: application/json` only when sending a body.
-```json
-{ "id": "abc", "status": "READY" }
-```
+### Sections
-### Error Format
+Sessions · Messages · Webhooks · Groups · Contacts · Chats · Labels · Channels · Catalog · Templates · Plugins · Settings · Auth (API Keys) · Health · Infrastructure · Stats · Metrics · Events (WebSocket).
-Errors use the NestJS default shape:
+## 07.2 Endpoints
-```json
-{
- "statusCode": 400,
- "message": "Invalid phone number format",
- "error": "Bad Request"
-}
-```
+All examples assume `BASE` and `API_KEY` are exported (see 07.1). Paths are prefixed with `/api`.
+
+### 07.3 Sessions
-## 07.2 Health & System
+All routes are under `$BASE/api/sessions` and require `X-API-Key: $API_KEY` (some require an OPERATOR-role key). Reads come first, then writes.
-### GET /health
+#### GET /api/sessions
-Basic health check.
+List all sessions visible to the key.
```bash
-curl http://localhost:2785/health
+curl -X GET "$BASE/api/sessions" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-{
- "status": "ok",
- "timestamp": "2026-02-02T10:30:00Z"
-}
+#### GET /api/sessions/:id
+
+Get a single session by ID.
+
+```bash
+curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /health/detailed
+#### GET /api/sessions/:id/qr
-Detailed health check with system status.
+Get the QR code (PNG data URL) for authentication.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed
+curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/qr" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-{
- "status": "ok",
- "version": "0.4.6",
- "uptime": 86400,
- "timestamp": "2026-02-02T10:30:00Z",
- "checks": {
- "database": "ok",
- "redis": "ok",
- "sessions": {
- "total": 5,
- "connected": 4,
- "disconnected": 1
- }
- }
-}
+#### GET /api/sessions/:id/groups
+
+List groups the session belongs to (paginated).
+
+```bash
+curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/groups?limit=100&offset=0" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /api/metrics
+#### GET /api/sessions/:id/chats
-System metrics (Prometheus format).
+List active chats, most-recent first (paginated).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/metrics
+curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats?limit=100&offset=0" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
+#### GET /api/sessions/stats/overview
+
+Aggregate session statistics for monitoring.
+
+```bash
+curl -X GET "$BASE/api/sessions/stats/overview" \
+ -H "X-API-Key: $API_KEY"
```
-# HELP openwa_sessions_total Total number of sessions
-# TYPE openwa_sessions_total gauge
-openwa_sessions_total{status="connected"} 4
-openwa_sessions_total{status="disconnected"} 1
-# HELP openwa_messages_total Total messages processed
-# TYPE openwa_messages_total counter
-openwa_messages_total{direction="incoming"} 15234
-openwa_messages_total{direction="outgoing"} 8567
+#### POST /api/sessions
-# HELP openwa_api_requests_total Total API requests
-# TYPE openwa_api_requests_total counter
-openwa_api_requests_total{method="GET",status="200"} 45678
-openwa_api_requests_total{method="POST",status="200"} 12345
+Create a new session (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "name": "my-bot", "config": { "autoReconnect": true }, "proxyUrl": "http://proxy.example.com:8080", "proxyType": "http" }'
```
-## 07.3 Sessions API
+#### POST /api/sessions/:id/start
-### GET /api/sessions
+Start a session and initialize the connection (OPERATOR).
-List all sessions.
+```bash
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/start" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:id/stop
+
+Stop a session and disconnect (OPERATOR).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/stop" \
+ -H "X-API-Key: $API_KEY"
```
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| status | string | Filter by status: `CONNECTED`, `DISCONNECTED`, `INITIALIZING` |
-| limit | number | Max results (default: 20) |
-| offset | number | Pagination offset |
+#### POST /api/sessions/:id/force-kill
-**Response:**
-```json
-[
- {
- "id": "default",
- "name": "Default Session",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "profileName": "John Doe",
- "profilePicture": "https://...",
- "createdAt": "2026-02-01T00:00:00Z",
- "lastSeen": "2026-02-02T10:30:00Z"
- }
-]
+Force-kill a stuck session (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/force-kill" \
+ -H "X-API-Key: $API_KEY"
```
-### POST /api/sessions
+#### POST /api/sessions/:id/pairing-code
-Create new session.
+Request an 8-char pairing code via phone number (OPERATOR).
```bash
-curl -X POST http://localhost:2785/api/sessions \
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/pairing-code" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "id": "session-1",
- "name": "Customer Support",
- "config": {
- "autoReconnect": true,
- "webhookUrl": "https://your-server.com/webhook"
- }
- }'
+ -d '{ "phoneNumber": "628123456789" }'
```
-**Request Body:**
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| id | string | No | Session ID (auto-generated if not provided) |
-| name | string | No | Display name |
-| config.autoReconnect | boolean | No | Auto reconnect on disconnect (default: true) |
-| config.webhookUrl | string | No | Webhook URL for this session |
-| config.proxy | string | No | Proxy URL (http://user:pass@host:port) |
+#### POST /api/sessions/:id/chats/read
+
+Mark a chat as read/seen (OPERATOR).
-**Response:**
-```json
-{
- "id": "session-1",
- "name": "Customer Support",
- "status": "INITIALIZING",
- "qr": null,
- "createdAt": "2026-02-02T10:30:00Z"
-}
+```bash
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/read" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]" }'
```
-### GET /api/sessions/:id
+#### POST /api/sessions/:id/chats/unread
-Get session details.
+Mark a chat as unread (OPERATOR).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/session-1
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/unread" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]" }'
```
-**Response:**
-```json
-{
- "id": "session-1",
- "name": "Customer Support",
- "status": "CONNECTED",
- "phoneNumber": "628123456789",
- "profileName": "John Doe",
- "profilePicture": "https://...",
- "pushName": "John",
- "platform": "android",
- "config": {
- "autoReconnect": true,
- "webhookUrl": "https://your-server.com/webhook"
- },
- "stats": {
- "messagesReceived": 1234,
- "messagesSent": 567,
- "lastMessageAt": "2026-02-02T10:25:00Z"
- },
- "createdAt": "2026-02-01T00:00:00Z",
- "lastSeen": "2026-02-02T10:30:00Z"
-}
+#### POST /api/sessions/:id/chats/delete
+
+Delete a chat from the chat list (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/delete" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]" }'
```
-### DELETE /api/sessions/:id
+#### POST /api/sessions/:id/chats/typing
-Delete session.
+Send a typing/recording presence indicator (or clear it with `paused`) (OPERATOR).
```bash
-curl -X DELETE \
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/typing" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/session-1
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "state": "typing" }'
```
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| keepAuth | boolean | Keep auth files for quick reconnect (default: false) |
+#### DELETE /api/sessions/:id
-**Response:**
-```json
-{
- "message": "Session deleted successfully"
-}
+Delete a session (OPERATOR). Returns `204` with no body.
+
+```bash
+curl -X DELETE "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /api/sessions/:id/qr
+### 07.4 Messages
+
+All routes are under `/api/sessions/:sessionId/messages`. Reads accept any API key; send/write routes need an OPERATOR (or higher) key.
+
+#### GET /api/sessions/:sessionId/messages
-Get QR code for authentication.
+Get persisted message history from the local DB (paginated, filterable).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/session-1/qr
+curl "$BASE/api/sessions/my-session/[email protected]&limit=20&offset=0" \
+ -H "X-API-Key: $API_KEY"
```
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| format | string | `base64` (default), `raw`, `image` |
+#### GET /api/sessions/:sessionId/messages/:chatId/history
-**Response (format=base64):**
-```json
-{
- "qr": "data:image/png;base64,iVBORw0KGgo...",
- "expiresAt": "2026-02-02T10:31:00Z"
-}
+Fetch chat history live from WhatsApp, bypassing the DB.
+
+```bash
+curl "$BASE/api/sessions/my-session/[email protected]/history?limit=100&deep=true" \
+ -H "X-API-Key: $API_KEY"
```
-**Response (format=image):**
-Returns PNG image directly with `Content-Type: image/png`
+#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/reactions
-### POST /api/sessions/:id/restart
+Get reactions for a message, grouped by emoji.
-Restart session.
+```bash
+curl "$BASE/api/sessions/my-session/[email protected]/[email protected]_3EB0ABCD/reactions" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/messages/batch/:batchId
+
+Get the status and progress of a bulk batch.
```bash
-curl -X POST \
- -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/session-1/restart
+curl "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-{
- "message": "Session restarting",
- "status": "INITIALIZING"
-}
+#### POST /api/sessions/:sessionId/messages/send-text
+
+Send a plain text message.
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-text" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }'
```
-### POST /api/sessions/:id/logout
+#### POST /api/sessions/:sessionId/messages/send-template
-Logout session (clear auth).
+Render a stored template (`{{vars}}` substituted) and send it as text.
```bash
-curl -X POST \
+curl -X POST "$BASE/api/sessions/my-session/messages/send-template" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/session-1/logout
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "templateName": "order-confirmation", "vars": { "customer": "Alice", "orderId": "1234" } }'
```
-**Response:**
-```json
-{
- "message": "Session logged out successfully"
-}
+#### POST /api/sessions/:sessionId/messages/send-image
+
+Send an image by URL or base64 with an optional caption.
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-image" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "url": "https://example.com/image.jpg", "caption": "Check out this image!" }'
```
-## 07.4 Messages API
+#### POST /api/sessions/:sessionId/messages/send-video
-### POST /api/sessions/:id/messages
+Send a video by URL or base64 with an optional caption.
-Send message.
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-video" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "url": "https://example.com/clip.mp4", "caption": "video" }'
+```
+
+#### POST /api/sessions/:sessionId/messages/send-audio
+
+Send an audio/voice message by URL or base64.
```bash
-# Text message
-curl -X POST http://localhost:2785/api/sessions/default/messages \
+curl -X POST "$BASE/api/sessions/my-session/messages/send-audio" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "phone": "[email protected]",
- "type": "text",
- "body": "Hello, World!"
- }'
+ -d '{ "chatId": "[email protected]", "url": "https://example.com/voice.ogg", "mimetype": "audio/ogg" }'
```
-**Request Body - Text:**
-```json
-{
- "phone": "[email protected]",
- "type": "text",
- "body": "Hello, World!",
- "options": {
- "quotedMessageId": "MSG_ABC123",
- "mentions": ["[email protected]"]
- }
-}
-```
-
-**Request Body - Image:**
-```json
-{
- "phone": "[email protected]",
- "type": "image",
- "media": {
- "url": "https://example.com/image.jpg"
- },
- "caption": "Check this out!"
-}
-```
-
-**Request Body - Image (Base64):**
-```json
-{
- "phone": "[email protected]",
- "type": "image",
- "media": {
- "base64": "iVBORw0KGgo...",
- "mimetype": "image/jpeg",
- "filename": "photo.jpg"
- },
- "caption": "Photo from base64"
-}
-```
-
-**Request Body - Document:**
-```json
-{
- "phone": "[email protected]",
- "type": "document",
- "media": {
- "url": "https://example.com/document.pdf"
- },
- "filename": "report.pdf",
- "caption": "Monthly report"
-}
-```
-
-**Request Body - Location:**
-```json
-{
- "phone": "[email protected]",
- "type": "location",
- "location": {
- "latitude": -6.2088,
- "longitude": 106.8456,
- "name": "Monas",
- "address": "Jakarta, Indonesia"
- }
-}
+#### POST /api/sessions/:sessionId/messages/send-document
+
+Send a document/file by URL or base64.
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-document" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "url": "https://example.com/report.pdf", "filename": "report.pdf", "mimetype": "application/pdf" }'
```
-**Request Body - Contact:**
-```json
-{
- "phone": "[email protected]",
- "type": "contact",
- "contact": {
- "name": "John Doe",
- "phone": "+628111222333"
- }
-}
+#### POST /api/sessions/:sessionId/messages/send-location
+
+Send a location pin.
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-location" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "latitude": -6.2088, "longitude": 106.8456, "description": "Jakarta", "address": "Central Jakarta" }'
```
-**Interactive messages (Buttons / List): not supported**
+#### POST /api/sessions/:sessionId/messages/send-contact
-> ⚠️ **Buttons and List (interactive) messages are not available** through OpenWA's
-> unofficial-client engines (`whatsapp-web.js` default or `baileys`). WhatsApp stopped
-> honoring the interactive-message payload for unofficial clients around 2021–2022 —
-> messages of this type are **silently dropped and never delivered** to recipients.
-> OpenWA therefore does not expose `type: "buttons"` or `type: "list"` endpoints;
-> sending interactive messages requires the official WhatsApp Business Cloud API.
-> (The earlier examples here were speculative and never implemented — see #158.)
+Send a contact card (vCard).
-**Response:**
-```json
-{
- "id": "MSG_ABC123DEF456",
- "phone": "[email protected]",
- "type": "text",
- "body": "Hello, World!",
- "status": "PENDING",
- "timestamp": "2026-02-02T10:30:00Z"
-}
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-contact" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "contactName": "John Doe", "contactNumber": "628987654321" }'
```
-### POST /api/sessions/:id/messages (Multipart)
+#### POST /api/sessions/:sessionId/messages/send-sticker
-Send message with file upload.
+Send a sticker by URL or base64 (typically webp).
```bash
-curl -X POST http://localhost:2785/api/sessions/default/messages \
+curl -X POST "$BASE/api/sessions/my-session/messages/send-sticker" \
-H "X-API-Key: $API_KEY" \
- -F "type=image" \
- -F "media=@/path/to/image.jpg" \
- -F "caption=Uploaded via multipart"
-```
-
-### GET /api/sessions/:id/messages
-
-Get message history.
-
-```bash
-curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/default/[email protected]&limit=50"
-```
-
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| phone | string | Filter by chat (required) |
-| limit | number | Max results (default: 50, max: 200) |
-| before | string | Messages before this ID |
-| after | string | Messages after this ID |
-| type | string | Filter by type: `text`, `image`, `video`, etc. |
-
-**Response:**
-```json
-[
- {
- "id": "MSG_ABC123",
- "from": "[email protected]",
- "body": "Hello!",
- "type": "text",
- "timestamp": "2026-02-02T10:25:00Z",
- "status": "READ",
- "isFromMe": false
- }
-]
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "url": "https://example.com/sticker.webp", "mimetype": "image/webp" }'
```
-### GET /api/sessions/:id/messages/:messageId
+#### POST /api/sessions/:sessionId/messages/reply
-Get specific message.
+Reply to a message, quoting a prior one.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/messages/MSG_ABC123
+curl -X POST "$BASE/api/sessions/my-session/messages/reply" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "quotedMessageId": "[email protected]_3EB0ABCD", "text": "Replying to you" }'
```
-### DELETE /api/sessions/:id/messages/:messageId
+#### POST /api/sessions/:sessionId/messages/forward
-Delete/revoke message.
+Forward a message from one chat to another.
```bash
-curl -X DELETE \
+curl -X POST "$BASE/api/sessions/my-session/messages/forward" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/messages/MSG_ABC123
+ -H "Content-Type: application/json" \
+ -d '{ "fromChatId": "[email protected]", "toChatId": "[email protected]", "messageId": "[email protected]_3EB0XYZ" }'
```
-**Query Parameters:**
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| forEveryone | boolean | Delete for everyone (default: true) |
+#### POST /api/sessions/:sessionId/messages/react
-### POST /api/sessions/:id/messages/:messageId/react
+Add a reaction (send an empty `emoji` to remove it).
-React to message.
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/react" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "emoji": "👍" }'
+```
+
+#### POST /api/sessions/:sessionId/messages/delete
+
+Delete a message (for everyone by default).
```bash
-curl -X POST http://localhost:2785/api/sessions/default/messages/MSG_ABC123/react \
+curl -X POST "$BASE/api/sessions/my-session/messages/delete" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{"emoji": "👍"}'
+ -d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "forEveryone": true }'
```
-## 07.5 Contacts API
+#### POST /api/sessions/:sessionId/messages/send-bulk
-### GET /api/sessions/:id/contacts
+Send to multiple recipients as an async batch (max 100 messages).
-Get all contacts.
+```bash
+curl -X POST "$BASE/api/sessions/my-session/messages/send-bulk" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "messages": [
+ { "chatId": "[email protected]", "type": "text", "content": { "text": "Hi {{name}}" }, "variables": { "name": "Alice" } },
+ { "chatId": "[email protected]", "type": "image", "content": { "image": { "url": "https://example.com/promo.jpg" }, "caption": "Promo" } }
+ ],
+ "options": { "delayBetweenMessages": 3000, "randomizeDelay": true, "stopOnError": false }
+ }'
+```
+
+#### POST /api/sessions/:sessionId/messages/batch/:batchId/cancel
+
+Cancel a running bulk batch (no body).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts
+curl -X POST "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4/cancel" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-[
- {
- "name": "John Doe",
- "pushName": "John",
- "shortName": "John",
- "isMyContact": true,
- "isBlocked": false,
- "profilePicture": "https://..."
- }
-]
+### 07.5 Contacts
+
+#### GET /api/sessions/:sessionId/contacts
+
+List contacts for a session (paginated window).
+
+```bash
+curl -X GET "$BASE/api/sessions/main/contacts?limit=100&offset=0" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /api/sessions/:id/contacts/:phone
+#### GET /api/sessions/:sessionId/contacts/check/:number
-Get contact info.
+Check whether a phone number is on WhatsApp.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts/628123456789
+curl -X GET "$BASE/api/sessions/main/contacts/check/628123456789" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /api/sessions/:id/contacts/check/:number
+#### GET /api/sessions/:sessionId/contacts/:contactId
-Check if number exists on WhatsApp.
+Get a single contact by its WhatsApp id.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts/check/628123456789
+curl -X GET "$BASE/api/sessions/main/contacts/[email protected]" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-{
- "number": "628123456789",
- "exists": true,
- "whatsappId": "[email protected]"
-}
+#### GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
+
+Get a contact's profile picture URL.
+
+```bash
+curl -X GET "$BASE/api/sessions/main/contacts/[email protected]/profile-picture" \
+ -H "X-API-Key: $API_KEY"
```
-`whatsappId` is the engine's canonical WhatsApp ID (`null` when `exists` is
-`false`); it may be normalized and differ from the submitted number.
+#### GET /api/sessions/:sessionId/contacts/:contactId/phone
-### POST /api/sessions/:id/contacts/:phone/block
+Resolve a contact id (e.g. an @lid) to a phone number.
-Block contact.
+```bash
+curl -X GET "$BASE/api/sessions/main/contacts/12345678901234@lid/phone" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/contacts/:contactId/block
+
+Block a contact (requires an OPERATOR key). Send an empty body.
```bash
-curl -X POST \
+curl -X POST "$BASE/api/sessions/main/contacts/[email protected]/block" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts/628123456789/block
+ -H "Content-Type: application/json" \
+ -d '{}'
```
-### POST /api/sessions/:id/contacts/:phone/unblock
+#### DELETE /api/sessions/:sessionId/contacts/:contactId/block
-Unblock contact.
+Unblock a contact (requires an OPERATOR key).
```bash
-curl -X POST \
- -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts/628123456789/unblock
+curl -X DELETE "$BASE/api/sessions/main/contacts/[email protected]/block" \
+ -H "X-API-Key: $API_KEY"
```
-## 07.6 Groups API
+### 07.6 Groups
-### GET /api/sessions/:id/groups
+#### GET /api/sessions/:sessionId/groups
-Get all groups.
+List all groups for a session (paginated).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/groups
+curl -X GET "$BASE/api/sessions/my-session/groups?limit=1000&offset=0" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-[
- {
- "name": "Family Group",
- "description": "Family chat",
- "participantsCount": 15,
- "isAdmin": true,
- "profilePicture": "https://...",
- "createdAt": "2025-01-15T00:00:00Z"
- }
-]
+#### GET /api/sessions/:sessionId/groups/:groupId
+
+Get detailed group info including participants.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]" \
+ -H "X-API-Key: $API_KEY"
```
-### POST /api/sessions/:id/groups
+#### GET /api/sessions/:sessionId/groups/:groupId/invite-code
-Create new group.
+Get the group invite code and full invite link.
```bash
-curl -X POST http://localhost:2785/api/sessions/default/groups \
+curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]/invite-code" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/groups
+
+Create a new group with an initial set of participants (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/groups" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "name": "New Group",
- "participants": [
- ]
- }'
+ -d '{ "name": "Project Team", "participants": ["[email protected]", "[email protected]"] }'
```
-**Response:**
-```json
-{
- "name": "New Group",
- "inviteCode": "ABC123XYZ"
-}
+#### POST /api/sessions/:sessionId/groups/:groupId/participants
+
+Add participants to a group (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "participants": ["[email protected]"] }'
```
-### GET /api/sessions/:id/groups/:groupId
+#### DELETE /api/sessions/:sessionId/groups/:groupId/participants
-Get group info.
+Remove participants from a group (OPERATOR). This DELETE takes a JSON body.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/groups/[email protected]
+curl -X DELETE "$BASE/api/sessions/my-session/groups/[email protected]/participants" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "participants": ["[email protected]"] }'
```
-**Response:**
-```json
-{
- "name": "Family Group",
- "description": "Family chat",
- "owner": "[email protected]",
- "participants": [
- {
- "isAdmin": true,
- "isSuperAdmin": false
- },
- {
- "isAdmin": false,
- "isSuperAdmin": false
- }
- ],
- "settings": {
- "announce": false,
- "restrict": false
- },
- "inviteCode": "ABC123XYZ",
- "createdAt": "2025-01-15T00:00:00Z"
-}
+#### POST /api/sessions/:sessionId/groups/:groupId/participants/promote
+
+Promote participants to group admin (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants/promote" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "participants": ["[email protected]"] }'
```
-### PATCH /api/sessions/:id/groups/:groupId
+#### POST /api/sessions/:sessionId/groups/:groupId/participants/demote
-Update group info.
+Demote participants from group admin (OPERATOR).
```bash
-curl -X PATCH http://localhost:2785/api/sessions/default/groups/[email protected] \
+curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants/demote" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "name": "Updated Group Name",
- "description": "New description"
- }'
+ -d '{ "participants": ["[email protected]"] }'
```
-### DELETE /api/sessions/:id/groups/:groupId
+#### PUT /api/sessions/:sessionId/groups/:groupId/subject
-Leave group.
+Change the group name/subject (OPERATOR).
```bash
-curl -X DELETE \
+curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/subject" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/groups/[email protected]
+ -H "Content-Type: application/json" \
+ -d '{ "subject": "New Team Name" }'
```
-### POST /api/sessions/:id/groups/:groupId/participants
+#### PUT /api/sessions/:sessionId/groups/:groupId/description
-Add participants to group.
+Change the group description; an empty string clears it (OPERATOR).
```bash
-curl -X POST http://localhost:2785/api/sessions/default/groups/[email protected]/participants \
+curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/description" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "participants": ["[email protected]", "[email protected]"]
- }'
+ -d '{ "description": "Internal coordination group." }'
```
-### DELETE /api/sessions/:id/groups/:groupId/participants
+#### POST /api/sessions/:sessionId/groups/:groupId/leave
-Remove participants from group.
+Leave a group (OPERATOR).
```bash
-curl -X DELETE http://localhost:2785/api/sessions/default/groups/[email protected]/participants \
+curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/leave" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/groups/:groupId/invite-code/revoke
+
+Revoke the current invite code and generate a new one (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/invite-code/revoke" \
+ -H "X-API-Key: $API_KEY"
+```
+
+### 07.7 Message Templates
+
+All template routes are nested under a session and require an OPERATOR-level key.
+
+#### GET /api/sessions/:sessionId/templates
+
+List all templates for a session, newest first.
+
+```bash
+curl "$BASE/api/sessions/$SESSION_ID/templates" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/templates/:id
+
+Get a single template by ID.
+
+```bash
+curl "$BASE/api/sessions/$SESSION_ID/templates/$TEMPLATE_ID" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/templates
+
+Create a message template with `{{variable}}` placeholders.
+
+```bash
+curl -X POST "$BASE/api/sessions/$SESSION_ID/templates" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "participants": ["[email protected]"]
+ "name": "order-confirmation",
+ "body": "Hi {{customer}}, your order {{orderId}} has shipped.",
+ "header": "OpenWA Store",
+ "footer": "Reply STOP to unsubscribe."
}'
```
-### POST /api/sessions/:id/groups/:groupId/admins
+#### PUT /api/sessions/:sessionId/templates/:id
-Promote to admin.
+Update a template (partial; only provided fields change).
```bash
-curl -X POST http://localhost:2785/api/sessions/default/groups/[email protected]/admins \
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/templates/$TEMPLATE_ID" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "participants": ["[email protected]"]
+ "body": "Hi {{customer}}, your order {{orderId}} is out for delivery.",
+ "footer": "Thanks for shopping with us."
}'
```
-### DELETE /api/sessions/:id/groups/:groupId/admins
+#### DELETE /api/sessions/:sessionId/templates/:id
+
+Delete a template by ID (returns `204` empty body).
+
+```bash
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/templates/$TEMPLATE_ID" \
+ -H "X-API-Key: $API_KEY"
+```
+
+### 07.8 Catalog & Channels
+
+#### GET /api/sessions/:sessionId/catalog
+
+Get business catalog info for the session.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/catalog" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/catalog/products
+
+List catalog products with pagination.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/catalog/products?page=1&limit=20" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/catalog/products/:productId
+
+Get a specific catalog product by id (unknown id returns 200 with `null`).
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/catalog/products/PROD_12345" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/messages/send-product
-Demote from admin.
+Send a product card to a chat (OPERATOR key required).
```bash
-curl -X DELETE http://localhost:2785/api/sessions/default/groups/[email protected]/admins \
+curl -X POST "$BASE/api/sessions/my-session/messages/send-product" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "participants": ["[email protected]"]
- }'
+ -d '{ "chatId": "[email protected]", "productId": "PROD_12345", "body": "Check out this item!" }'
```
-### GET /api/sessions/:id/groups/:groupId/invite-code
+#### POST /api/sessions/:sessionId/messages/send-catalog
-Get group invite code.
+Send the business catalog link to a chat (OPERATOR key required).
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/groups/[email protected]/invite-code
+curl -X POST "$BASE/api/sessions/my-session/messages/send-catalog" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "chatId": "[email protected]", "body": "Browse our full catalog here" }'
```
-**Response:**
-```json
-{
- "inviteCode": "ABC123XYZ",
- "inviteUrl": "https://chat.whatsapp.com/ABC123XYZ"
-}
+#### GET /api/sessions/:sessionId/channels
+
+List subscribed channels/newsletters.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/channels" \
+ -H "X-API-Key: $API_KEY"
```
-### POST /api/sessions/:id/groups/:groupId/invite-code/revoke
+#### GET /api/sessions/:sessionId/channels/:channelId
-Revoke and generate new invite code.
+Get a single channel by id.
```bash
-curl -X POST \
+curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/channels/:channelId/messages
+
+Get recent messages from a channel.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter/messages?limit=50" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/channels/subscribe
+
+Subscribe to a channel by invite code (OPERATOR key required).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/channels/subscribe" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/groups/[email protected]/invite-code/revoke
+ -H "Content-Type: application/json" \
+ -d '{ "inviteCode": "ABC123xyz" }'
```
-## 07.7 Webhooks API
+#### DELETE /api/sessions/:sessionId/channels/:channelId
-### GET /api/sessions/:sessionId/webhooks
+Unsubscribe from a channel (OPERATOR key required).
-List all webhooks.
+```bash
+curl -X DELETE "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter" \
+ -H "X-API-Key: $API_KEY"
+```
+
+### 07.9 Labels & Status
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/sess_abc123/webhooks
+# List all labels for a session (WhatsApp Business only)
+curl -X GET "$BASE/api/sessions/$SESSION_ID/labels" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-[
- {
- "id": "wh_123",
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.ack"],
- "sessionId": "sess_abc123",
- "enabled": true,
- "secret": "whsec_***",
- "createdAt": "2026-02-01T00:00:00Z"
- }
-]
+```bash
+# Get a single label by ID
+curl -X GET "$BASE/api/sessions/$SESSION_ID/labels/5" \
+ -H "X-API-Key: $API_KEY"
```
-### POST /api/sessions/:sessionId/webhooks
+```bash
+# List labels assigned to a chat
+curl -X GET "$BASE/api/sessions/$SESSION_ID/labels/chat/[email protected]" \
+ -H "X-API-Key: $API_KEY"
+```
-Create webhook.
+```bash
+# Add a label to a chat (OPERATOR)
+curl -X POST "$BASE/api/sessions/$SESSION_ID/labels/chat/[email protected]" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "labelId": "5" }'
+```
+
+```bash
+# Remove a label from a chat (OPERATOR)
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/labels/chat/[email protected]/5" \
+ -H "X-API-Key: $API_KEY"
+```
```bash
-curl -X POST http://localhost:2785/api/sessions/sess_abc123/webhooks \
+# Get all status updates (stories) visible to the session
+curl -X GET "$BASE/api/sessions/$SESSION_ID/status" \
+ -H "X-API-Key: $API_KEY"
+```
+
+```bash
+# Get status updates posted by a specific contact
+curl -X GET "$BASE/api/sessions/$SESSION_ID/status/[email protected]" \
+ -H "X-API-Key: $API_KEY"
+```
+
+```bash
+# Post a text status (OPERATOR)
+curl -X POST "$BASE/api/sessions/$SESSION_ID/status/send-text" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "text": "Hello from OpenWA!", "backgroundColor": "#25D366", "font": 2 }'
+```
+
+```bash
+# Post an image status from a URL (OPERATOR)
+curl -X POST "$BASE/api/sessions/$SESSION_ID/status/send-image" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "image": { "url": "https://example.com/photo.jpg" }, "caption": "My status" }'
+```
+
+```bash
+# Post a video status from a URL (OPERATOR)
+curl -X POST "$BASE/api/sessions/$SESSION_ID/status/send-video" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "video": { "url": "https://example.com/clip.mp4" }, "caption": "Watch this" }'
+```
+
+```bash
+# Delete one of the session's own posted statuses (OPERATOR)
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/status/false_status@broadcast_3A1F" \
+ -H "X-API-Key: $API_KEY"
+```
+
+### 07.10 Webhooks (management)
+
+All routes require an API key with OPERATOR role or higher. `secret` and `headers` are write-only (never returned). The per-session routes live under `/api/sessions/:sessionId/webhooks`; the cross-session list is `/api/webhooks`.
+
+#### GET /api/sessions/:sessionId/webhooks
+
+List all webhooks for a session (newest first).
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/webhooks" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/sessions/:sessionId/webhooks/:id
+
+Get a single webhook by ID, scoped to the session.
+
+```bash
+curl -X GET "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/webhooks
+
+List webhooks visible to the calling key (scoped to its allowed sessions).
+
+```bash
+curl -X GET "$BASE/api/webhooks" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/sessions/:sessionId/webhooks
+
+Create a webhook for the session.
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/webhooks" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-server.com/webhook",
- "events": ["message.received", "message.ack", "session.status"],
- "headers": {
- "Authorization": "Bearer your-token"
- }
+ "events": ["message.received", "session.status"],
+ "secret": "your-secret-key",
+ "headers": { "X-Custom-Header": "value" },
+ "filters": {
+ "conditions": [
+ { "field": "sender", "operator": "is", "value": ["[email protected]"] },
+ { "field": "body", "operator": "contains", "value": "invoice" }
+ ]
+ },
+ "retryCount": 3
}'
```
-**Request Body:**
-| Field | Type | Required | Description |
-|-------|------|----------|-------------|
-| url | string | Yes | Webhook endpoint URL |
-| events | string[] | Yes | Events to subscribe |
-| headers | object | No | Custom headers to send |
-| secret | string | No | Secret for signature verification |
+#### PUT /api/sessions/:sessionId/webhooks/:id
+
+Update a webhook (partial; only provided fields change).
-**Available Events:**
+```bash
+curl -X PUT "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "events": ["*"],
+ "active": false,
+ "retryCount": 5,
+ "filters": null
+ }'
```
-message.received - New incoming message
-message.sent - Message sent
-message.ack - Message status (sent, delivered, read)
-message.revoked - Message deleted
-message.reaction - Reaction added, changed, or removed
-session.status - Session status change
-session.qr - QR code generated
-session.authenticated - Session authenticated
-session.disconnected - Session disconnected
-group.join - Someone joined group
-group.leave - Someone left group
-group.update - Group settings changed
+
+#### POST /api/sessions/:sessionId/webhooks/:id/test
+
+Send a synthetic test payload to the webhook URL and report the result (no request body).
+
+```bash
+curl -X POST "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef/test" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### DELETE /api/sessions/:sessionId/webhooks/:id
+
+Delete a webhook (returns `204` no content).
+
+```bash
+curl -X DELETE "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-{
- "id": "wh_456",
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.ack", "session.status"],
- "sessionId": "sess_abc123",
- "enabled": true,
- "secret": "whsec_abc123xyz",
- "createdAt": "2026-02-02T10:30:00Z"
-}
+### 07.11 API Keys
+
+All `/api/auth/api-keys` routes require an **ADMIN** key. `POST /api/auth/validate` accepts any valid key. The plaintext key is returned only by the create call.
+
+#### GET /api/auth/api-keys
+
+List all API keys (newest first).
+
+```bash
+curl -X GET "$BASE/api/auth/api-keys" \
+ -H "X-API-Key: $API_KEY"
```
-### GET /api/sessions/:sessionId/webhooks/:id
+#### GET /api/auth/api-keys/:id
-Get webhook details.
+Get one API key by id.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/sess_abc123/webhooks/wh_456
+curl -X GET "$BASE/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33" \
+ -H "X-API-Key: $API_KEY"
```
-### PATCH /api/sessions/:sessionId/webhooks/:webhookId
+#### POST /api/auth/api-keys
-Update webhook.
+Create a key; the response includes the full plaintext key once.
```bash
-curl -X PATCH http://localhost:2785/api/sessions/sess_abc123/webhooks/wh_456 \
+curl -X POST "$BASE/api/auth/api-keys" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "events": ["message.received"],
- "enabled": false
+ "name": "Production Bot",
+ "role": "operator",
+ "allowedIps": ["192.168.1.1", "10.0.0.0/8"],
+ "allowedSessions": ["session-uuid-1"],
+ "expiresAt": "2027-12-31T23:59:59Z"
}'
```
-### DELETE /api/sessions/:sessionId/webhooks/:webhookId
+#### PUT /api/auth/api-keys/:id
-Delete webhook.
+Update name/role/allowedIps/allowedSessions/expiresAt.
```bash
-curl -X DELETE \
+curl -X PUT "$BASE/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/sess_abc123/webhooks/wh_456
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "Renamed Bot",
+ "role": "viewer",
+ "allowedIps": ["203.0.113.5"],
+ "expiresAt": "2028-01-01T00:00:00Z"
+ }'
```
-### GET /api/sessions/:sessionId/webhooks/:id/logs
+#### POST /api/auth/api-keys/:id/revoke
-Get webhook delivery logs.
+Deactivate a key without deleting it (no body).
```bash
-curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/sess_abc123/webhooks/wh_456/logs?limit=20"
+curl -X POST "$BASE/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33/revoke" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-[
- {
- "id": "log_789",
- "webhookId": "wh_456",
- "event": "message.received",
- "status": "success",
- "statusCode": 200,
- "duration": 150,
- "attempt": 1,
- "payload": { },
- "response": { },
- "createdAt": "2026-02-02T10:30:00Z"
- }
-]
+#### DELETE /api/auth/api-keys/:id
+
+Permanently delete a key (returns `204`, no body).
+
+```bash
+curl -X DELETE "$BASE/api/auth/api-keys/3f2a1c9e-1b2d-4a5f-9c8e-aa11bb22cc33" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/auth/validate
+
+Validate the supplied key and report its role (empty body; key read from the header).
+
+```bash
+curl -X POST "$BASE/api/auth/validate" \
+ -H "X-API-Key: $API_KEY"
+```
+
+### 07.12 System (Health, Metrics, Stats, Settings)
+
+#### GET /api/health
+
+Basic health check (status, timestamp, version). Public.
+
+```bash
+curl "$BASE/api/health"
+```
+
+#### GET /api/health/live
+
+Liveness probe — always `{ "status": "ok" }`. Public.
+
+```bash
+curl "$BASE/api/health/live"
+```
+
+#### GET /api/health/ready
+
+Readiness probe — checks both datasources; `503` while draining or on DB failure. Public.
+
+```bash
+curl "$BASE/api/health/ready"
```
-### POST /api/sessions/:sessionId/webhooks/:id/test
+#### GET /api/metrics
-Test webhook.
+Prometheus scrape. Gated by the metrics bearer token (not the API key); `404` when `METRICS_TOKEN` is unset.
```bash
-curl -X POST \
+curl "$BASE/api/metrics" \
+ -H "Authorization: Bearer $METRICS_TOKEN"
+```
+
+#### GET /api/stats/overview
+
+Cross-session aggregate stats. ADMIN key required.
+
+```bash
+curl "$BASE/api/stats/overview" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/stats/messages
+
+Message stats over a period (`24h` | `7d` | `30d`, default `24h`). ADMIN key required.
+
+```bash
+curl "$BASE/api/stats/messages?period=7d" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/stats/sessions/:sessionId
+
+Per-session stats. Any valid API key (not session-scoped).
+
+```bash
+curl "$BASE/api/stats/sessions/9f1c2d3e-…" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/settings
+
+Read runtime settings (env-derived). Any valid API key.
+
+```bash
+curl "$BASE/api/settings" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### PUT /api/settings
+
+Always returns `501` — settings are read-only at runtime. ADMIN key required (still `501`).
+
+```bash
+curl -X PUT "$BASE/api/settings" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/sess_abc123/webhooks/wh_456/test
+ -H "Content-Type: application/json" \
+ -d '{ "general": { "sessionTimeout": 10 } }'
```
-**Response:**
-```json
-{
- "status": "success",
- "statusCode": 200,
- "duration": 125,
- "response": {
- "received": true
- }
-}
+### 07.13 Administration (Infrastructure, Plugins, MCP)
+
+ADMIN-only operations (except the public health check and the MCP transport). Assumes `BASE`, `API_KEY`, and — for MCP — that `MCP_ENABLED=true`.
+
+#### GET /api/infra/health
+
+Public liveness probe.
+
+```bash
+curl "$BASE/api/infra/health"
```
-## 07.8 API Keys API
+#### GET /api/infra/status
+
+Aggregate infra status (DB, Redis, queue, storage, engine).
-All API key management endpoints require an admin API key in `X-API-Key`.
-OpenWA creates the initial admin key on first run, prints it in the startup
-logs, and writes it to `data/.api-key` (or `/app/data/.api-key` inside the API
-container). By default a random `owa_k1_...` admin key is generated on first run
-in all environments; set `ALLOW_DEV_API_KEY=true` to seed the well-known
-`dev-admin-key` for local development only.
+```bash
+curl "$BASE/api/infra/status" \
+ -H "X-API-Key: $API_KEY"
+```
-### GET /api/auth/api-keys
+#### GET /api/infra/engines
-List API keys.
+List available WhatsApp engine plugins.
```bash
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/auth/api-keys
+curl "$BASE/api/infra/engines" \
+ -H "X-API-Key: $API_KEY"
```
-**Response:**
-```json
-[
- {
- "id": "2a8f41e3-3b9a-4a1d-b6d0-b9910df8f0be",
- "name": "Production Key",
- "keyPrefix": "owa_k1_abcd",
- "role": "operator",
- "allowedIps": ["192.168.1.10"],
- "allowedSessions": ["session-uuid-1"],
- "isActive": true,
- "lastUsedAt": "2026-02-02T10:30:00Z",
- "usageCount": 12,
- "expiresAt": null,
- "createdAt": "2026-01-01T00:00:00Z"
- }
-]
+#### GET /api/infra/engines/current
+
+Get the currently active engine type.
+
+```bash
+curl "$BASE/api/infra/engines/current" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/infra/config
+
+Read saved infrastructure config (secrets omitted).
+
+```bash
+curl "$BASE/api/infra/config" \
+ -H "X-API-Key: $API_KEY"
```
-### POST /api/auth/api-keys
+#### PUT /api/infra/config
-Create API key.
+Merge-save infrastructure config to `data/.env.generated`.
```bash
-curl -X POST http://localhost:2785/api/auth/api-keys \
+curl -X PUT "$BASE/api/infra/config" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "name": "Integration Key",
- "role": "operator",
- "allowedIps": ["192.168.1.10"],
- "allowedSessions": ["default"],
- "expiresAt": "2027-01-01T00:00:00Z"
+ "database": { "type": "postgres", "host": "db.example.com", "port": "5432", "username": "openwa", "password": "s3cret", "database": "openwa", "poolSize": 10, "sslEnabled": true, "sslRejectUnauthorized": false },
+ "redis": { "enabled": true, "builtIn": true },
+ "queue": { "enabled": true },
+ "storage": { "type": "s3", "s3Bucket": "my-bucket", "s3Region": "ap-southeast-1", "s3AccessKey": "AKIA...", "s3SecretKey": "...", "s3Endpoint": "https://s3.example.com" },
+ "engine": { "type": "whatsapp-web.js", "headless": true }
}'
```
-**Roles:**
-```
-admin - Full access, including API key management
-operator - Operational API access for integrations
-viewer - Read-only API access where supported
-```
+#### POST /api/infra/restart
+
+Request a graceful restart, optionally orchestrating Docker profiles.
-**Response:**
-```json
-{
- "id": "4d0564f1-5fb7-4e4a-baae-4cb0d154e861",
- "name": "Integration Key",
- "keyPrefix": "owa_k1_efgh",
- "role": "operator",
- "allowedIps": ["192.168.1.10"],
- "allowedSessions": ["default"],
- "isActive": true,
- "usageCount": 0,
- "expiresAt": "2027-01-01T00:00:00Z",
- "createdAt": "2026-02-02T10:30:00Z",
- "apiKey": "owa_k1_efgh5678..."
-}
+```bash
+curl -X POST "$BASE/api/infra/restart" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "profiles": ["postgres", "redis"], "profilesToRemove": ["minio"] }'
```
-**Note:** The full `apiKey` is only shown once at creation.
+#### GET /api/infra/export-data
+
+Export all Data DB rows as JSON for migration.
-### PUT /api/auth/api-keys/:id
+```bash
+curl "$BASE/api/infra/export-data" \
+ -H "X-API-Key: $API_KEY"
+```
-Update API key metadata, role, IP allowlist, session allowlist, or expiry.
+#### POST /api/infra/import-data
+
+Replace all Data DB rows with a prior export (destructive, all-or-nothing).
```bash
-curl -X PUT http://localhost:2785/api/auth/api-keys/4d0564f1-5fb7-4e4a-baae-4cb0d154e861 \
+curl -X POST "$BASE/api/infra/import-data" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "name": "Integration Key - Production",
- "role": "operator"
+ "tables": {
+ "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": []
+ }
}'
```
-### POST /api/auth/api-keys/:id/revoke
+#### GET /api/infra/storage/files/count
-Revoke API key without deleting its record.
+File count and total size in the active storage backend.
```bash
-curl -X POST \
+curl "$BASE/api/infra/storage/files/count" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/infra/storage/export
+
+Export all storage files to a tar.gz; returns its server-side path.
+
+```bash
+curl "$BASE/api/infra/storage/export" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### POST /api/infra/storage/import
+
+Import storage files from a tar.gz located inside `data/`.
+
+```bash
+curl -X POST "$BASE/api/infra/storage/import" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/auth/api-keys/4d0564f1-5fb7-4e4a-baae-4cb0d154e861/revoke
+ -H "Content-Type: application/json" \
+ -d '{ "filePath": "./data/exports/storage-export-1750000000000-abc.tar.gz" }'
+```
+
+#### GET /api/plugins
+
+List all loaded plugins (secrets redacted).
+
+```bash
+curl "$BASE/api/plugins" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/plugins/catalog
+
+List the remote plugin catalog with install state.
+
+```bash
+curl "$BASE/api/plugins/catalog" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/plugins/:id
+
+Get a single plugin by id.
+
+```bash
+curl "$BASE/api/plugins/chat-flow" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/plugins/:id/config-ui
+
+Fetch a plugin's sandboxed config-UI HTML (for an iframe srcdoc).
+
+```bash
+curl "$BASE/api/plugins/chat-flow/config-ui" \
+ -H "X-API-Key: $API_KEY"
+```
+
+#### GET /api/plugins/:id/health
+
+Check a plugin's health.
+
+```bash
+curl "$BASE/api/plugins/chat-flow/health" \
+ -H "X-API-Key: $API_KEY"
```
-### DELETE /api/auth/api-keys/:id
+#### POST /api/plugins/install
-Delete API key.
+Install a plugin from an uploaded .zip (multipart, field `file`, max 5 MB).
```bash
-curl -X DELETE \
+curl -X POST "$BASE/api/plugins/install" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/auth/api-keys/4d0564f1-5fb7-4e4a-baae-4cb0d154e861
```
-### POST /api/auth/validate
+#### POST /api/plugins/install-url
-Validate the API key provided in the `X-API-Key` header.
+Install a plugin by downloading its .zip from a URL (SSRF-guarded).
```bash
-curl -X POST \
+curl -X POST "$BASE/api/plugins/install-url" \
-H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/auth/validate
-```
-
-## 07.9 Postman Collection
-
-```json
-{
- "info": {
- "name": "OpenWA API",
- "description": "OpenWA WhatsApp API Gateway",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
- },
- "variable": [
- {
- "key": "baseUrl",
- "value": "http://localhost:2785",
- "type": "string"
- },
- {
- "key": "apiKey",
- "value": "your-api-key",
- "type": "string"
- },
- {
- "key": "sessionId",
- "value": "default",
- "type": "string"
- }
- ],
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "key",
- "value": "X-API-Key",
- "type": "string"
- },
- {
- "key": "value",
- "value": "{{apiKey}}",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "item": [
- {
- "name": "Health",
- "item": [
- {
- "name": "Health Check",
- "request": {
- "method": "GET",
- "url": "{{baseUrl}}/health"
- }
- },
- {
- "name": "Detailed Health",
- "request": {
- "method": "GET",
- "url": "{{baseUrl}}/health/detailed"
- }
- }
- ]
- },
- {
- "name": "Sessions",
- "item": [
- {
- "name": "List Sessions",
- "request": {
- "method": "GET",
- "url": "{{baseUrl}}/api/sessions"
- }
- },
- {
- "name": "Create Session",
- "request": {
- "method": "POST",
- "url": "{{baseUrl}}/api/sessions",
- "body": {
- "mode": "raw",
- "raw": "{\n \"id\": \"{{sessionId}}\",\n \"name\": \"My Session\"\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- }
- }
- },
- {
- "name": "Get Session",
- "request": {
- "method": "GET",
- "url": "{{baseUrl}}/api/sessions/{{sessionId}}"
- }
- },
- {
- "name": "Get QR Code",
- "request": {
- "method": "GET",
- "url": "{{baseUrl}}/api/sessions/{{sessionId}}/qr"
- }
- },
- {
- "name": "Delete Session",
- "request": {
- "method": "DELETE",
- "url": "{{baseUrl}}/api/sessions/{{sessionId}}"
- }
- }
- ]
- },
- {
- "name": "Messages",
- "item": [
- {
- "name": "Send Text Message",
- "request": {
- "method": "POST",
- "url": "{{baseUrl}}/api/sessions/{{sessionId}}/messages",
- "body": {
- "mode": "raw",
- "raw": "{\n \"phone\": \"[email protected]\",\n \"type\": \"text\",\n \"body\": \"Hello from OpenWA!\"\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- }
- }
- },
- {
- "name": "Send Image (URL)",
- "request": {
- "method": "POST",
- "url": "{{baseUrl}}/api/sessions/{{sessionId}}/messages",
- "body": {
- "mode": "raw",
- "raw": "{\n \"phone\": \"[email protected]\",\n \"type\": \"image\",\n \"media\": {\n \"url\": \"https://example.com/image.jpg\"\n },\n \"caption\": \"Check this out!\"\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- }
- }
- },
- {
- "name": "Get Message History",
- "request": {
- "method": "GET",
- "url": {
- "raw": "{{baseUrl}}/api/sessions/{{sessionId}}/[email protected]&limit=50",
- "host": ["{{baseUrl}}"],
- "path": ["api", "sessions", "{{sessionId}}", "messages"],
- "query": [
- {"key": "phone", "value": "[email protected]"},
- {"key": "limit", "value": "50"}
- ]
- }
- }
- }
- ]
- }
- ]
-}
+ -H "Content-Type: application/json" \
+ -d '{ "url": "https://github.com/openwa-plugins/chat-flow/releases/download/v1.0.0/chat-flow.zip" }'
+```
+
+#### POST /api/plugins/:id/enable
+
+Enable a plugin.
+
+```bash
+curl -X POST "$BASE/api/plugins/chat-flow/enable" \
+ -H "X-API-Key: $API_KEY"
```
-Download: [openwa-postman-collection.json](./assets/openwa-postman-collection.json)
+#### POST /api/plugins/:id/disable
-## 07.10 cURL Examples Collection
+Disable a plugin.
```bash
-#!/bin/bash
-# openwa-curl-examples.sh
+curl -X POST "$BASE/api/plugins/chat-flow/disable" \
+ -H "X-API-Key: $API_KEY"
+```
-BASE_URL="http://localhost:2785"
-API_KEY="your-api-key"
-SESSION_ID="default"
+#### PUT /api/plugins/:id/config
-# Health Check
-echo "=== Health Check ==="
-curl -s "$BASE_URL/health" | jq
+Update a plugin's base configuration.
-# Create Session
-echo "=== Create Session ==="
-curl -s -X POST "$BASE_URL/api/sessions" \
+```bash
+curl -X PUT "$BASE/api/plugins/chat-flow/config" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d "{\"id\": \"$SESSION_ID\", \"name\": \"Test Session\"}" | jq
+ -d '{ "config": { "apiKey": "sk-...", "replyDelayMs": 1500 } }'
+```
+
+#### PUT /api/plugins/:id/config/:sessionId
-# Get QR Code
-echo "=== Get QR Code ==="
-curl -s "$BASE_URL/api/sessions/$SESSION_ID/qr" \
- -H "X-API-Key: $API_KEY" | jq -r '.qr'
+Set (or clear with `{}`) a per-session plugin config override.
-# Send Text Message
-echo "=== Send Text Message ==="
-curl -s -X POST "$BASE_URL/api/sessions/$SESSION_ID/messages" \
+```bash
+curl -X PUT "$BASE/api/plugins/chat-flow/config/session-1" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "phone": "[email protected]",
- "type": "text",
- "body": "Hello from cURL!"
- }' | jq
-
-# Send Image
-echo "=== Send Image ==="
-curl -s -X POST "$BASE_URL/api/sessions/$SESSION_ID/messages" \
+ -d '{ "config": { "replyDelayMs": 3000 } }'
+```
+
+#### PUT /api/plugins/:id/sessions
+
+Set which sessions a session-scoped plugin is activated for (`["*"]` = all).
+
+```bash
+curl -X PUT "$BASE/api/plugins/chat-flow/sessions" \
-H "X-API-Key: $API_KEY" \
- -F "type=image" \
- -F "media=@./test-image.jpg" \
- -F "caption=Uploaded via cURL" | jq
-
-# Get Contacts
-echo "=== Get Contacts ==="
-curl -s "$BASE_URL/api/sessions/$SESSION_ID/contacts" \
- -H "X-API-Key: $API_KEY" | jq
-
-# Get Groups
-echo "=== Get Groups ==="
-curl -s "$BASE_URL/api/sessions/$SESSION_ID/groups" \
- -H "X-API-Key: $API_KEY" | jq
-
-# Create Webhook
-echo "=== Create Webhook ==="
-curl -s -X POST "$BASE_URL/api/sessions/$SESSION_ID/webhooks" \
+ -H "Content-Type: application/json" \
+ -d '{ "sessions": ["*"] }'
+```
+
+#### POST /api/plugins/:id/update
+
+Update an installed plugin in place from a URL.
+
+```bash
+curl -X POST "$BASE/api/plugins/chat-flow/update" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{
- "url": "https://your-server.com/webhook",
- "events": ["message.received", "message.ack"]
- }' | jq
+ -d '{ "url": "https://example.com/plugins/chat-flow-1.1.0.zip" }'
+```
+
+#### DELETE /api/plugins/:id
+
+Uninstall a plugin (built-ins protected).
+
+```bash
+curl -X DELETE "$BASE/api/plugins/chat-flow" \
+ -H "X-API-Key: $API_KEY"
```
----
-<div align="center">
+#### POST /mcp
-[← 06 - API Specification](./06-api-specification.md) · [Documentation Index](./README.md) · [Next: 08 - Development Guidelines →](./08-development-guidelines.md)
+MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer`; auth is enforced per tool call. See doc 24 for the tool catalog.
-</div>
+```bash
+# Initialize handshake
+curl -X POST "$BASE/mcp" \
+ -H "X-Api-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "openwa-collection", "version": "1.0.0" } } }'
+
+# List available tools
+curl -X POST "$BASE/mcp" \
+ -H "X-Api-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }'
+
+# Call a tool (arguments must match the tool's zod inputSchema)
+curl -X POST "$BASE/mcp" \
+ -H "X-Api-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "session_send_text", "arguments": { "sessionId": "default", "to": "6281234567890", "text": "Hello from MCP" } } }'
+```
+
+### 07.14 Real-time (WebSocket)
+
+Events are delivered over **Socket.IO** on the `/events` namespace (not a raw WebSocket). Use the `socket.io-client` package. Set `BASE_WS` (e.g. `ws://localhost:2785`) and `API_KEY`.
+
+```bash
+npm install socket.io-client
+```
+
+```js
+// realtime.mjs — run: BASE_WS=ws://localhost:2785 API_KEY=... SESSION_ID=main node realtime.mjs
+import { io } from 'socket.io-client';
+
+const BASE_WS = process.env.BASE_WS || 'ws://localhost:2785';
+const API_KEY = process.env.API_KEY;
+const SESSION_ID = process.env.SESSION_ID || 'main';
+
+const socket = io(`${BASE_WS}/events`, {
+ auth: { apiKey: API_KEY }, // or transport.headers / ?apiKey=
+});
+
+socket.on('connect', () => {
+ console.log('connected:', socket.id);
+ socket.emit('message', {
+ type: 'subscribe',
+ sessionId: SESSION_ID,
+ events: ['*'], // or e.g. ['message.received', 'session.status']
+ requestId: 'sub-1',
+ });
+});
+
+socket.on('message', (msg) => {
+ if (msg.type === 'event') {
+ console.log(`[${msg.payload.event}] ${msg.payload.sessionId}`, msg.payload.data);
+ } else {
+ console.log(`[${msg.type}]`, msg); // subscribed | unsubscribed | pong | error
+ }
+});
+
+socket.on('connect_error', (err) => console.error('connect_error:', err.message));
+socket.on('disconnect', (reason) => console.log('disconnected:', reason));
+```
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 53a8d3bce..b59b6d442 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -86,9 +86,9 @@ USER openwa
# Expose port
EXPOSE 2785
-# Health check
+# Health check (global API prefix is 'api'; readiness probes both databases)
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s \
- CMD curl -f http://localhost:2785/health || exit 1
+ CMD curl -f http://localhost:2785/api/health/ready || exit 1
# Start app
CMD ["node", "dist/main.js"]
@@ -173,11 +173,11 @@ services:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
- - ENCRYPTION_KEY=${ENCRYPTION_KEY}
+ - API_MASTER_KEY=${API_MASTER_KEY}
volumes:
- session-data:/app/.wwebjs_auth
healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:2785/health"]
+ test: ["CMD", "curl", "-f", "http://localhost:2785/api/health/ready"]
interval: 30s
timeout: 10s
retries: 3
@@ -200,8 +200,14 @@ volumes:
driver: local
```
-> [!NOTE]
-> If running more than 1 replica, use shared storage for `SESSION_DATA_PATH` (NFS/S3/CSI) and enable sticky sessions. Local volumes are not suitable for multi-replica setups.
+> [!IMPORTANT]
+> **Keep `replicas: 1`.** OpenWA is a single-process application: live engine state lives in an
+> in-memory `Map` in `SessionService` (`src/modules/session/session.service.ts`). Multi-replica is
+> **not** a supported topology — running two replicas against a shared `SESSION_DATA_PATH` makes two
+> browsers write the same WhatsApp LocalAuth directory and **corrupts the session** (forced logout /
+> ban). Shared storage and sticky sessions do **not** make multi-replica safe. See
+> [13 - Horizontal Scaling Guide](./13-horizontal-scaling.md) for the `replicas: 1` stance and the
+> (unimplemented) session-claim design that would be required first.
## 10.3 CI/CD Pipeline
@@ -362,6 +368,11 @@ flowchart TB
### Multi-Server Deployment
+> **Design sketch, not a supported topology.** OpenWA is single-process with in-memory engine state,
+> so the multi-`OpenWA` fan-out below would corrupt WhatsApp auth across replicas. It is retained only
+> as the target architecture once the session-claim design in
+> [13 - Horizontal Scaling Guide](./13-horizontal-scaling.md) is implemented. Deploy with `replicas: 1`.
+
```mermaid
flowchart TB
subgraph External["External"]
@@ -462,11 +473,10 @@ CACHE_MAX=1000
# ===========================================
ENGINE_TYPE=whatsapp-web.js
# ENGINE_TYPE=baileys
-# ENGINE_TYPE=mock
+# ENGINE_TYPE=baileys # whatsapp-web.js (default) | baileys; omit to use the dashboard selection
# Session
SESSION_DATA_PATH=./.wwebjs_auth
-MAX_SESSIONS=10
# Puppeteer (for whatsapp-web.js)
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
@@ -477,8 +487,9 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox
# SECURITY
# ===========================================
# Generate with: openssl rand -base64 32
-ENCRYPTION_KEY=your-32-byte-encryption-key-here
-API_KEY_MASTER=your-master-api-key
+API_MASTER_KEY=your-master-api-key
+# Optional HMAC pepper so a DB leak alone can't precompute key hashes
+API_KEY_PEPPER=optional-key-hashing-pepper
# ===========================================
# WEBHOOK
@@ -490,8 +501,9 @@ WEBHOOK_RETRY_DELAY=5000
# ===========================================
# RATE LIMITING
# ===========================================
-RATE_LIMIT_WINDOW=60000
-RATE_LIMIT_MAX=100
+# Three global per-IP windows (short/medium/long); defaults shown
+RATE_LIMIT_MEDIUM_TTL=60000
+RATE_LIMIT_MEDIUM_LIMIT=100
```
### Configuration Service
@@ -507,12 +519,10 @@ export default () => ({
url: process.env.REDIS_URL,
},
security: {
- encryptionKey: process.env.ENCRYPTION_KEY,
- masterApiKey: process.env.API_KEY_MASTER,
+ masterApiKey: process.env.API_MASTER_KEY,
},
session: {
dataPath: process.env.SESSION_DATA_PATH || './.wwebjs_auth',
- maxSessions: parseInt(process.env.MAX_SESSIONS, 10) || 10,
},
webhook: {
timeout: parseInt(process.env.WEBHOOK_TIMEOUT, 10) || 30000,
@@ -520,8 +530,12 @@ export default () => ({
retryDelay: parseInt(process.env.WEBHOOK_RETRY_DELAY, 10) || 5000,
},
rateLimit: {
- windowMs: parseInt(process.env.RATE_LIMIT_WINDOW, 10) || 60000,
- max: parseInt(process.env.RATE_LIMIT_MAX, 10) || 100,
+ shortTtl: parseInt(process.env.RATE_LIMIT_SHORT_TTL, 10) || 1000,
+ shortLimit: parseInt(process.env.RATE_LIMIT_SHORT_LIMIT, 10) || 10,
+ mediumTtl: parseInt(process.env.RATE_LIMIT_MEDIUM_TTL, 10) || 60000,
+ mediumLimit: parseInt(process.env.RATE_LIMIT_MEDIUM_LIMIT, 10) || 100,
+ longTtl: parseInt(process.env.RATE_LIMIT_LONG_TTL, 10) || 3600000,
+ longLimit: parseInt(process.env.RATE_LIMIT_LONG_LIMIT, 10) || 1000,
},
puppeteer: {
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
@@ -683,79 +697,65 @@ scrape_configs:
### Alert Rules
+These rules use the metric names OpenWA actually exports (`openwa_*`). The memory rule below uses a
+node-exporter metric — an **external** exporter, not the app — and is kept as a host-level example.
+
```yaml
# monitoring/alerts.yml
groups:
- name: openwa-alerts
rules:
- # High Error Rate
- - alert: HighErrorRate
- expr: |
- sum(rate(http_requests_total{status=~"5.."}[5m]))
- / sum(rate(http_requests_total[5m])) > 0.05
- for: 5m
+ # Service Down — openwa_up disappears (or the scrape fails)
+ - alert: ServiceDown
+ expr: up{job="openwa"} == 0 or absent(openwa_up)
+ for: 1m
labels:
severity: critical
annotations:
- summary: "High error rate detected"
- description: "Error rate is {{ $value | humanizePercentage }} in last 5 minutes"
-
- # API Response Time
- - alert: HighResponseTime
- expr: |
- histogram_quantile(0.95,
- sum(rate(http_request_duration_seconds_bucket[5m])) by (le)
- ) > 1
- for: 5m
- labels:
- severity: warning
- annotations:
- summary: "High API response time"
- description: "95th percentile response time is {{ $value }}s"
+ summary: "OpenWA service is down"
+ description: "The OpenWA application is not responding"
- # Session Down
+ # Session(s) disconnected
- alert: SessionDisconnected
- expr: session_status{status="disconnected"} > 0
+ expr: openwa_sessions{status="disconnected"} > 0
for: 2m
labels:
severity: warning
annotations:
summary: "WhatsApp session disconnected"
- description: "Session {{ $labels.session_id }} has been disconnected"
+ description: "{{ $value }} session(s) in disconnected state"
- # Memory Usage
- - alert: HighMemoryUsage
- expr: |
- (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes)
- / node_memory_MemTotal_bytes > 0.85
+ # Failed messages climbing
+ - alert: FailedMessagesRising
+ expr: rate(openwa_messages_failed_total[5m]) > 0
for: 5m
labels:
severity: warning
annotations:
- summary: "High memory usage"
- description: "Memory usage is {{ $value | humanizePercentage }}"
+ summary: "Messages are failing"
+ description: "openwa_messages_failed_total is increasing over the last 5 minutes"
- # Webhook Failures
- - alert: WebhookDeliveryFailures
- expr: |
- sum(rate(webhook_deliveries_total{status="failed"}[5m]))
- / sum(rate(webhook_deliveries_total[5m])) > 0.1
- for: 5m
+ # Process memory growth (app-exported RSS; ~2GB example threshold)
+ - alert: HighProcessMemory
+ expr: openwa_process_resident_memory_bytes > 2e9
+ for: 10m
labels:
severity: warning
annotations:
- summary: "High webhook delivery failure rate"
- description: "{{ $value | humanizePercentage }} webhooks failing"
+ summary: "High OpenWA process memory"
+ description: "RSS is {{ $value | humanize1024 }}B"
- # Service Down
- - alert: ServiceDown
- expr: up{job="openwa"} == 0
- for: 1m
+ # Host memory pressure — EXTERNAL (node-exporter), not exported by OpenWA
+ - alert: HighHostMemoryUsage
+ expr: |
+ (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes)
+ / node_memory_MemTotal_bytes > 0.85
+ for: 5m
labels:
- severity: critical
+ severity: warning
annotations:
- summary: "OpenWA service is down"
- description: "The OpenWA application is not responding"
+ summary: "High host memory usage"
+ description: "Host memory usage is {{ $value | humanizePercentage }}"
```
### AlertManager Configuration
@@ -802,146 +802,109 @@ receivers:
### Health Check Endpoint
+All health endpoints are `@Public()` (no API key) and `@SkipThrottle()`, and live under the global
+`api` prefix. There is **no** `/health/detailed` endpoint.
+
+| Endpoint | Purpose | Body | Codes |
+|----------|---------|------|-------|
+| `GET /api/health` | Basic check | `{ status, timestamp, version }` (version from `package.json`) | 200 |
+| `GET /api/health/live` | Liveness (deliberately static — a transient dependency outage must not KILL the pod) | `{ status: 'ok' }` | 200 |
+| `GET /api/health/ready` | Readiness — probes **both** databases (`main` + `data`, `SELECT 1`, 3s timeout each) and reports 503 while draining (graceful shutdown) | `{ status, details: { mainDatabase, dataDatabase } }` | 200 / 503 |
+
```typescript
// health/health.controller.ts
@Controller('health')
+@Public() // no API key required
+@SkipThrottle()
export class HealthController {
@Get()
- async basic(): Promise<{ status: string; timestamp: string }> {
- return {
- status: 'ok',
- timestamp: new Date().toISOString(),
- };
+ check(): { status: string; timestamp: string; version: string } {
+ return { status: 'ok', timestamp: new Date().toISOString(), version: APP_VERSION };
}
- // Requires API key (protected via auth guard/middleware)
- @Get('detailed')
- async detailed(): Promise<HealthCheckResult> {
- return {
- status: 'ok',
- version: process.env.npm_package_version,
- uptime: process.uptime(),
- timestamp: new Date().toISOString(),
- checks: {
- database: await this.checkDatabase(),
- redis: await this.checkRedis(),
- sessions: await this.getSessionStats(),
- },
- };
+ @Get('live')
+ liveness(): { status: string } {
+ return { status: 'ok' };
+ }
+
+ @Get('ready')
+ async readiness(): Promise<HealthCheckResult> {
+ // 503 while draining so the LB stops routing before teardown.
+ if (this.shutdownService.isShuttingDown()) {
+ throw new ServiceUnavailableException({ status: 'error', details: { shutdown: { status: 'draining' } } });
+ }
+ const [main, data] = await Promise.all([
+ this.probeDatabase(this.mainDataSource),
+ this.probeDatabase(this.dataDataSource),
+ ]);
+ const details = { mainDatabase: { status: main }, dataDatabase: { status: data } };
+ if (main === 'down' || data === 'down') {
+ throw new ServiceUnavailableException({ status: 'error', details });
+ }
+ return { status: 'ok', details };
}
}
```
### Prometheus Metrics Implementation
-```typescript
-// metrics/metrics.service.ts
-import { Injectable } from '@nestjs/common';
-import { Registry, Counter, Gauge, Histogram, collectDefaultMetrics } from 'prom-client';
+The metrics surface is small, so OpenWA emits Prometheus text exposition format (v0.0.4) **by hand** —
+there is **no `prom-client` dependency** and **no `collectDefaultMetrics`**. `MetricsService` reads an
+aggregate overview from `StatsService` plus `process.memoryUsage()`, memoizes the rendered text for a
+short TTL (~5s, so back-to-back scrapes don't repeat the DB scan), and exposes it at
+`GET /api/metrics`.
+Access is **disabled by default**: the endpoint returns **404** unless `METRICS_TOKEN` is set. When
+set, scrapers must send `Authorization: Bearer <token>` (compared with `timingSafeEqual`); a missing or
+wrong token returns 401. The token is **separate** from the API key — the route is `@Public()` (skips
+the API-key guard) and `@SkipThrottle()`.
+
+```typescript
+// metrics/metrics.service.ts (dependency-free; emits text v0.0.4 by hand)
@Injectable()
export class MetricsService {
- private readonly registry: Registry;
-
- // Counters
- readonly httpRequestsTotal: Counter;
- readonly messagesSentTotal: Counter;
- readonly webhookDeliveriesTotal: Counter;
-
- // Gauges
- readonly activeSessions: Gauge;
- readonly connectedSessions: Gauge;
- readonly queueSize: Gauge;
-
- // Histograms
- readonly httpRequestDuration: Histogram;
- readonly messageSendDuration: Histogram;
- readonly webhookDeliveryDuration: Histogram;
-
- constructor() {
- this.registry = new Registry();
- collectDefaultMetrics({ register: this.registry });
-
- // HTTP Metrics
- this.httpRequestsTotal = new Counter({
- name: 'http_requests_total',
- help: 'Total HTTP requests',
- labelNames: ['method', 'path', 'status'],
- registers: [this.registry],
- });
-
- this.httpRequestDuration = new Histogram({
- name: 'http_request_duration_seconds',
- help: 'HTTP request duration in seconds',
- labelNames: ['method', 'path'],
- buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],
- registers: [this.registry],
- });
-
- // Message Metrics
- this.messagesSentTotal = new Counter({
- name: 'messages_sent_total',
- help: 'Total messages sent',
- labelNames: ['session_id', 'type', 'status'],
- registers: [this.registry],
- });
-
- this.messageSendDuration = new Histogram({
- name: 'message_send_duration_seconds',
- help: 'Message send duration in seconds',
- labelNames: ['session_id', 'type'],
- buckets: [0.1, 0.5, 1, 2, 5, 10],
- registers: [this.registry],
- });
-
- // Session Metrics
- this.activeSessions = new Gauge({
- name: 'active_sessions_total',
- help: 'Number of active sessions',
- registers: [this.registry],
- });
-
- this.connectedSessions = new Gauge({
- name: 'connected_sessions_total',
- help: 'Number of connected sessions',
- registers: [this.registry],
- });
-
- // Webhook Metrics
- this.webhookDeliveriesTotal = new Counter({
- name: 'webhook_deliveries_total',
- help: 'Total webhook deliveries',
- labelNames: ['event', 'status'],
- registers: [this.registry],
- });
-
- this.webhookDeliveryDuration = new Histogram({
- name: 'webhook_delivery_duration_seconds',
- help: 'Webhook delivery duration in seconds',
- labelNames: ['event'],
- buckets: [0.1, 0.5, 1, 2, 5, 10, 30],
- registers: [this.registry],
- });
-
- // Queue Metrics
- this.queueSize = new Gauge({
- name: 'message_queue_size',
- help: 'Current size of message queue',
- labelNames: ['queue_name'],
- registers: [this.registry],
- });
- }
-
- getMetrics(): Promise<string> {
- return this.registry.metrics();
+ constructor(
+ private readonly config: ConfigService,
+ private readonly statsService: StatsService,
+ ) {}
+
+ async render(): Promise<string> {
+ const overview = await this.statsService.getOverview();
+ const mem = process.memoryUsage();
+ const lines: string[] = [];
+ // ... gauge() helper pushes `# HELP` / `# TYPE` / value lines ...
+ gauge('openwa_up', '...', 1);
+ gauge('openwa_process_uptime_seconds', '...', Math.round(process.uptime()));
+ gauge('openwa_process_resident_memory_bytes', '...', mem.rss);
+ gauge('openwa_process_heap_used_bytes', '...', mem.heapUsed);
+ gauge('openwa_sessions_total', '...', overview.sessions.total);
+ gauge('openwa_sessions_active', '...', overview.sessions.active);
+ // openwa_sessions{status="..."} — one line per status
+ // openwa_messages_total{direction="outgoing"|"incoming"}
+ // openwa_messages_failed_total
+ return lines.join('\n') + '\n';
}
}
```
+**Exported metric names** (the complete set — nothing else is emitted):
+
+| Metric | Type | Labels | Meaning |
+|--------|------|--------|---------|
+| `openwa_up` | gauge | — | Always `1` when scraped |
+| `openwa_process_uptime_seconds` | gauge | — | Process uptime |
+| `openwa_process_resident_memory_bytes` | gauge | — | RSS |
+| `openwa_process_heap_used_bytes` | gauge | — | V8 heap used |
+| `openwa_sessions_total` | gauge | — | Configured sessions |
+| `openwa_sessions_active` | gauge | — | READY (active) sessions |
+| `openwa_sessions` | gauge | `status` | Session count per status |
+| `openwa_messages_total` | counter | `direction` (`incoming`/`outgoing`) | Messages by direction |
+| `openwa_messages_failed_total` | counter | — | Messages in FAILED state |
+
### Grafana Dashboard Definition
```json
-// monitoring/grafana/dashboards/openwa.json
+// monitoring/grafana/dashboards/openwa.json — panels use the openwa_* metrics OpenWA exports
{
"title": "OpenWA Dashboard",
"uid": "openwa-main",
@@ -951,7 +914,7 @@ export class MetricsService {
"type": "stat",
"gridPos": { "x": 0, "y": 0, "w": 6, "h": 4 },
"targets": [
- { "expr": "active_sessions_total" }
+ { "expr": "openwa_sessions_active" }
]
},
{
@@ -959,61 +922,48 @@ export class MetricsService {
"type": "stat",
"gridPos": { "x": 6, "y": 0, "w": 6, "h": 4 },
"targets": [
- { "expr": "sum(increase(messages_sent_total[24h]))" }
+ { "expr": "increase(openwa_messages_total{direction=\"outgoing\"}[24h])" }
]
},
{
- "title": "Error Rate",
- "type": "gauge",
+ "title": "Failed Messages",
+ "type": "stat",
"gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 },
"targets": [
- {
- "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"
- }
+ { "expr": "openwa_messages_failed_total" }
]
},
{
- "title": "Request Rate",
+ "title": "Sessions by Status",
"type": "timeseries",
"gridPos": { "x": 0, "y": 4, "w": 12, "h": 8 },
"targets": [
- { "expr": "sum(rate(http_requests_total[5m])) by (status)", "legendFormat": "{{status}}" }
+ { "expr": "openwa_sessions", "legendFormat": "{{status}}" }
]
},
{
- "title": "Response Time (p95)",
+ "title": "Message Rate by Direction",
"type": "timeseries",
"gridPos": { "x": 12, "y": 4, "w": 12, "h": 8 },
"targets": [
- {
- "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))"
- }
+ { "expr": "rate(openwa_messages_total[5m])", "legendFormat": "{{direction}}" }
]
},
{
- "title": "Messages by Type",
- "type": "piechart",
- "gridPos": { "x": 0, "y": 12, "w": 8, "h": 8 },
- "targets": [
- { "expr": "sum(messages_sent_total) by (type)", "legendFormat": "{{type}}" }
- ]
- },
- {
- "title": "Webhook Delivery Success Rate",
+ "title": "Process Memory",
"type": "timeseries",
- "gridPos": { "x": 8, "y": 12, "w": 8, "h": 8 },
+ "gridPos": { "x": 0, "y": 12, "w": 12, "h": 8 },
"targets": [
- {
- "expr": "sum(rate(webhook_deliveries_total{status=\"success\"}[5m])) / sum(rate(webhook_deliveries_total[5m])) * 100"
- }
+ { "expr": "openwa_process_resident_memory_bytes / 1024 / 1024", "legendFormat": "RSS (MB)" },
+ { "expr": "openwa_process_heap_used_bytes / 1024 / 1024", "legendFormat": "Heap used (MB)" }
]
},
{
- "title": "Memory Usage",
- "type": "timeseries",
- "gridPos": { "x": 16, "y": 12, "w": 8, "h": 8 },
+ "title": "Uptime",
+ "type": "stat",
+ "gridPos": { "x": 12, "y": 12, "w": 12, "h": 8 },
"targets": [
- { "expr": "process_resident_memory_bytes / 1024 / 1024", "legendFormat": "Memory (MB)" }
+ { "expr": "openwa_process_uptime_seconds" }
]
}
]
@@ -1082,17 +1032,25 @@ this.logger.log('Message sent', {
### Key Metrics to Monitor
-| Category | Metric | Description | Alert Threshold |
-|----------|--------|-------------|-----------------|
-| **API** | `http_requests_total` | Request count by status | Error rate > 5% |
-| **API** | `http_request_duration_seconds` | Request latency | p95 > 1s |
-| **Sessions** | `active_sessions_total` | Total sessions | Near limit |
-| **Sessions** | `connected_sessions_total` | Connected sessions | < active |
-| **Messages** | `messages_sent_total` | Messages sent | Sudden drop |
-| **Messages** | `message_send_duration_seconds` | Send latency | p95 > 5s |
-| **Webhooks** | `webhook_deliveries_total` | Delivery status | Failure > 10% |
-| **System** | `process_resident_memory_bytes` | Memory usage | > 80% |
-| **System** | `nodejs_eventloop_lag_seconds` | Event loop lag | > 100ms |
+These are the metrics OpenWA actually exports at `GET /api/metrics`:
+
+| Category | Metric | Description | Alert Idea |
+|----------|--------|-------------|------------|
+| **Liveness** | `openwa_up` | Always `1` when scraped (absence/scrape-failure = down) | Target down |
+| **Sessions** | `openwa_sessions_total` | Configured sessions | Near your expected session count |
+| **Sessions** | `openwa_sessions_active` | READY (active) sessions | Drops below expected |
+| **Sessions** | `openwa_sessions{status="..."}` | Per-status counts (e.g. `disconnected`, `failed`) | `disconnected`/`failed` > 0 |
+| **Messages** | `openwa_messages_total{direction="outgoing"}` | Outgoing messages | Sudden drop |
+| **Messages** | `openwa_messages_total{direction="incoming"}` | Incoming messages | Sudden drop |
+| **Messages** | `openwa_messages_failed_total` | Messages in FAILED state | Rising rate |
+| **System** | `openwa_process_resident_memory_bytes` | RSS | Growth / near limit |
+| **System** | `openwa_process_heap_used_bytes` | V8 heap used | Growth |
+| **System** | `openwa_process_uptime_seconds` | Process uptime | Frequent restarts (resets) |
+
+> OpenWA does **not** expose request-rate, latency-histogram, webhook, queue, or Node default
+> (`nodejs_*`) metrics. For host/container-level signals (CPU, memory pressure, event-loop), scrape
+> external exporters: `up` and `container_memory_usage_bytes` come from blackbox/cAdvisor, and
+> `node_*` from node-exporter — not from the app.
## 10.7 Backup & Recovery
@@ -1175,6 +1133,11 @@ echo "Restore completed"
### Vertical Scaling
+OpenWA scales **vertically** — add CPU/RAM to a single instance. The table below is **unbenchmarked
+starting guidance**, not measured figures; actual usage depends heavily on engine choice
+(whatsapp-web.js spawns a Chromium per session; Baileys is far lighter), message volume, and media.
+Size up from your own monitoring.
+
| Sessions | RAM | CPU | Storage |
|----------|-----|-----|---------|
| 1-5 | 2GB | 2 cores | 20GB |
@@ -1182,14 +1145,13 @@ echo "Restore completed"
| 10-20 | 8GB | 8 cores | 100GB |
| 20+ | 16GB+ | 16+ cores | 200GB+ |
-### Horizontal Scaling Checklist
+### Horizontal Scaling
-- [ ] Shared PostgreSQL database
-- [ ] Redis for session affinity
-- [ ] Shared file storage (S3/NFS)
-- [ ] Load balancer with sticky sessions
-- [ ] Health check endpoints
-- [ ] Graceful shutdown handling
+**Not currently supported.** OpenWA is a single-process application with in-memory engine state, so
+multiple replicas against a shared session volume corrupt WhatsApp auth. Run exactly **one** API
+instance per session-data volume (`replicas: 1`). The DB-backed session registry / node-claim design
+that would be required to scale out is documented — as a future design sketch, not a shipped feature —
+in [13 - Horizontal Scaling Guide](./13-horizontal-scaling.md).
---
<div align="center">
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index 05e96246e..8c7f0893a 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -79,17 +79,17 @@ docker compose restart openwa
```bash
# Check health
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
# Check all sessions reconnected
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions | jq '.[].status'
# Send test message
-curl -X POST http://localhost:2785/api/sessions/default/messages \
+curl -X POST http://localhost:2785/api/sessions/default/messages/send-text \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{"phone": "[email protected]", "type": "text", "body": "Test after restart"}'
+ -d '{"chatId": "[email protected]", "text": "Test after restart"}'
```
**Rollback:** Restore from backup if data corruption detected (see Runbook: Restore from Backup)
@@ -116,9 +116,11 @@ curl -H "X-API-Key: $API_KEY" \
# 2. Check if auto-reconnect is working
docker compose logs openwa 2>&1 | grep -i "{sessionId}" | tail -20
-# 3. Try session restart
+# 3. Try session restart (stop then start — there is no /restart route)
curl -X POST -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/restart
+ http://localhost:2785/api/sessions/{sessionId}/stop
+curl -X POST -H "X-API-Key: $API_KEY" \
+ http://localhost:2785/api/sessions/{sessionId}/start
# 4. Wait for reconnection (30 seconds)
sleep 30
@@ -133,12 +135,12 @@ curl -H "X-API-Key: $API_KEY" \
# - Has the phone been inactive for 14+ days?
# 7. If need to re-scan QR:
+# The endpoint returns a PNG data URL: { "qrCode": "data:image/png;base64,...", "status": "qr_ready" }
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/qr
-# Display QR in terminal (requires qrencode)
-curl -s -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/{sessionId}/qr?format=raw" | qrencode -t ANSI
+# Display QR in terminal: there is no raw/format param — consume the `session.qr`
+# webhook/WebSocket event to get the raw QR string for qrencode.
```
**Verification:**
@@ -147,13 +149,13 @@ curl -s -H "X-API-Key: $API_KEY" \
# Session connected
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId} | jq '.status'
-# Expected: "CONNECTED"
+# Expected: "ready"
# Test message
-curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages \
+curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{"phone": "[email protected]", "type": "text", "body": "Session reconnected"}'
+ -d '{"chatId": "[email protected]", "text": "Session reconnected"}'
```
---
@@ -176,26 +178,27 @@ docker stats --no-stream openwa
free -m
# 2. Identify memory consumers
-# Check per-session memory
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/metrics/memory
+# Process-wide memory: scrape /api/metrics (Prometheus text, Bearer METRICS_TOKEN)
+curl -H "Authorization: Bearer $METRICS_TOKEN" \
+ http://localhost:2785/api/metrics \
+ | grep -E "openwa_process_resident_memory_bytes|openwa_process_heap_used_bytes"
# 3. Check for memory leaks
docker compose logs openwa 2>&1 | grep -i "heap\|memory\|gc"
# 4. Immediate actions:
-# A. Clear message cache
-curl -X POST -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/cache/clear
+# A. Clear the in-process cache (no runtime cache-clear API — restart the container;
+# if using Redis, flush via redis-cli)
+docker compose restart openwa
# B. Restart container (will reconnect sessions)
docker compose restart openwa
# C. If caused by too many sessions:
-# List sessions sorted by memory
+# List sessions (no sort param); process memory is in stats/overview (memoryUsage, MB)
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions?sort=memory
+ http://localhost:2785/api/sessions/stats/overview
# Consider removing unused sessions
@@ -235,9 +238,9 @@ curl -H "X-API-Key: $API_KEY" \
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks
-# 2. Check recent webhook logs
-curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/logs?status=failed&limit=20"
+# 2. Check recent webhook deliveries
+# There is no webhook-delivery log API — inspect the server logs / audit trail instead:
+docker compose logs openwa 2>&1 | grep -i "webhook" | tail -20
# 3. Identify failure reason:
# A. Endpoint not responding
@@ -260,27 +263,30 @@ curl -X POST -H "X-API-Key: $API_KEY" \
# 5. Fix based on cause:
# A. Update webhook URL
-curl -X PATCH http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
+curl -X PUT http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://new-endpoint.com/webhook"}'
# B. Update authentication
-curl -X PATCH http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
+curl -X PUT http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"headers": {"Authorization": "Bearer new-token"}}'
-# C. Temporarily disable and re-enable
-curl -X POST -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/disable
+# C. Temporarily disable and re-enable (toggle the `active` boolean)
+curl -X PUT http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"active": false}'
-curl -X POST -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/enable
+curl -X PUT http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId} \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"active": true}'
# 6. Retry failed deliveries
-curl -X POST -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/retry-failed
+# No retry-failed API — failed deliveries auto-retry with exponential backoff (doc 06 §6.6)
```
**Verification:**
@@ -289,12 +295,11 @@ curl -X POST -H "X-API-Key: $API_KEY" \
# Webhook test successful
curl -X POST -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/test
-# Expected: {"status": "success"}
+# Expected: {"success": true, "statusCode": 200}
# Recent deliveries successful
-curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/logs?limit=5" | jq '.[].status'
-# Expected: all "success"
+# No delivery-log API — confirm via the server logs / audit trail:
+docker compose logs openwa 2>&1 | grep -i "webhook" | tail -5
```
---
@@ -316,8 +321,7 @@ curl -H "X-API-Key: $API_KEY" \
```bash
# 1. Pre-maintenance checks (1 hour before)
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed
+curl http://localhost:2785/api/health/ready
docker stats --no-stream
# 2. Notify users (via webhook or external system)
@@ -349,7 +353,7 @@ docker compose up -d
# 9. Wait for health
sleep 30
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
# 10. Verify all sessions reconnected
curl -H "X-API-Key: $API_KEY" \
@@ -364,12 +368,11 @@ curl -H "X-API-Key: $API_KEY" \
```bash
# All services healthy
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed
+curl http://localhost:2785/api/health/ready
# All sessions connected
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions | jq '[.[] | select(.status == "CONNECTED")] | length'
+ http://localhost:2785/api/sessions | jq '[.[] | select(.status == "ready")] | length'
# Test message flow
# Send test message and verify webhook received
@@ -408,7 +411,7 @@ docker compose down
# 5. Update version in docker-compose.yml
# Change: image: ghcr.io/rmyndharis/openwa:0.1.0
-# To: image: ghcr.io/rmyndharis/openwa:0.2.0
+# To: image: ghcr.io/rmyndharis/openwa:0.7.3
# 6. Pull new image
docker compose pull
@@ -423,11 +426,10 @@ docker compose up -d
# 9. Wait for health
sleep 30
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
# 10. Verify version
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed | jq '.version'
+curl http://localhost:2785/api/health | jq '.version'
# 11. Verify all sessions
curl -H "X-API-Key: $API_KEY" \
@@ -441,9 +443,8 @@ curl -H "X-API-Key: $API_KEY" \
```bash
# Correct version
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed | jq '.version'
-# Expected: "0.2.0"
+curl http://localhost:2785/api/health | jq '.version'
+# Expected: "0.7.3"
# All tests pass
./scripts/smoke-test.sh
@@ -547,7 +548,7 @@ docker compose down
# 4. Start the app and CONFIRM an existing API key still authenticates
docker compose up -d
-curl -s -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth/validate
+curl -s -X POST -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth/validate
```
> Restoring `main.sqlite` is the whole point: it carries the API keys and audit log.
@@ -558,7 +559,7 @@ curl -s -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth/validat
```bash
# Health check
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
# Verify sessions
curl -H "X-API-Key: $API_KEY" \
@@ -566,7 +567,7 @@ curl -H "X-API-Key: $API_KEY" \
# Verify data integrity
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/messages?limit=1
+ "http://localhost:2785/api/sessions/default/messages?limit=1"
```
---
@@ -605,7 +606,7 @@ sudo systemctl restart nginx
docker compose restart nginx
# Verify HTTPS
-curl -v https://api.your-domain.com/health
+curl -v https://api.your-domain.com/api/health
```
---
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 5273cc288..83f65c14f 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -6,15 +6,15 @@
```bash
# Basic health check
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
-# Detailed health check
+# Readiness (DB) check
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/health/detailed
+ http://localhost:2785/api/health/ready
# Check specific session
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/health
+ http://localhost:2785/api/sessions/{sessionId}
# Check all services
docker compose ps
@@ -324,17 +324,15 @@ WA_QR_TIMEOUT=60000
**Diagnostic:**
```bash
-# Check message status
+# Check message history
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/messages/{messageId}
+ http://localhost:2785/api/sessions/{sessionId}/messages/{chatId}/history
-# Check queue status
+# Check queue / infra status (ADMIN)
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/queues/status
+ http://localhost:2785/api/infra/status
-# Check rate limit status
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/rate-limit
+# Rate limiting is global (throttler, env-configured) — there is no per-session rate-limit endpoint
```
**Common Causes:**
@@ -358,9 +356,9 @@ const validFormats = [
];
// API to check if number exists
-// GET /api/sessions/{id}/contacts/{phone}/exists
+// GET /api/sessions/{id}/contacts/check/{number}
curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/default/contacts/628123456789/exists"
+ "http://localhost:2785/api/sessions/default/contacts/check/628123456789"
```
### Issue: Media Upload Fails
@@ -391,13 +389,14 @@ environment:
**Media Compression:**
```bash
-# Compress image before sending
-curl -X POST http://localhost:2785/api/sessions/{id}/messages \
+# Send an image (by URL or base64)
+curl -X POST http://localhost:2785/api/sessions/{id}/messages/send-image \
-H "X-API-Key: $API_KEY" \
- -F "type=image" \
- -F "compress=true" # Enable compression
+ -H "Content-Type: application/json" \
+ -d '{
+ "chatId": "[email protected]",
+ "url": "https://example.com/image.jpg"
+ }'
```
### Issue: Webhook Not Receiving Messages
@@ -414,9 +413,8 @@ curl -X POST http://localhost:2785/api/sessions/{id}/messages \
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks
-# Check webhook logs
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/logs?limit=20
+# No webhook-delivery log API — check the server logs / audit trail instead
+docker compose logs openwa 2>&1 | grep -i webhook
# Test webhook endpoint
curl -X POST http://your-webhook-url \
@@ -457,9 +455,9 @@ webhook:
# Check memory usage
docker stats openwa --no-stream
-# Check per-session memory
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/metrics/memory
+# Check process memory (Prometheus text; read openwa_process_resident_memory_bytes)
+curl -H "Authorization: Bearer $METRICS_TOKEN" \
+ http://localhost:2785/api/metrics
# Expected: ~300-500MB per session (whatsapp-web.js / Chromium engine)
# With ENGINE_TYPE=baileys the footprint is significantly lower (no Chromium)
@@ -506,15 +504,14 @@ services:
```bash
# Measure API response time
-time curl http://localhost:2785/health
+time curl http://localhost:2785/api/health
-# Check database query times
-curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/metrics/database
+# Check database readiness (no dedicated DB metric)
+curl http://localhost:2785/api/health/ready
-# Check queue depth
+# Check queue / infra status (ADMIN)
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/queues/status
+ http://localhost:2785/api/infra/status
```
**Solutions:**
@@ -597,20 +594,18 @@ flowchart TD
**Solutions:**
```bash
-# Check migration status
-npm run migration:status
-
-# Show pending migrations
+# Show migration status (executed + pending)
npm run migration:show
-# Force run specific migration
-npm run migration:run -- --name CreateSessionsTable
+# Run all pending migrations
+npm run migration:run
# Rollback last migration
npm run migration:revert
-# Sync schema (development only!)
-npm run schema:sync
+# Schema is managed by migrations (there is no schema:sync)
+# The auth/audit DB has parallel :main variants, e.g.:
+npm run migration:run:main
```
## 12.6 Docker Issues
@@ -710,34 +705,32 @@ curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{id}/groups
# Send to group
-curl -X POST http://localhost:2785/api/sessions/{id}/messages \
+curl -X POST http://localhost:2785/api/sessions/{id}/messages/send-text \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "phone": "[email protected]",
- "type": "text",
- "body": "Hello group!"
+ "chatId": "[email protected]",
+ "text": "Hello group!"
}'
```
**Q: How to handle message replies?**
```bash
# Reply to specific message
-curl -X POST http://localhost:2785/api/sessions/{id}/messages \
+curl -X POST http://localhost:2785/api/sessions/{id}/messages/reply \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
- "phone": "[email protected]",
- "type": "text",
- "body": "This is a reply",
- "quotedMessageId": "ABC123_DEF456"
+ "chatId": "[email protected]",
+ "quotedMessageId": "ABC123_DEF456",
+ "text": "This is a reply"
}'
```
**Q: How to use with n8n?**
-> See [n8n Integration Guide](./examples/n8n-integration.md). Quick setup:
+> See [n8n Integration Guide](./22-n8n-integration.md). Quick setup:
> 1. Add HTTP Request node
-> 2. Set URL: `http://openwa:2785/api/sessions/{id}/messages`
+> 2. Set URL: `http://openwa:2785/api/sessions/{id}/messages/send-text`
> 3. Add header: `X-API-Key: your-key`
> 4. Configure webhook trigger for incoming messages
@@ -806,6 +799,7 @@ available_events:
- message.received # New incoming message
- message.sent # Message sent
- message.ack # Message status update (sent, delivered, read)
+ - message.failed # Receipt resolved to failed
- message.revoked # Message deleted
- message.reaction # Reaction added, changed, or removed
@@ -815,14 +809,10 @@ available_events:
- session.authenticated # Session authenticated
- session.disconnected # Session disconnected
- # Groups
- - group.join # Someone joined group
- - group.leave # Someone left group
- - group.update # Group settings changed
-
- # Contacts
- - contact.update # Contact info changed
- - presence.update # Contact online/offline status
+ # Groups (reserved but NOT currently emitted — accepted in events list, never delivered)
+ - group.join # reserved, not emitted
+ - group.leave # reserved, not emitted
+ - group.update # reserved, not emitted
```
**Q: Webhook payload format?**
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index baf0d1db9..eaa9584f0 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -519,11 +519,11 @@ groups:
### Health Check Endpoints
-| Endpoint | Purpose |
-| ---------------------- | ------------------------------- |
-| `/api/health` | Liveness probe |
-| `/api/health/ready` | Readiness probe |
-| `/api/health/detailed` | Full status with DB/Redis check |
+| Endpoint | Purpose |
+| ------------------- | ---------------------------------------------------------------- |
+| `/api/health` | Basic health check — returns `status`, `timestamp`, `version` |
+| `/api/health/live` | Liveness probe (static `ok`; reflects process liveness only) |
+| `/api/health/ready` | Readiness probe — verifies the main + data databases respond (returns 503 while draining or if a DB is down) |
---
<div align="center">
diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.md
index 0f34d9fc1..b9c454cbd 100644
--- a/docs/15-project-roadmap.md
+++ b/docs/15-project-roadmap.md
@@ -313,7 +313,7 @@ gantt
Message queue :p2-18, after p2-17, 2d
section Dashboard (Week 8-10)
- React + shadcn/ui setup :p2-19, after p2-18, 3d
+ React + bespoke-CSS setup :p2-19, after p2-18, 3d
Authentication UI :p2-20, after p2-19, 3d
Session management :p2-21, after p2-20, 4d
QR code display :p2-22, after p2-21, 2d
@@ -550,26 +550,27 @@ vars are removed. Ships with a migration guide.
#### Incremental themes — SDK, Developer Tools & Observability
-Delivered additively whenever ready (so they land in `0.2.x`/`0.3.x` per SemVer, not gated to one version):
+Delivered additively whenever ready, per SemVer (not gated to one version). The client SDKs and Prometheus metrics have **shipped** (v0.7.x); the rest remain open.
-| Feature | Priority | Description |
-| ---------------------- | -------- | ------------------------------- |
-| JavaScript/Node.js SDK | P1 | Official client library |
-| Python SDK | P2 | Python client library |
-| Docs Site | P1 | Documentation website |
-| Postman Collection | P1 | Ready-to-use API collection |
-| Video Tutorials | P2 | Getting started video series |
-| Example Projects | P1 | Real-world integration examples |
+| Feature | Priority | Status | Description |
+| ---------------------- | -------- | ------ | ------------------------------- |
+| JavaScript/Node.js SDK | P1 | ✅ Shipped (`@rmyndharis/openwa`) | Official client library |
+| Python SDK | P2 | ✅ Shipped (`rmyndharis-openwa`) | Python client library |
+| PHP SDK | P2 | ✅ Shipped (`rmyndharis/openwa`) | PHP client library |
+| Postman Collection | P1 | ◐ cURL collection (doc 07); Postman export TBD | Ready-to-use API collection |
+| Docs Site | P1 | ☐ Open | Documentation website |
+| Video Tutorials | P2 | ☐ Open | Getting started video series |
+| Example Projects | P1 | ◐ A few under `docs/examples/` | Real-world integration examples |
**Performance & Observability**
-| Feature | Priority | Description |
-| ---------------------- | -------- | -------------------------------- |
-| Prometheus Metrics | P1 | /metrics endpoint for monitoring |
-| Grafana Dashboard | P2 | Pre-built monitoring dashboard |
-| OpenTelemetry Tracing | P2 | Distributed tracing support |
-| Performance Benchmarks | P1 | Documented performance metrics |
-| Memory Optimization | P1 | Reduced memory per session |
+| Feature | Priority | Status | Description |
+| ---------------------- | -------- | ------ | -------------------------------- |
+| Prometheus Metrics | P1 | ✅ Shipped (`GET /api/metrics`, `openwa_*`) | /metrics endpoint for monitoring |
+| Grafana Dashboard | P2 | ☐ Open | Pre-built monitoring dashboard |
+| OpenTelemetry Tracing | P2 | ☐ Open | Distributed tracing support |
+| Performance Benchmarks | P1 | ☐ Open | Documented performance metrics |
+| Memory Optimization | P1 | ☐ Open | Reduced memory per session |
### v1.0.0 - Enterprise Ready
diff --git a/docs/16-risk-management.md b/docs/16-risk-management.md
index d4d0ae667..a8b578399 100644
--- a/docs/16-risk-management.md
+++ b/docs/16-risk-management.md
@@ -194,7 +194,7 @@ flowchart TB
### Dependency Security
- [ ] npm audit clean
-- [ ] Snyk scan passed
+- [ ] Dependabot alerts reviewed
- [ ] Dependencies up to date
- [ ] No known vulnerabilities
```
@@ -289,6 +289,8 @@ Dependencies (`whatsapp-web.js`, Puppeteer, NestJS, etc.) may have vulnerabiliti
**Mitigation Strategies:**
+> **Current state:** the real dependency check is an inline `npm audit --audit-level=critical` step in `ci.yml` (runs on push / PR — not on a daily schedule), plus Dependabot PRs (`.github/dependabot.yml`: npm for `/` and `/dashboard`, weekly). There is **no** standalone `security.yml` and **no** Snyk integration. The workflow below is a recommended enhancement to add scheduled scanning.
+
```yaml
# .github/workflows/security.yml
name: Security Scan
@@ -318,10 +320,10 @@ jobs:
| Action | Frequency |
|--------|-----------|
-| npm audit | Daily (automated) |
-| Snyk scan | Daily (automated) |
-| Minor updates | Weekly |
-| Major updates | Monthly (with testing) |
+| npm audit (`--audit-level=critical`, inline in CI) | Every push / PR |
+| Snyk scan | Not configured (planned) |
+| Dependabot PRs (npm: `/` and `/dashboard`) | Weekly |
+| Major updates | Reviewed manually |
| Security patches | Immediate |
---
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index 02617afc0..782c42f97 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -9,28 +9,34 @@ The dashboard is a web-based management interface for OpenWA that lets users man
```mermaid
flowchart LR
subgraph Frontend
- REACT[React 18]
- VITE[Vite 5]
+ REACT[React 19]
+ VITE[Vite 8]
TS[TypeScript]
- TW[Tailwind CSS]
- SHADCN[shadcn/ui]
- LUCIDE[Lucide Icons]
+ CSS[Hand-written per-page CSS]
+ LUCIDE[lucide-react Icons]
end
subgraph State
TANSTACK[TanStack Query]
- ZUSTAND[Zustand]
+ CTX[React Context]
end
subgraph Backend
API[OpenWA API]
- WS[WebSocket]
+ WS[socket.io WebSocket]
end
Frontend --> State
State --> Backend
```
+The styling foundation is **plain CSS** — there is no Tailwind, no shadcn/ui, and no CSS-in-JS.
+Each page and shared component ships its own stylesheet colocated beside the source
+(`Sessions.tsx` + `Sessions.css`, `Layout.tsx` + `Layout.css`, ...), imported directly by the
+component. Icons come from `lucide-react`; charts from `recharts`; i18n from `react-i18next`.
+Client state is **TanStack Query** for server data (see `src/hooks/queries.ts`) plus a couple of
+small React Context providers (`useRole`, `useTheme`) — there is no Zustand store.
+
### Design Principles
1. **Minimalist** - Clean, uncluttered interface
@@ -41,59 +47,57 @@ flowchart LR
## 17.2 Information Architecture
+The dashboard is a **flat, single-level route table** (see `src/App.tsx`). Each sidebar entry maps
+to one top-level page — there are no nested detail/`:id` routes; a session or chat is opened in-place
+(modals / split panes) rather than via its own URL.
+
```mermaid
flowchart TB
- subgraph Dashboard
- HOME[Dashboard Home]
- SESSIONS[Sessions]
- WEBHOOKS[Webhooks]
- APIKEYS[API Keys]
- LOGS[Logs]
- SETTINGS[Settings]
- end
-
- HOME --> |Quick Actions| SESSIONS
- HOME --> |View Stats| LOGS
-
- subgraph Sessions Pages
- LIST[Session List]
- DETAIL[Session Detail]
- QR[QR Scanner]
- CHAT[Test Chat]
+ subgraph "Always visible"
+ HOME[Dashboard /]
+ SESSIONS[Sessions /sessions]
+ CHATS[Chats /chats]
+ WEBHOOKS[Webhooks /webhooks]
+ TEMPLATES[Templates /templates]
+ TESTER[Message Tester /message-tester]
+ LOGS[Logs /logs]
end
- SESSIONS --> LIST
- LIST --> DETAIL
- DETAIL --> QR
- DETAIL --> CHAT
-
- subgraph Webhooks Pages
- WH_LIST[Webhook List]
- WH_DETAIL[Webhook Detail]
- WH_LOGS[Webhook Logs]
+ subgraph "Admin-only"
+ APIKEYS[API Keys /api-keys]
+ INFRA[Infrastructure /infrastructure]
+ PLUGINS[Plugins /plugins]
end
- WEBHOOKS --> WH_LIST
- WH_LIST --> WH_DETAIL
- WH_DETAIL --> WH_LOGS
+ HOME --> SESSIONS
+ HOME --> CHATS
+ SESSIONS --> CHATS
```
### Navigation Structure
+The route table lives in `src/App.tsx`; the sidebar items in `src/components/Layout.tsx`. Routes
+guarded by `role === 'admin'` are only mounted (and only shown in the sidebar) for an admin key —
+a non-admin hitting the path falls through to the `*` redirect.
+
```
-/ → Dashboard Home
-/sessions → Session List
-/sessions/:id → Session Detail
-/sessions/:id/chat → Test Chat Interface
-/webhooks → Webhook List
-/webhooks/:id → Webhook Detail
-/api-keys → API Keys Management
-/logs → Activity Logs
-/settings → Settings
-/settings/profile → Profile Settings
-/settings/appearance → Theme Settings
+/ → Dashboard (overview + charts)
+/sessions → Sessions (create / start / stop / QR / delete)
+/chats → Chats (chat list + message thread, live via WebSocket)
+/webhooks → Webhooks (per-session webhook endpoints)
+/templates → Message Templates
+/message-tester → Message Tester (ad-hoc send-* + check-number)
+/logs → Activity / Audit Logs
+/api-keys → API Keys Management [admin only]
+/infrastructure → Infrastructure status & config [admin only]
+/plugins → Plugins (install / enable / configure) [admin only]
+* → redirect to /
```
+> There is **no Settings page** and no `/sessions/:id`, `/sessions/:id/chat`, or `/webhooks/:id`
+> route. Theme (light/dark/system) and color-palette selection live in a popover menu in the sidebar
+> footer (`Layout.tsx`), persisted client-side by the `useTheme` hook.
+
## 17.3 Wireframes
### Dashboard Home
@@ -339,618 +343,300 @@ flowchart TB
## 17.4 Component Library
-### Using shadcn/ui
+> **No component framework is installed.** shadcn/ui is *not* adopted — there is no `npx shadcn`
+> init, no `components/ui/` directory, no `cn()` utility, and no `@/components` import alias. The
+> wireframes above are design intent; the implementation is hand-written.
-```bash
-# Initialize shadcn/ui
-npx shadcn-ui@latest init
-
-# Add components
-npx shadcn-ui@latest add button
-npx shadcn-ui@latest add card
-npx shadcn-ui@latest add dialog
-npx shadcn-ui@latest add dropdown-menu
-npx shadcn-ui@latest add input
-npx shadcn-ui@latest add table
-npx shadcn-ui@latest add tabs
-npx shadcn-ui@latest add toast
-npx shadcn-ui@latest add avatar
-npx shadcn-ui@latest add badge
-npx shadcn-ui@latest add skeleton
-```
-
-### Custom Components
-
-```typescript
-// components/ui/status-badge.tsx
-
-import { Badge } from '@/components/ui/badge';
-import { cn } from '@/lib/utils';
+### Bespoke components
-type SessionStatus = 'CONNECTED' | 'DISCONNECTED' | 'INITIALIZING' | 'SCAN_QR';
-
-interface StatusBadgeProps {
- status: SessionStatus;
- className?: string;
-}
+The UI is built from a small set of project-specific components under `dashboard/src/components/`,
+each with a colocated CSS file. There is no design-system package to pull from.
-const statusConfig: Record<SessionStatus, { label: string; variant: string; dot: string }> = {
- CONNECTED: {
- label: 'Connected',
- variant: 'success',
- dot: 'bg-green-500',
- },
- DISCONNECTED: {
- label: 'Disconnected',
- variant: 'destructive',
- dot: 'bg-red-500',
- },
- INITIALIZING: {
- label: 'Initializing',
- variant: 'warning',
- dot: 'bg-yellow-500',
- },
- SCAN_QR: {
- label: 'Scan QR',
- variant: 'secondary',
- dot: 'bg-blue-500 animate-pulse',
- },
-};
+| Component | File | Responsibility |
+| --- | --- | --- |
+| `Layout` | `components/Layout.tsx` | App shell: collapsible sidebar nav, mobile drawer, language menu, theme/palette popover, logout, live version badge |
+| `ToastProvider` / `useToast` | `components/Toast.tsx` | Context-based toast notifications (success/error/warning/info) with de-dup keys |
+| `PageHeader` | `components/PageHeader.tsx` | Shared page title / subtitle / badge / actions header |
+| `DashboardCharts` | `components/DashboardCharts.tsx` | `recharts`-based message-volume / activity charts on the Dashboard |
+| `FilterBuilder` | `components/FilterBuilder.tsx` | Visual condition builder for webhook event filters |
+| `ErrorBoundary` | `components/ErrorBoundary.tsx` | Top-level React error boundary wrapping the whole app |
+| `GithubIcon` | `components/GithubIcon.tsx` | Inline brand SVG |
-export function StatusBadge({ status, className }: StatusBadgeProps) {
- const config = statusConfig[status];
+Pages live under `dashboard/src/pages/`, each as a `*.tsx` + `*.css` pair (e.g. `Sessions.tsx` +
+`Sessions.css`). Pages are lazy-loaded in `App.tsx` via `React.lazy` + `Suspense`.
- return (
- <Badge variant={config.variant as any} className={cn('gap-1.5', className)}>
- <span className={cn('h-2 w-2 rounded-full', config.dot)} />
- {config.label}
- </Badge>
- );
-}
-```
+A representative bespoke component — the shared page header — shows the actual conventions
+(plain props, a colocated stylesheet, BEM-ish class names, no utility classes):
```typescript
-// components/ui/session-card.tsx
-
-import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card';
-import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
-import { Button } from '@/components/ui/button';
-import { StatusBadge } from '@/components/ui/status-badge';
-import { MessageSquare, QrCode, Settings, Trash2 } from 'lucide-react';
-import { Session } from '@/types';
-import { formatDistanceToNow } from 'date-fns';
-
-interface SessionCardProps {
- session: Session;
- onQr: () => void;
- onChat: () => void;
- onSettings: () => void;
- onDelete: () => void;
+// components/PageHeader.tsx
+import type { ReactNode } from 'react';
+import './PageHeader.css';
+
+interface PageHeaderProps {
+ title: string;
+ subtitle?: string;
+ badge?: ReactNode;
+ actions?: ReactNode;
}
-export function SessionCard({
- session,
- onQr,
- onChat,
- onSettings,
- onDelete,
-}: SessionCardProps) {
+export function PageHeader({ title, subtitle, badge, actions }: PageHeaderProps) {
return (
- <Card>
- <CardHeader className="flex flex-row items-center gap-4">
- <Avatar className="h-12 w-12">
- <AvatarImage src={session.profilePicture} />
- <AvatarFallback>
- {session.name.slice(0, 2).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1">
- <div className="flex items-center justify-between">
- <h3 className="font-semibold">{session.name}</h3>
- <StatusBadge status={session.status} />
- </div>
- <p className="text-sm text-muted-foreground">
- {session.phoneNumber || 'Not connected'}
- </p>
- </div>
- </CardHeader>
-
- <CardContent>
- <div className="flex justify-between text-sm text-muted-foreground">
- <span>{session.stats?.messagesSent || 0} messages</span>
- <span>
- {session.lastSeen
- ? `Active ${formatDistanceToNow(new Date(session.lastSeen))} ago`
- : 'Never active'}
- </span>
- </div>
- </CardContent>
-
- <CardFooter className="gap-2">
- {session.status === 'CONNECTED' ? (
- <>
- <Button variant="outline" size="sm" onClick={onChat}>
- <MessageSquare className="mr-2 h-4 w-4" />
- Chat
- </Button>
- </>
- ) : (
- <Button variant="outline" size="sm" onClick={onQr}>
- <QrCode className="mr-2 h-4 w-4" />
- Scan QR
- </Button>
- )}
- <Button variant="ghost" size="sm" onClick={onSettings}>
- <Settings className="h-4 w-4" />
- </Button>
- <Button variant="ghost" size="sm" onClick={onDelete}>
- <Trash2 className="h-4 w-4 text-destructive" />
- </Button>
- </CardFooter>
- </Card>
+ <header className="page-header">
+ <div className="page-header__title-group">
+ <h1>{title}</h1>
+ {badge && <span className="page-header__badge">{badge}</span>}
+ </div>
+ {actions && <div className="page-header__actions">{actions}</div>}
+ {subtitle && <p className="page-header__subtitle">{subtitle}</p>}
+ </header>
);
}
```
-```typescript
-// components/ui/qr-code-display.tsx
-
-import { useEffect, useState } from 'react';
-import { Card, CardContent } from '@/components/ui/card';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
-import { RefreshCw } from 'lucide-react';
-import QRCode from 'qrcode';
-
-interface QrCodeDisplayProps {
- qrData: string | null;
- expiresAt: string | null;
- onRefresh: () => void;
- isLoading: boolean;
-}
+Icons are imported individually from `lucide-react`; there is no `Avatar`/`Card`/`Badge` primitive
+library — those visuals are composed directly with `div`s and the page's own CSS.
-export function QrCodeDisplay({
- qrData,
- expiresAt,
- onRefresh,
- isLoading,
-}: QrCodeDisplayProps) {
- const [qrImage, setQrImage] = useState<string | null>(null);
- const [countdown, setCountdown] = useState<number>(0);
+## 17.5 State Management
- useEffect(() => {
- if (qrData) {
- QRCode.toDataURL(qrData, {
- width: 256,
- margin: 2,
- color: {
- dark: '#000000',
- light: '#ffffff',
- },
- }).then(setQrImage);
- }
- }, [qrData]);
+There is **no Zustand store** (and no global client-state library). Server data is owned by
+**TanStack Query** (`@tanstack/react-query`); the only other shared state is two small React Context
+providers — `useRole` (the authenticated key's role) and `useTheme` (mode + palette, persisted to
+`localStorage`).
- useEffect(() => {
- if (expiresAt) {
- const interval = setInterval(() => {
- const remaining = Math.max(
- 0,
- Math.floor((new Date(expiresAt).getTime() - Date.now()) / 1000)
- );
- setCountdown(remaining);
-
- if (remaining === 0) {
- clearInterval(interval);
- }
- }, 1000);
-
- return () => clearInterval(interval);
- }
- }, [expiresAt]);
+### API client — raw payloads, no `{ data }` envelope
- return (
- <Card className="w-fit mx-auto">
- <CardContent className="pt-6 text-center">
- {isLoading ? (
- <Skeleton className="h-64 w-64 mx-auto" />
- ) : qrImage ? (
- <>
- <img
- src={qrImage}
- alt="QR Code"
- className="mx-auto rounded-lg"
- width={256}
- height={256}
- />
- <p className="mt-4 text-sm text-muted-foreground">
- Expires in: {Math.floor(countdown / 60)}:
- {(countdown % 60).toString().padStart(2, '0')}
- </p>
- </>
- ) : (
- <div className="h-64 w-64 flex items-center justify-center bg-muted rounded-lg">
- <p className="text-muted-foreground">QR Code expired</p>
- </div>
- )}
-
- <Button
- variant="outline"
- className="mt-4"
- onClick={onRefresh}
- disabled={isLoading}
- >
- <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
- Refresh QR
- </Button>
- </CardContent>
- </Card>
- );
-}
-```
-
-## 17.5 State Management
-
-### Zustand Store
+The client lives in `src/services/api.ts`. A single `request<T>()` helper attaches the `X-API-Key`
+header from `sessionStorage`, then returns **the parsed JSON body as-is** — the backend sends the
+raw handler payload, so `request<Session[]>('/sessions')` resolves to a bare `Session[]`, not
+`{ data: Session[] }`. (A `204 No Content` resolves to `undefined`; a `401` clears the stored key
+and redirects to login.) Endpoints are grouped into typed namespaces — `sessionApi`, `webhookApi`,
+`templateApi`, `apiKeyApi`, `auditApi`, `messageApi`, `infraApi`, `pluginsApi`, `statsApi`, ...
```typescript
-// stores/session-store.ts
-
-import { create } from 'zustand';
-import { Session } from '@/types';
-
-interface SessionState {
- sessions: Session[];
- selectedSession: Session | null;
- isLoading: boolean;
- error: string | null;
-
- // Actions
- setSessions: (sessions: Session[]) => void;
- addSession: (session: Session) => void;
- updateSession: (id: string, updates: Partial<Session>) => void;
- removeSession: (id: string) => void;
- selectSession: (session: Session | null) => void;
- setLoading: (loading: boolean) => void;
- setError: (error: string | null) => void;
+// src/services/api.ts (abridged)
+export const API_BASE_URL = `${(import.meta.env.VITE_API_URL ?? '').replace(/\/+$/, '')}/api`;
+
+async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
+ const apiKey = sessionStorage.getItem('openwa_api_key');
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(apiKey ? { 'X-API-Key': apiKey } : {}),
+ ...options.headers,
+ },
+ });
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ throw new Error(error.message || `HTTP ${response.status}`);
+ }
+ if (response.status === 204) return undefined as T;
+ return response.json(); // ← the raw payload, no unwrapping
}
-export const useSessionStore = create<SessionState>((set) => ({
- sessions: [],
- selectedSession: null,
- isLoading: false,
- error: null,
-
- setSessions: (sessions) => set({ sessions }),
-
- addSession: (session) =>
- set((state) => ({
- sessions: [...state.sessions, session],
- })),
-
- updateSession: (id, updates) =>
- set((state) => ({
- sessions: state.sessions.map((s) =>
- s.id === id ? { ...s, ...updates } : s
- ),
- selectedSession:
- state.selectedSession?.id === id
- ? { ...state.selectedSession, ...updates }
- : state.selectedSession,
- })),
-
- removeSession: (id) =>
- set((state) => ({
- sessions: state.sessions.filter((s) => s.id !== id),
- selectedSession:
- state.selectedSession?.id === id ? null : state.selectedSession,
- })),
-
- selectSession: (session) => set({ selectedSession: session }),
-
- setLoading: (isLoading) => set({ isLoading }),
-
- setError: (error) => set({ error }),
-}));
+export const sessionApi = {
+ list: () => request<Session[]>('/sessions'), // bare array
+ get: (id: string) => request<Session>(`/sessions/${id}`),
+ create: (name: string) =>
+ request<Session>('/sessions', { method: 'POST', body: JSON.stringify({ name }) }),
+ delete: (id: string) => request<void>(`/sessions/${id}`, { method: 'DELETE' }),
+ // QR returns a raw { qrCode, status } object — not { qr, expiresAt }, and there is no expiry timer.
+ getQR: (id: string) => request<{ qrCode: string; status: string }>(`/sessions/${id}/qr`),
+};
```
-### TanStack Query Hooks
+### TanStack Query hooks
-```typescript
-// hooks/use-sessions.ts
+Hooks wrap those namespaces in `src/hooks/queries.ts` — each returns the raw payload directly (no
+`.data.data`). Cache invalidation, not a store, keeps the UI in sync after a mutation.
+```typescript
+// src/hooks/queries.ts (abridged)
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
-import { api } from '@/lib/api';
-import { Session, CreateSessionInput } from '@/types';
-import { useSessionStore } from '@/stores/session-store';
-
-export function useSessions() {
- const { setSessions, setError } = useSessionStore();
+import { sessionApi, webhookApi } from '../services/api';
- return useQuery({
- queryKey: ['sessions'],
- queryFn: async () => {
- const response = await api.get<{ data: Session[] }>('/api/sessions');
- return response.data.data;
- },
- onSuccess: (data) => {
- setSessions(data);
- },
- onError: (error: Error) => {
- setError(error.message);
- },
- });
-}
+export const queryKeys = {
+ sessions: ['sessions'] as const,
+ webhooks: ['webhooks'] as const,
+ // ...
+};
-export function useSession(id: string) {
+export function useSessionsQuery() {
return useQuery({
- queryKey: ['sessions', id],
- queryFn: async () => {
- const response = await api.get<{ data: Session }>(`/api/sessions/${id}`);
- return response.data.data;
- },
- enabled: !!id,
+ queryKey: queryKeys.sessions,
+ queryFn: sessionApi.list, // resolves to Session[] directly
+ staleTime: 30_000,
});
}
-export function useCreateSession() {
+export function useStopSessionMutation() {
const queryClient = useQueryClient();
- const { addSession } = useSessionStore();
-
return useMutation({
- mutationFn: async (input: CreateSessionInput) => {
- const response = await api.post<{ data: Session }>('/api/sessions', input);
- return response.data.data;
- },
- onSuccess: (data) => {
- addSession(data);
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
- },
- });
-}
-
-export function useDeleteSession() {
- const queryClient = useQueryClient();
- const { removeSession } = useSessionStore();
-
- return useMutation({
- mutationFn: async (id: string) => {
- await api.delete(`/api/sessions/${id}`);
- return id;
- },
- onSuccess: (id) => {
- removeSession(id);
- queryClient.invalidateQueries({ queryKey: ['sessions'] });
- },
- });
-}
-
-export function useSessionQr(id: string) {
- return useQuery({
- queryKey: ['sessions', id, 'qr'],
- queryFn: async () => {
- const response = await api.get<{ data: { qr: string; expiresAt: string } }>(
- `/api/sessions/${id}/qr`
- );
- return response.data.data;
- },
- enabled: !!id,
- refetchInterval: 30000, // Refresh every 30 seconds
+ mutationFn: (id: string) => sessionApi.stop(id),
+ onSuccess: () => void queryClient.invalidateQueries({ queryKey: queryKeys.sessions }),
});
}
```
+> **There is no `useSessionQr` polling hook.** QR codes are not fetched on a 30 s
+> `refetchInterval`. The Sessions page fetches the current QR imperatively via `sessionApi.getQR()`
+> and then receives fresh codes pushed over the WebSocket (`session.qr` events, see §17.6).
+
## 17.6 WebSocket Integration
+Real-time updates use **socket.io** (`socket.io-client`), not a raw browser `WebSocket`. The hook is
+`src/hooks/useWebSocket.ts`. Key facts:
+
+- **Namespace `/events`** (not `/ws`). The client connects to
+ `${VITE_WS_URL || window.location.origin}/events` — same-origin by default; `VITE_WS_URL` only
+ overrides it for split-origin deployments.
+- **API key via the socket.io `auth` payload (and an `X-API-Key` header for proxies), deliberately
+ *not* in the query string** — a key in the handshake URL would leak into access logs / `Referer`.
+- **Reconnection is socket.io's built-in mechanism** — `reconnectionAttempts: 5`,
+ `reconnectionDelay: 1000` — not a hand-rolled `setTimeout(connect, 3000)`. When all attempts are
+ exhausted the manager fires `reconnect_failed`; the hook surfaces that as `connectionFailed` so the
+ UI can offer a manual `reconnect()`.
+- **Server → client envelope.** Every push arrives as a single `message` event whose payload is
+ `{ type: 'event', timestamp, payload: { event, sessionId, data } }`. The hook registers one
+ handler, switches on `payload.event`, and fans out to typed callbacks.
+- **Subscriptions** are sent with `socket.emit('message', { type: 'subscribe' | 'unsubscribe', ... })`.
+
```typescript
-// lib/websocket.ts
-
-import { useEffect, useRef, useCallback } from 'react';
-import { useSessionStore } from '@/stores/session-store';
-
-type EventType =
- | 'session.status'
- | 'session.qr'
- | 'message.received'
- | 'message.ack'
- | 'session.authenticated'
- | 'session.disconnected';
-
-interface WebSocketMessage {
- event: EventType;
- sessionId: string;
- data: any;
-}
+// src/hooks/useWebSocket.ts (abridged)
+import { useEffect, useRef, useCallback, useState } from 'react';
+import { io, Socket } from 'socket.io-client';
-export function useWebSocket(apiKey: string) {
- const ws = useRef<WebSocket | null>(null);
- const { updateSession } = useSessionStore();
+const SOCKET_URL = import.meta.env.VITE_WS_URL || window.location.origin;
- const connect = useCallback(() => {
- const wsUrl = `${import.meta.env.VITE_WS_URL || 'ws://localhost:2785'}/ws?apiKey=${apiKey}`;
- ws.current = new WebSocket(wsUrl);
+interface ServerEventEnvelope {
+ type: string; // 'event'
+ timestamp: string;
+ payload?: { event: string; sessionId: string; data: Record<string, unknown> };
+}
- ws.current.onopen = () => {
- console.log('WebSocket connected');
- };
+export function useWebSocket(events: WebSocketEvents = {}) {
+ const socketRef = useRef<Socket | null>(null);
+ const [isConnected, setIsConnected] = useState(false);
+ const [connectionFailed, setConnectionFailed] = useState(false);
- ws.current.onmessage = (event) => {
- const message: WebSocketMessage = JSON.parse(event.data);
+ const connect = useCallback(() => {
+ if (socketRef.current?.connected) return;
+ const apiKey = sessionStorage.getItem('openwa_api_key');
+ if (!apiKey) return;
+
+ socketRef.current = io(`${SOCKET_URL}/events`, {
+ reconnection: true,
+ reconnectionAttempts: 5,
+ reconnectionDelay: 1000,
+ auth: { apiKey }, // key in the handshake auth, NOT the URL
+ extraHeaders: { 'X-API-Key': apiKey }, // header copy for proxies
+ });
+
+ socketRef.current.on('connect', () => { setIsConnected(true); setConnectionFailed(false); });
+ socketRef.current.on('disconnect', () => setIsConnected(false));
+ socketRef.current.io.on('reconnect_failed', () => setConnectionFailed(true));
+ }, []);
- switch (message.event) {
+ useEffect(() => {
+ connect();
+ const socket = socketRef.current;
+ const handle = (msg: ServerEventEnvelope) => {
+ if (!msg || msg.type !== 'event' || !msg.payload) return;
+ const { event, sessionId, data } = msg.payload;
+ switch (event) {
case 'session.status':
- updateSession(message.sessionId, {
- status: message.data.status,
- });
+ events.onSessionStatus?.({ sessionId, status: String(data.status), timestamp: msg.timestamp });
break;
-
- case 'session.authenticated':
- updateSession(message.sessionId, {
- status: 'CONNECTED',
- phoneNumber: message.data.phoneNumber,
- profileName: message.data.profileName,
- });
- break;
-
- case 'session.disconnected':
- updateSession(message.sessionId, {
- status: 'DISCONNECTED',
- });
- break;
-
case 'session.qr':
- // Handle QR update via query invalidation
+ events.onQRCode?.({ sessionId, qrCode: String(data.qrCode), timestamp: msg.timestamp });
break;
-
- default:
- console.log('Unknown event:', message.event);
+ case 'message.received':
+ case 'message.sent':
+ events.onMessage?.({ sessionId, message: data, timestamp: msg.timestamp });
+ break;
+ // ...message.ack, message.reaction, message.revoked
}
};
+ socket?.on('message', handle);
+ return () => { socket?.off('message', handle); };
+ }, [connect, events]);
- ws.current.onclose = () => {
- console.log('WebSocket disconnected, reconnecting...');
- setTimeout(connect, 3000);
- };
-
- ws.current.onerror = (error) => {
- console.error('WebSocket error:', error);
- };
- }, [apiKey, updateSession]);
-
- useEffect(() => {
- connect();
-
- return () => {
- ws.current?.close();
- };
- }, [connect]);
-
- const send = useCallback((event: string, data: any) => {
- if (ws.current?.readyState === WebSocket.OPEN) {
- ws.current.send(JSON.stringify({ event, data }));
- }
- }, []);
-
- return { send };
+ return { isConnected, connectionFailed, reconnect, subscribe, unsubscribe };
}
```
## 17.7 Theme Configuration
-```typescript
-// lib/theme.ts
-
-export const themes = {
- light: {
- background: '0 0% 100%',
- foreground: '222.2 84% 4.9%',
- card: '0 0% 100%',
- 'card-foreground': '222.2 84% 4.9%',
- primary: '222.2 47.4% 11.2%',
- 'primary-foreground': '210 40% 98%',
- secondary: '210 40% 96.1%',
- 'secondary-foreground': '222.2 47.4% 11.2%',
- muted: '210 40% 96.1%',
- 'muted-foreground': '215.4 16.3% 46.9%',
- accent: '210 40% 96.1%',
- 'accent-foreground': '222.2 47.4% 11.2%',
- destructive: '0 84.2% 60.2%',
- 'destructive-foreground': '210 40% 98%',
- border: '214.3 31.8% 91.4%',
- input: '214.3 31.8% 91.4%',
- ring: '222.2 84% 4.9%',
- },
- dark: {
- background: '222.2 84% 4.9%',
- foreground: '210 40% 98%',
- card: '222.2 84% 4.9%',
- 'card-foreground': '210 40% 98%',
- primary: '210 40% 98%',
- 'primary-foreground': '222.2 47.4% 11.2%',
- secondary: '217.2 32.6% 17.5%',
- 'secondary-foreground': '210 40% 98%',
- muted: '217.2 32.6% 17.5%',
- 'muted-foreground': '215 20.2% 65.1%',
- accent: '217.2 32.6% 17.5%',
- 'accent-foreground': '210 40% 98%',
- destructive: '0 62.8% 30.6%',
- 'destructive-foreground': '210 40% 98%',
- border: '217.2 32.6% 17.5%',
- input: '217.2 32.6% 17.5%',
- ring: '212.7 26.8% 83.9%',
- },
-};
-
-// Theme provider component
-// components/theme-provider.tsx
-
-import { createContext, useContext, useEffect, useState } from 'react';
+Theming is **not** shadcn HSL design tokens. It is a plain `useTheme` hook (`src/hooks/useTheme.ts`)
+that toggles two attributes on `<html>` and lets the CSS do the rest. The values are persisted to
+`localStorage` under `openwa_theme` and `openwa_palette`:
-type Theme = 'light' | 'dark' | 'system';
+- **Mode** — `light | dark | system`. `system` removes `data-theme` so a `prefers-color-scheme`
+ media query in the global CSS takes over; otherwise `data-theme="light|dark"` is set explicitly.
+- **Palette** — one of seven accent palettes (`openwa`, `blue`, `graphite`, `indigo`, `amber`,
+ `rose`, `teal`), applied as `data-palette="…"`. Each palette is a set of CSS custom properties
+ scoped to that attribute selector.
-interface ThemeContextType {
- theme: Theme;
- setTheme: (theme: Theme) => void;
-}
+The mode/palette pickers render in the sidebar footer popover (`Layout.tsx`); there is no
+`ThemeProvider` context wrapper — it's a hook consumed directly where needed.
-const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
+```typescript
+// src/hooks/useTheme.ts (abridged)
+export type Theme = 'light' | 'dark' | 'system';
+export type ThemePalette = 'openwa' | 'blue' | 'graphite' | 'indigo' | 'amber' | 'rose' | 'teal';
-export function ThemeProvider({ children }: { children: React.ReactNode }) {
- const [theme, setTheme] = useState<Theme>(() => {
- const stored = localStorage.getItem('theme') as Theme;
- return stored || 'system';
- });
+export function useTheme() {
+ const [theme, setTheme] = useState<Theme>(/* localStorage 'openwa_theme' ?? 'system' */);
+ const [palette, setPalette] = useState<ThemePalette>(/* localStorage 'openwa_palette' ?? 'openwa' */);
useEffect(() => {
const root = document.documentElement;
-
- root.classList.remove('light', 'dark');
-
- if (theme === 'system') {
- const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
- ? 'dark'
- : 'light';
- root.classList.add(systemTheme);
- } else {
- root.classList.add(theme);
- }
-
- localStorage.setItem('theme', theme);
+ if (theme === 'system') root.removeAttribute('data-theme');
+ else root.setAttribute('data-theme', theme);
+ localStorage.setItem('openwa_theme', theme);
}, [theme]);
- return (
- <ThemeContext.Provider value={{ theme, setTheme }}>
- {children}
- </ThemeContext.Provider>
- );
-}
+ useEffect(() => {
+ document.documentElement.setAttribute('data-palette', palette);
+ localStorage.setItem('openwa_palette', palette);
+ }, [palette]);
-export function useTheme() {
- const context = useContext(ThemeContext);
- if (!context) {
- throw new Error('useTheme must be used within a ThemeProvider');
- }
- return context;
+ return { theme, setTheme, palette, setPalette, /* resolvedTheme, paletteOptions, ... */ };
}
```
+The actual colors live in the global CSS as variables keyed off `[data-theme]` / `[data-palette]` —
+e.g. `:root { --color-accent: #25d366; } [data-palette='blue'] { --color-accent: #2563eb; }` — so
+switching mode or palette is a single attribute write with no re-render of the tree.
+
## 17.8 Build & Deployment
### Vite Configuration
+The dev server listens on **2886** and proxies `/api` to the API on `2785`. The WebSocket proxy is
+on **`/socket.io`** (socket.io's transport path) with `ws: true` — *not* `/ws`. There is no `@`
+import alias and no custom `manualChunks`/Radix vendor split; code-splitting is handled by the
+per-page `React.lazy` imports in `App.tsx`. The build-time version (`__APP_VERSION__`) is injected
+from `package.json` via `define`.
+
```typescript
// vite.config.ts
-
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
-import path from 'path';
+
+const { version: pkgVersion } = JSON.parse(
+ readFileSync(resolve(process.cwd(), 'package.json'), 'utf-8'),
+) as { version: string };
export default defineConfig({
plugins: [react()],
- resolve: {
- alias: {
- '@': path.resolve(__dirname, './src'),
- },
+ appType: 'spa', // SPA fallback for client-side routing
+ define: {
+ __APP_VERSION__: JSON.stringify(process.env.APP_VERSION || pkgVersion),
+ __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
server: {
port: 2886,
@@ -958,22 +644,13 @@ export default defineConfig({
'/api': {
target: 'http://localhost:2785',
changeOrigin: true,
+ secure: false,
},
- '/ws': {
- target: 'ws://localhost:2785',
+ // socket.io transport — NOT '/ws'
+ '/socket.io': {
+ target: 'http://localhost:2785',
ws: true,
- },
- },
- },
- build: {
- outDir: 'dist',
- sourcemap: true,
- rollupOptions: {
- output: {
- manualChunks: {
- vendor: ['react', 'react-dom', 'react-router-dom'],
- ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
- },
+ changeOrigin: true,
},
},
},
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 4fb62297b..35764c15e 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -2,1493 +2,923 @@
## 18.1 Overview
-OpenWA provides official SDKs for multiple programming languages to simplify API integration. This document describes the SDK design and specifications.
-
-### Supported Languages
-
-```mermaid
-flowchart TB
- subgraph Tier1["Tier 1 - Official SDKs"]
- TS[TypeScript/JavaScript]
- PY[Python]
- PHP[PHP]
- end
-
- subgraph Tier2["Tier 2 - Community SDKs"]
- GO[Go]
- RUBY[Ruby]
- CSHARP[C#/.NET]
- JAVA[Java/Kotlin]
- end
-
- subgraph Tier3["Tier 3 - Integrations"]
- N8N[n8n Node]
- MAKE[Make/Integromat]
- ZAP[Zapier]
- end
-```
-
-### Design Principles
+OpenWA ships three official, hand-written client libraries for the REST API. They are not generated from an OpenAPI spec — each is written directly against the real API surface (paths, request DTOs, response shapes) and **unit-tested with a mocked HTTP transport that asserts on the exact request path, method, and body**, so contract drift is caught at test time rather than in production.
-1. **Idiomatic** - Follow each language's conventions
-2. **Type-safe** - Full type definitions for IDE support
-3. **Async-first** - Native async/await support
-4. **Minimal dependencies** - Only required dependencies
-5. **Consistent** - Consistent API across languages
-6. **Well-documented** - Inline docs and examples
+| Language | Package | Install | Notes |
+| --- | --- | --- | --- |
+| JavaScript / TypeScript | [`@rmyndharis/openwa`](https://www.npmjs.com/package/@rmyndharis/openwa) | `npm install @rmyndharis/openwa` | Dual ESM + CJS, bundled `.d.ts` types, Node 18+ |
+| Python | [`rmyndharis-openwa`](https://pypi.org/project/rmyndharis-openwa/) | `pip install rmyndharis-openwa` | Synchronous (httpx), PEP 561 typed, Python 3.9+ |
+| PHP | [`rmyndharis/openwa`](https://packagist.org/packages/rmyndharis/openwa) | `composer require rmyndharis/openwa` | Synchronous (Guzzle 7), PSR-4, PHP 8.1+ |
-## 18.2 TypeScript/JavaScript SDK
+> The import names differ from the dist names where the ecosystem requires it. Python installs `rmyndharis-openwa` but imports `openwa`; the client class is `OpenWAClient` in JS/Python and `OpenWA\Client` in PHP.
-### Installation
-
-```bash
-# npm
-npm install @openwa/sdk
+### Design Principles
-# yarn
-yarn add @openwa/sdk
+- **One client, fluent resources.** A single client object (`OpenWAClient` / `OpenWA\Client`) exposes every resource as a property — `client.messages.sendText(...)`, `client.sessions.start(...)`. All three SDKs expose the **same** resource surface; only the language idioms differ (camelCase methods + objects in JS/PHP, snake_case methods + dicts in Python).
+- **It is a request/response client, not an event SDK.** There is no WebSocket, EventEmitter, or `client.on(...)`. To receive inbound messages and acks, register a webhook (the `webhooks` resource) and host your own receiver, or connect to the real-time Socket.IO API directly (see [API Specification §6.5](./06-api-specification.md)).
+- **Typed errors.** Non-2xx responses raise/throw a typed error mapped from the HTTP status (`401/403/404/409/429/501`), plus a timeout error — all `instanceof`/`catch`-checkable. See each language's Error Handling subsection.
+- **Injectable transport.** The HTTP layer is replaceable (`fetch` in JS, an `httpx` transport in Python, a Guzzle client in PHP) — the extension point for retry/observability middleware and for testing without the network.
+- **Safe by default.** Redirects are never followed (so the API key is never re-sent to a redirect target), the auth/JSON headers always take precedence over caller-supplied defaults, path segments are percent-encoded, a base-URL path prefix (e.g. behind a reverse proxy at `/v1`) is preserved, and there is a default 30s per-request timeout. **No automatic retries** — wrap calls in your own backoff if you need them (especially for `429`).
-# pnpm
-pnpm add @openwa/sdk
-```
+### Resource Coverage
-### Quick Start
+All three SDKs expose the same fluent surface:
-```typescript
-import { OpenWA } from '@openwa/sdk';
+| Resource | Methods |
+| --- | --- |
+| `sessions` | list, get, create, delete, start, stop, forceKill, getQrCode, requestPairingCode, stats |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, history, reactions, sendBulk, batchStatus, cancelBatch |
+| `contacts` | list, get, check, profilePicture, phone, block, unblock |
+| `groups` | list, get, create, add/remove/promote/demoteParticipants, setSubject, setDescription, leave, inviteCode, revokeInviteCode |
+| `webhooks` | list, get, create, update, delete, test |
+| `chats` | list, markRead, markUnread, delete, sendState |
+| `labels` | list, get, forChat, addToChat, removeFromChat *(WhatsApp Business)* |
+| `channels` | list, get, messages, subscribe, unsubscribe *(Newsletters)* |
+| `catalog` | info, products, product, sendProduct, sendCatalog *(WhatsApp Business)* |
+| `status` | list, fromContact, sendText, sendImage, sendVideo, delete *(Stories)* |
+| `templates` | list, get, create, update, delete |
+| `health` | check, live, ready |
-const client = new OpenWA({
- baseUrl: 'http://localhost:2785',
- apiKey: 'your-api-key',
-});
+> The operator/admin-only server modules — `docker`, `metrics`, `infra`, `plugins`, `mcp` — are intentionally **not** exposed in the SDKs; all user-facing resources above are. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.
-// Create session
-const session = await client.sessions.create({
- id: 'my-session',
- name: 'My WhatsApp',
-});
+## 18.2 TypeScript / JavaScript SDK
-// Wait for QR code
-client.on('session.qr', ({ sessionId, qr }) => {
- if (sessionId !== 'my-session') return;
- console.log('Scan this QR:', qr);
-});
+The official JavaScript/TypeScript SDK is published as **`@rmyndharis/openwa`**. It is a pure promise-based HTTP client: a single `OpenWAClient` exposes every API resource as a typed property. There is no event model — the SDK does not open WebSockets, emit events, or expose `client.on(...)`. To receive inbound messages and acks, configure a webhook (see the `webhooks` resource) and host your own HTTP receiver.
-// Wait for session ready
-client.on('session.status', async ({ sessionId, status }) => {
- if (sessionId !== 'my-session' || status !== 'ready') return;
+The package ships **dual CJS + ESM** with bundled `.d.ts` types, so it is consumable from both `require()` and `import`.
- // Send message
- const message = await client.messages.send('my-session', {
- phone: '[email protected]',
- type: 'text',
- body: 'Hello from SDK!',
- });
+### Installation
- console.log('Message sent:', message.id);
-});
+```bash
+npm install @rmyndharis/openwa
+# or
+yarn add @rmyndharis/openwa
+# or
+pnpm add @rmyndharis/openwa
```
-### SDK Architecture
+> **Node 18+ required.** The transport uses the global `fetch` (and `AbortController`), both built into Node 18 and later. To run on an older runtime, pass your own `fetch` implementation via the client constructor (see [Client Configuration](#client-configuration)).
-```typescript
-// src/index.ts
-
-export interface OpenWAConfig {
- baseUrl: string;
- apiKey: string;
- timeout?: number;
- retries?: number;
- debug?: boolean;
-}
-
-export class OpenWA extends EventEmitter {
- private config: OpenWAConfig;
- private http: HttpClient;
- private ws: WebSocketClient;
-
- // Resource managers
- public sessions: SessionsResource;
- public messages: MessagesResource;
- public contacts: ContactsResource;
- public groups: GroupsResource;
- public webhooks: WebhooksResource;
- public apiKeys: ApiKeysResource;
-
- constructor(config: OpenWAConfig) {
- super();
- this.config = this.validateConfig(config);
- this.http = new HttpClient(this.config);
- this.ws = new WebSocketClient(this.config);
-
- // Initialize resources
- this.sessions = new SessionsResource(this.http);
- this.messages = new MessagesResource(this.http);
- this.contacts = new ContactsResource(this.http);
- this.groups = new GroupsResource(this.http);
- this.webhooks = new WebhooksResource(this.http);
- this.apiKeys = new ApiKeysResource(this.http);
-
- // Setup WebSocket events
- this.setupWebSocket();
- }
-
- private setupWebSocket(): void {
- this.ws.on('message', event => {
- this.emit(event.type, event.data);
- });
- }
-
- // Utility methods
- async health(): Promise<HealthResponse> {
- return this.http.get('/health');
- }
-
- async healthDetailed(): Promise<DetailedHealthResponse> {
- return this.http.get('/health/detailed');
- }
-}
-```
-
-### Resource Classes
+### Quick Start
```typescript
-// src/resources/sessions.ts
-
-export interface Session {
- id: string;
- name: string;
- status: SessionStatus;
- phoneNumber?: string;
- profileName?: string;
- profilePicture?: string;
- createdAt: string;
- lastSeen?: string;
-}
-
-export type SessionStatus = 'INITIALIZING' | 'SCAN_QR' | 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED' | 'FAILED';
-
-export interface CreateSessionInput {
- id?: string;
- name?: string;
- config?: {
- autoReconnect?: boolean;
- webhookUrl?: string;
- proxy?: string;
- };
-}
-
-export class SessionsResource {
- constructor(private http: HttpClient) {}
-
- async list(params?: ListParams): Promise<PaginatedResponse<Session>> {
- return this.http.get('/api/sessions', { params });
- }
-
- async create(input: CreateSessionInput): Promise<Session> {
- return this.http.post('/api/sessions', input);
- }
-
- async get(id: string): Promise<Session> {
- return this.http.get(`/api/sessions/${id}`);
- }
-
- async delete(id: string, keepAuth = false): Promise<void> {
- return this.http.delete(`/api/sessions/${id}`, {
- params: { keepAuth },
- });
- }
-
- async getQr(id: string, format: 'base64' | 'raw' = 'base64'): Promise<QrResponse> {
- return this.http.get(`/api/sessions/${id}/qr`, {
- params: { format },
- });
- }
+import { OpenWAClient } from '@rmyndharis/openwa';
- async restart(id: string): Promise<Session> {
- return this.http.post(`/api/sessions/${id}/restart`);
- }
-
- async logout(id: string): Promise<void> {
- return this.http.post(`/api/sessions/${id}/logout`);
- }
-}
-```
+const client = new OpenWAClient({
+ baseUrl: 'http://localhost:2785',
+ apiKey: 'owa_k1_…',
+});
-```typescript
-// src/resources/messages.ts
-
-export type MessageType =
- | 'text'
- | 'image'
- | 'video'
- | 'audio'
- | 'document'
- | 'location'
- | 'contact'
- | 'sticker'
- | 'buttons'
- | 'list';
-
-export interface Message {
- id: string;
- from: string;
- to: string;
- type: MessageType;
- body?: string;
- caption?: string;
- timestamp: string;
- status: MessageStatus;
- isFromMe: boolean;
- hasMedia: boolean;
- media?: MediaInfo;
-}
+async function main() {
+ // Start a session and bring the WhatsApp connection up.
+ await client.sessions.start('my-session');
-export interface SendMessageInput {
- phone: string;
- type: MessageType;
- body?: string;
- caption?: string;
- media?: MediaInput;
- location?: LocationInput;
- contact?: ContactInput;
- buttons?: ButtonInput[];
- sections?: ListSection[];
- options?: MessageOptions;
-}
+ // Send a text message.
+ const result = await client.messages.sendText('my-session', {
+ chatId: '[email protected]',
+ text: 'Hello from the OpenWA SDK!',
+ });
-export interface MediaInput {
- url?: string;
- base64?: string;
- mimetype?: string;
- filename?: string;
+ console.log(result.messageId); // -> the WhatsApp message id
}
-export class MessagesResource {
- constructor(private http: HttpClient) {}
-
- async send(sessionId: string, input: SendMessageInput): Promise<Message> {
- return this.http.post(`/api/sessions/${sessionId}/messages`, input);
- }
-
- async sendFile(
- sessionId: string,
- phone: string,
- file: File | Buffer | ReadStream,
- options?: SendFileOptions,
- ): Promise<Message> {
- const formData = new FormData();
- formData.append('phone', phone);
- formData.append('type', options?.type || 'document');
- formData.append('media', file);
-
- if (options?.caption) {
- formData.append('caption', options.caption);
- }
-
- return this.http.post(`/api/sessions/${sessionId}/messages`, formData, {
- headers: { 'Content-Type': 'multipart/form-data' },
- });
- }
-
- async list(sessionId: string, phone: string, params?: MessageListParams): Promise<PaginatedResponse<Message>> {
- return this.http.get(`/api/sessions/${sessionId}/messages`, {
- params: { phone, ...params },
- });
- }
-
- async get(sessionId: string, messageId: string): Promise<Message> {
- return this.http.get(`/api/sessions/${sessionId}/messages/${messageId}`);
- }
-
- 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 });
- }
-}
+main();
```
-### Helper Functions
-
-```typescript
-// src/helpers/index.ts
-
-/**
- * Format phone number to WhatsApp JID format
- */
-export function formatPhone(phone: string): string {
- // Remove non-numeric characters
- let cleaned = phone.replace(/\D/g, '');
-
- // Remove leading zeros
- cleaned = cleaned.replace(/^0+/, '');
-
- // Add country code if needed (assuming Indonesian)
- if (!cleaned.startsWith('62') && cleaned.length <= 12) {
- cleaned = '62' + cleaned;
- }
-
- return `${cleaned}@c.us`;
-}
-
-/**
- * Format group ID to WhatsApp JID format
- */
-export function formatGroup(groupId: string): string {
- if (groupId.endsWith('@g.us')) {
- return groupId;
- }
- return `${groupId}@g.us`;
-}
-
-/**
- * Check if JID is a group
- */
-export function isGroup(jid: string): boolean {
- return jid.endsWith('@g.us');
-}
-
-/**
- * Extract phone number from JID
- */
-export function extractPhone(jid: string): string {
- return jid.replace(/@[cgs]\.us$/, '');
-}
-
-/**
- * Create message builder
- */
-export function message(phone: string): MessageBuilder {
- return new MessageBuilder(phone);
-}
-
-export class MessageBuilder {
- private input: Partial<SendMessageInput>;
-
- constructor(phone: string) {
- this.input = { phone: formatPhone(phone) };
- }
-
- text(body: string): this {
- this.input.type = 'text';
- this.input.body = body;
- return this;
- }
-
- image(url: string, caption?: string): this {
- this.input.type = 'image';
- this.input.media = { url };
- this.input.caption = caption;
- return this;
- }
-
- document(url: string, filename: string, caption?: string): this {
- this.input.type = 'document';
- this.input.media = { url, filename };
- this.input.caption = caption;
- return this;
- }
+`sendText` resolves to a `MessageResponse` (`{ messageId: string; timestamp: number }`). `timestamp` is the Unix epoch value returned by the API — **seconds**, passed through unchanged.
- location(lat: number, lng: number, name?: string): this {
- this.input.type = 'location';
- this.input.location = { latitude: lat, longitude: lng, name };
- return this;
- }
-
- replyTo(messageId: string): this {
- this.input.options = { ...this.input.options, quotedMessageId: messageId };
- return this;
- }
+CommonJS consumers use the same API via `require`:
- build(): SendMessageInput {
- if (!this.input.type) {
- throw new Error('Message type not specified');
- }
- return this.input as SendMessageInput;
- }
-}
+```javascript
+const { OpenWAClient } = require('@rmyndharis/openwa');
```
-### Event Handling
-
-```typescript
-// src/events/index.ts
-
-export interface OpenWAEvents {
- // Session events
- 'session.status': (data: SessionStatusEvent) => void;
- 'session.qr': (data: SessionQrEvent) => void;
- 'session.authenticated': (data: SessionAuthenticatedEvent) => void;
- 'session.disconnected': (data: SessionDisconnectedEvent) => void;
-
- // Message events
- 'message.received': (data: MessageEvent) => void;
- 'message.sent': (data: MessageEvent) => void;
- 'message.ack': (data: MessageAckEvent) => void;
- 'message.revoked': (data: MessageRevokedEvent) => void;
-
- // Group events
- 'group.join': (data: GroupJoinEvent) => void;
- 'group.leave': (data: GroupLeaveEvent) => void;
- 'group.update': (data: GroupUpdateEvent) => void;
-
- // Contact events
- 'contact.update': (data: ContactUpdateEvent) => void;
- 'presence.update': (data: PresenceUpdateEvent) => void;
-}
-
-export interface MessageEvent {
- sessionId: string;
- message: Message;
-}
-
-export interface MessageAckEvent {
- sessionId: string;
- messageId: string;
- ack: 'error' | 'pending' | 'server' | 'device' | 'read' | 'played';
-}
-
-// Usage with typed events
-const client = new OpenWA({ ... });
-
-client.on('message.received', ({ sessionId, message }) => {
- console.log(`[${sessionId}] New message from ${message.from}: ${message.body}`);
-});
-
-client.on('message.ack', ({ messageId, ack }) => {
- console.log(`Message ${messageId} status: ${ack}`);
-});
-```
+### Client Configuration
+
+The constructor takes a single `OpenWAClientOptions` object. `baseUrl` and `apiKey` are required (the constructor throws synchronously if either is missing).
+
+| Option | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `baseUrl` | `string` | yes | — | Base URL of the OpenWA API, e.g. `http://localhost:2785`. A trailing slash is trimmed; a path prefix (e.g. `https://host/v1`) is preserved. |
+| `apiKey` | `string` | yes | — | API key sent as the `X-API-Key` header on every request. |
+| `timeoutMs` | `number` | no | `30000` | Per-request timeout in milliseconds. Overridable per call via `RequestOptions.timeoutMs` on the raw `request()` method. |
+| `defaultHeaders` | `Record<string, string>` | no | `{}` | Headers merged onto every request. The `Content-Type: application/json` and `X-API-Key` headers always take precedence. |
+| `fetch` | `FetchLike` | no | `globalThis.fetch` | Injectable transport (the WHATWG `fetch` signature). Use this to wrap requests with retry/observability middleware, or to supply a `fetch` on runtimes that lack a global one. |
+
+### Resources & Methods
+
+All resources are accessed as properties on the client (`client.<resource>.<method>`). Every method returns a `Promise`. Methods marked **OPERATOR** require an API key with the `OPERATOR` role; a non-operator key receives a `403` (`OpenWAForbiddenError`).
+
+The top-level client also exposes:
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `auth` | `client.auth()` | Validate the configured API key and resolve its role (`{ valid, role? }`). |
+| `request` | `client.request<T>(options)` | Raw escape hatch — issue an arbitrary request against the API. |
+
+#### `sessions`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list()` | List all sessions (scoped to the key's `allowedSessions`). |
+| `get` | `get(id)` | Get a single session by id. |
+| `create` | `create(body)` | Create a new session (`body.name` required). **OPERATOR** |
+| `delete` | `delete(id)` | Delete a session. **OPERATOR** |
+| `start` | `start(id)` | Start a session and initialize the WhatsApp connection. |
+| `stop` | `stop(id)` | Stop a session and disconnect gracefully. |
+| `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). |
+| `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). |
+| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. |
+| `stats` | `stats()` | Aggregate statistics across the key's sessions. |
+
+#### `messages`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId, query?)` | List messages (filter by chat/sender); returns `{ messages, total }`. |
+| `sendText` | `sendText(sessionId, { chatId, text })` | Send a text message (`text` max 4096 chars). |
+| `sendImage` | `sendImage(sessionId, body)` | Send an image (`url` or `base64`). |
+| `sendVideo` | `sendVideo(sessionId, body)` | Send a video (`url` or `base64`). |
+| `sendAudio` | `sendAudio(sessionId, body)` | Send an audio file (`url` or `base64`). |
+| `sendDocument` | `sendDocument(sessionId, body)` | Send a document (`url` or `base64`; `filename` recommended). |
+| `sendSticker` | `sendSticker(sessionId, body)` | Send a sticker (`url` or `base64`). |
+| `sendLocation` | `sendLocation(sessionId, body)` | Send a location (`{ chatId, latitude, longitude, description? }`). |
+| `sendContact` | `sendContact(sessionId, body)` | Send a contact card. |
+| `sendTemplate` | `sendTemplate(sessionId, body)` | Render and send a stored message template. |
+| `reply` | `reply(sessionId, body)` | Reply to a specific message. |
+| `forward` | `forward(sessionId, body)` | Forward a message to another chat. |
+| `react` | `react(sessionId, body)` | React to a message (empty `reaction` removes it). |
+| `delete` | `delete(sessionId, body)` | Delete a message. |
+| `history` | `history(sessionId, chatId, query?)` | Get message history for a chat (read live from WhatsApp). |
+| `reactions` | `reactions(sessionId, chatId, messageId)` | Get reactions for a specific message. |
+| `sendBulk` | `sendBulk(sessionId, body)` | Send a batch asynchronously (202 + batch id); poll via `batchStatus`. |
+| `batchStatus` | `batchStatus(sessionId, batchId)` | Poll the status/progress of a bulk-send batch. |
+| `cancelBatch` | `cancelBatch(sessionId, batchId)` | Cancel a running batch. **OPERATOR** |
+
+Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mimetype?, filename?, caption? }` (`url` and `base64` are mutually exclusive; `base64` requires `mimetype`).
+
+#### `contacts`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId, query?)` | List contacts known to the session. |
+| `get` | `get(sessionId, contactId)` | Get details for a single contact by JID. |
+| `check` | `check(sessionId, number)` | Check whether a phone number is registered on WhatsApp. |
+| `profilePicture` | `profilePicture(sessionId, contactId)` | Get the contact's profile picture URL (or null). |
+| `phone` | `phone(sessionId, contactId)` | Resolve a contact id (e.g. a `@lid`) to a phone number. |
+| `block` | `block(sessionId, contactId)` | Block a contact. **OPERATOR** |
+| `unblock` | `unblock(sessionId, contactId)` | Unblock a contact. **OPERATOR** |
+
+#### `groups`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId, query?)` | List all groups for the session. |
+| `get` | `get(sessionId, groupId)` | Get detailed group info including participants. |
+| `create` | `create(sessionId, body)` | Create a new group. **OPERATOR** |
+| `addParticipants` | `addParticipants(sessionId, groupId, participants)` | Add participants (`string[]`) to a group. **OPERATOR** |
+| `removeParticipants` | `removeParticipants(sessionId, groupId, participants)` | Remove participants from a group. **OPERATOR** |
+| `promoteParticipants` | `promoteParticipants(sessionId, groupId, participants)` | Promote participants to group admin. **OPERATOR** |
+| `demoteParticipants` | `demoteParticipants(sessionId, groupId, participants)` | Demote participants from group admin. **OPERATOR** |
+| `setSubject` | `setSubject(sessionId, groupId, subject)` | Update the group subject (name). **OPERATOR** |
+| `setDescription` | `setDescription(sessionId, groupId, description)` | Update the group description (empty clears it). **OPERATOR** |
+| `leave` | `leave(sessionId, groupId)` | Leave a group. **OPERATOR** |
+| `inviteCode` | `inviteCode(sessionId, groupId)` | Get the group invite code and link. |
+| `revokeInviteCode` | `revokeInviteCode(sessionId, groupId)` | Revoke the current invite code and generate a new one. **OPERATOR** |
+
+#### `chats`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId, query?)` | List active chats, most recent first. |
+| `markRead` | `markRead(sessionId, body)` | Mark a chat as read/seen. **OPERATOR** |
+| `markUnread` | `markUnread(sessionId, body)` | Mark a chat as unread. **OPERATOR** |
+| `delete` | `delete(sessionId, body)` | Delete a chat from the chat list. **OPERATOR** |
+| `sendState` | `sendState(sessionId, body)` | Send a chat presence state (typing/recording/paused). **OPERATOR** |
+
+#### `webhooks`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId)` | List all webhooks for a session. |
+| `get` | `get(sessionId, id)` | Get a single webhook by id. |
+| `create` | `create(sessionId, body)` | Create a new webhook. **OPERATOR** |
+| `update` | `update(sessionId, id, body)` | Update a webhook. **OPERATOR** |
+| `delete` | `delete(sessionId, id)` | Delete a webhook. **OPERATOR** |
+| `test` | `test(sessionId, id)` | Trigger a test dispatch to the webhook URL and report the result. **OPERATOR** |
+
+#### `labels` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId)` | List all labels available in the business account. |
+| `get` | `get(sessionId, labelId)` | Get a single label by id. |
+| `forChat` | `forChat(sessionId, chatId)` | Get the labels currently applied to a chat. |
+| `addToChat` | `addToChat(sessionId, chatId, body)` | Add a label to a chat. **OPERATOR** |
+| `removeFromChat` | `removeFromChat(sessionId, chatId, labelId)` | Remove a label from a chat. **OPERATOR** |
+
+#### `channels` *(Newsletters)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId)` | List all channels/newsletters the session is subscribed to. |
+| `get` | `get(sessionId, channelId)` | Get a single channel by id. |
+| `messages` | `messages(sessionId, channelId, query?)` | Get recent messages from a channel. |
+| `subscribe` | `subscribe(sessionId, body)` | Subscribe to a channel using its invite code. **OPERATOR** |
+| `unsubscribe` | `unsubscribe(sessionId, channelId)` | Unsubscribe from a channel. **OPERATOR** |
+
+#### `catalog` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `info` | `info(sessionId)` | Get the business catalog info. |
+| `products` | `products(sessionId, query?)` | List catalog products; returns `{ products, pagination }`. |
+| `product` | `product(sessionId, productId)` | Get a single product by id. |
+| `sendProduct` | `sendProduct(sessionId, body)` | Send a product message. **OPERATOR** |
+| `sendCatalog` | `sendCatalog(sessionId, body)` | Send a catalog link message. **OPERATOR** |
+
+#### `status` *(Stories)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId)` | Get all status updates (`{ statuses }`). |
+| `fromContact` | `fromContact(sessionId, contactId)` | Get status updates from a specific contact. |
+| `sendText` | `sendText(sessionId, body)` | Post a text status update. **OPERATOR** |
+| `sendImage` | `sendImage(sessionId, body)` | Post an image status update. **OPERATOR** |
+| `sendVideo` | `sendVideo(sessionId, body)` | Post a video status update. **OPERATOR** |
+| `delete` | `delete(sessionId, statusId)` | Delete a status update by id. **OPERATOR** |
+
+> This is WhatsApp "Status/Stories", distinct from session lifecycle status.
+
+#### `templates`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(sessionId)` | List all templates for a session. |
+| `get` | `get(sessionId, id)` | Get a single template by id. |
+| `create` | `create(sessionId, body)` | Create a new template. **OPERATOR** |
+| `update` | `update(sessionId, id, body)` | Update a template. **OPERATOR** |
+| `delete` | `delete(sessionId, id)` | Delete a template. **OPERATOR** |
+
+#### `health`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `check` | `check()` | General health (also returns the running version). |
+| `live` | `live()` | Kubernetes liveness probe (`{ status }`). |
+| `ready` | `ready()` | Kubernetes readiness probe — checks both DB connections. |
### Error Handling
-```typescript
-// src/errors/index.ts
-
-export class OpenWAError extends Error {
- constructor(
- message: string,
- public code: string,
- public status: number,
- public details?: unknown,
- ) {
- super(message);
- this.name = 'OpenWAError';
- }
-}
+On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`).
-export class ValidationError extends OpenWAError {
- constructor(message: string, details?: unknown) {
- super(message, 'VALIDATION_ERROR', 400, details);
- this.name = 'ValidationError';
- }
-}
-
-export class AuthenticationError extends OpenWAError {
- constructor(message = 'Invalid API key') {
- super(message, 'AUTHENTICATION_ERROR', 401);
- this.name = 'AuthenticationError';
- }
-}
-
-export class SessionNotFoundError extends OpenWAError {
- constructor(sessionId: string) {
- super(`Session '${sessionId}' not found`, 'SESSION_NOT_FOUND', 404);
- this.name = 'SessionNotFoundError';
- }
-}
+| Error class | HTTP status | Meaning |
+| --- | --- | --- |
+| `OpenWAAuthError` | 401 | Missing or invalid API key. |
+| `OpenWAForbiddenError` | 403 | The key's role is insufficient (e.g. an OPERATOR-only route). |
+| `OpenWANotFoundError` | 404 | Resource not found. |
+| `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. |
+| `OpenWARateLimitError` | 429 | Rate limited. |
+| `OpenWANotImplementedError` | 501 | The active engine does not support this operation. |
+| `OpenWAApiError` | any other | Generic non-2xx (the base API error, e.g. `400`; also surfaced for unfollowed 3xx redirects). |
+| `OpenWATimeoutError` | — | The request exceeded the configured timeout. |
-export class RateLimitError extends OpenWAError {
- constructor(public retryAfter: number) {
- super(`Rate limited. Retry after ${retryAfter}ms`, 'RATE_LIMIT_EXCEEDED', 429);
- this.name = 'RateLimitError';
- }
-}
+```typescript
+import {
+ OpenWAClient,
+ OpenWAConflictError,
+ OpenWANotFoundError,
+ OpenWARateLimitError,
+ OpenWATimeoutError,
+ OpenWAApiError,
+} from '@rmyndharis/openwa';
-// Error handling example
try {
- await client.messages.send('session-1', {
- phone: '[email protected]',
- type: 'text',
- body: 'Hello!',
+ await client.messages.sendText('my-session', {
+ chatId: '[email protected]',
+ text: 'Hi!',
});
-} catch (error) {
- if (error instanceof RateLimitError) {
- console.log(`Rate limited, retry in ${error.retryAfter}ms`);
- await sleep(error.retryAfter);
- // Retry
- } else if (error instanceof SessionNotFoundError) {
- console.log('Session not found, creating new session...');
- await client.sessions.create({ id: 'session-1' });
+} catch (err) {
+ if (err instanceof OpenWAConflictError) {
+ // 409 — engine not ready; start the session first.
+ } else if (err instanceof OpenWANotFoundError) {
+ // 404 — session/chat does not exist.
+ } else if (err instanceof OpenWARateLimitError) {
+ // 429 — back off and retry.
+ } else if (err instanceof OpenWATimeoutError) {
+ // request timed out.
+ } else if (err instanceof OpenWAApiError) {
+ console.error(`API error ${err.status}:`, err.body);
} else {
- throw error;
+ throw err; // network/transport error
}
}
```
+### Notable Behaviors
+
+- **Redirects are never followed.** The transport uses `redirect: 'manual'`, so a `3xx` surfaces to the caller as an error (via `OpenWAApiError`) rather than being followed — this guarantees the `X-API-Key` header is never re-sent to a redirect target (potentially a different origin).
+- **Auth and JSON headers take precedence.** Request headers are merged in the order `Content-Type: application/json` → `defaultHeaders` → per-call headers → `X-API-Key`. The `X-API-Key` is applied last and cannot be overridden; `Content-Type` defaults to JSON.
+- **Path segments are percent-encoded.** Ids (session, chat, message, etc.) are encoded so a value cannot break out of its path position, while keeping the WhatsApp-safe characters `@`, `:`, and `+` readable (e.g. `[email protected]`).
+- **Base-URL path prefix is preserved.** A `baseUrl` such as `https://gateway.example.com/v1` keeps its `/v1` prefix on every request; only a trailing slash is trimmed.
+- **No automatic retries.** A failed request rejects immediately — the SDK does not retry, even on `429`. Wrap calls in your own backoff if you need retries.
+- **Injectable transport.** Supply a custom `fetch` to wrap outbound calls with retry, logging, or observability middleware, or to run on a runtime without a global `fetch`. This is also the recommended way to unit-test without monkey-patching globals.
+- **Dual CJS + ESM.** The package exposes both an `import` (ESM) and `require` (CommonJS) entry point with bundled type declarations, so it works in either module system without configuration.
+
## 18.3 Python SDK
+The Python SDK is a **synchronous** client built on [`httpx`](https://www.python-httpx.org/). It ships its own type hints (PEP 561) so editors and type-checkers see the full surface without stubs. There is **no async client and no event/streaming model** — every call is a blocking method that returns a plain `dict`/`list` (or `None` for a 204), and request payloads are plain `dict`s.
+
### Installation
+The PyPI distribution name and the import package differ:
+
```bash
-pip install openwa-sdk
+pip install rmyndharis-openwa
```
-### Quick Start
-
```python
-from openwa import OpenWA
-import asyncio
-
-async def main():
- client = OpenWA(
- base_url="http://localhost:2785",
- api_key="your-api-key"
- )
-
- # Create session
- session = await client.sessions.create(
- id="my-session",
- name="My WhatsApp"
- )
-
- # Send message
- message = await client.messages.send(
- session_id="my-session",
- type="text",
- body="Hello from Python!"
- )
-
- print(f"Message sent: {message.id}")
-
-asyncio.run(main())
+from openwa import OpenWAClient
```
-### SDK Structure
+- **Distribution (PyPI):** `rmyndharis-openwa`
+- **Import package:** `openwa`
+- **Client class:** `OpenWAClient`
+- **Python:** `>=3.9` (per `pyproject.toml`)
+- **Runtime dependency:** `httpx>=0.25.0,<1.0`
+- **Typed:** ships `py.typed` markers for `openwa` and `openwa.resources` (PEP 561)
-```python
-# openwa/__init__.py
-
-from typing import Optional, List, Dict, Any
-from dataclasses import dataclass
-from enum import Enum
-import aiohttp
-
-class SessionStatus(Enum):
- INITIALIZING = "INITIALIZING"
- SCAN_QR = "SCAN_QR"
- CONNECTING = "CONNECTING"
- CONNECTED = "CONNECTED"
- DISCONNECTED = "DISCONNECTED"
- FAILED = "FAILED"
-
-@dataclass
-class Session:
- id: str
- name: str
- status: SessionStatus
- phone_number: Optional[str] = None
- profile_name: Optional[str] = None
- created_at: Optional[str] = None
-
-@dataclass
-class Message:
- id: str
- from_: str
- to: str
- type: str
- body: Optional[str] = None
- timestamp: Optional[str] = None
- status: Optional[str] = None
- is_from_me: bool = False
-
-class OpenWA:
- def __init__(
- self,
- base_url: str,
- api_key: str,
- timeout: int = 30
- ):
- self.base_url = base_url.rstrip('/')
- self.api_key = api_key
- self.timeout = timeout
-
- self.sessions = SessionsResource(self)
- self.messages = MessagesResource(self)
- self.contacts = ContactsResource(self)
- self.groups = GroupsResource(self)
- self.webhooks = WebhooksResource(self)
-
- async def _request(
- self,
- method: str,
- path: str,
- **kwargs
- ) -> Dict[str, Any]:
- headers = {
- "X-API-Key": self.api_key,
- "Content-Type": "application/json"
- }
-
- async with aiohttp.ClientSession() as session:
- async with session.request(
- method,
- f"{self.base_url}{path}",
- headers=headers,
- timeout=aiohttp.ClientTimeout(total=self.timeout),
- **kwargs
- ) as response:
- data = await response.json()
-
- if not response.ok:
- raise OpenWAError(
- message=data.get("message", "Unknown error"),
- code=str(response.status),
- status=response.status
- )
-
- return data
-
- async def health(self) -> Dict[str, Any]:
- return await self._request("GET", "/health")
-
-
-class SessionsResource:
- def __init__(self, client: OpenWA):
- self.client = client
-
- async def list(
- self,
- status: Optional[str] = None,
- limit: int = 20,
- offset: int = 0
- ) -> List[Session]:
- params = {"limit": limit, "offset": offset}
- if status:
- params["status"] = status
-
- data = await self.client._request(
- "GET",
- "/api/sessions",
- params=params
- )
- return [Session(**s) for s in data]
-
- async def create(
- self,
- id: Optional[str] = None,
- name: Optional[str] = None,
- **config
- ) -> Session:
- body = {}
- if id:
- body["id"] = id
- if name:
- body["name"] = name
- if config:
- body["config"] = config
-
- data = await self.client._request(
- "POST",
- "/api/sessions",
- json=body
- )
- return Session(**data)
-
- async def get(self, id: str) -> Session:
- data = await self.client._request("GET", f"/api/sessions/{id}")
- return Session(**data)
-
- async def delete(self, id: str, keep_auth: bool = False) -> None:
- await self.client._request(
- "DELETE",
- f"/api/sessions/{id}",
- params={"keepAuth": keep_auth}
- )
-
- async def get_qr(self, id: str, format: str = "base64") -> Dict[str, str]:
- return await self.client._request(
- "GET",
- f"/api/sessions/{id}/qr",
- params={"format": format}
- )
-
-
-class MessagesResource:
- def __init__(self, client: OpenWA):
- self.client = client
-
- async def send(
- self,
- session_id: str,
- phone: str,
- type: str,
- body: Optional[str] = None,
- media: Optional[Dict] = None,
- caption: Optional[str] = None,
- **kwargs
- ) -> Message:
- payload = {
- "phone": phone,
- "type": type,
- }
- if body:
- payload["body"] = body
- if media:
- payload["media"] = media
- if caption:
- payload["caption"] = caption
- payload.update(kwargs)
-
- data = await self.client._request(
- "POST",
- f"/api/sessions/{session_id}/messages",
- json=payload
- )
- return Message(**data)
-
- async def send_text(
- self,
- session_id: str,
- phone: str,
- text: str
- ) -> Message:
- return await self.send(session_id, phone, "text", body=text)
-
- async def send_image(
- self,
- session_id: str,
- phone: str,
- url: str,
- caption: Optional[str] = None
- ) -> Message:
- return await self.send(
- session_id,
- phone,
- "image",
- media={"url": url},
- caption=caption
- )
-
-
-class OpenWAError(Exception):
- def __init__(self, message: str, code: str, status: int):
- super().__init__(message)
- self.code = code
- self.status = status
-```
-
-### Sync Wrapper
+### Quick Start
```python
-# openwa/sync.py
+from openwa import OpenWAClient
-from .async_client import OpenWA as AsyncOpenWA
-import asyncio
+client = OpenWAClient(
+ base_url="http://localhost:2785",
+ api_key="owa_k1_…",
+)
-class OpenWASync:
- """Synchronous wrapper for OpenWA client"""
+# Create then start a session
+client.sessions.create({"name": "my-session"})
+client.sessions.start("my-session")
- def __init__(self, **kwargs):
- self._async_client = AsyncOpenWA(**kwargs)
- self._loop = asyncio.new_event_loop()
+# Send a text message
+result = client.messages.send_text("my-session", {
+ "chatId": "[email protected]",
+ "text": "Hello from the OpenWA Python SDK!",
+})
+print(result["messageId"])
- def _run(self, coro):
- return self._loop.run_until_complete(coro)
+client.close()
+```
- @property
- def sessions(self):
- return SessionsResourceSync(self._async_client.sessions, self._run)
+`OpenWAClient` is also a context manager, so the connection pool is closed for you:
- @property
- def messages(self):
- return MessagesResourceSync(self._async_client.messages, self._run)
+```python
+with OpenWAClient(base_url="http://localhost:2785", api_key="owa_k1_…") as client:
+ print(client.health.check())
+```
- def health(self):
- return self._run(self._async_client.health())
+### Client Configuration
+Constructor signature (from `client.py`):
-class SessionsResourceSync:
- def __init__(self, async_resource, run):
- self._async = async_resource
- self._run = run
+```python
+OpenWAClient(
+ base_url: str,
+ api_key: str,
+ *,
+ timeout: float = 30.0,
+ default_headers: Mapping[str, str] | None = None,
+ transport: httpx.BaseTransport | None = None,
+)
+```
- def list(self, **kwargs):
- return self._run(self._async.list(**kwargs))
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| `base_url` | `str` | *(required)* | Gateway base URL, e.g. `http://localhost:2785`. Raises `ValueError` if empty. A trailing `/` is stripped; any path prefix is preserved. |
+| `api_key` | `str` | *(required)* | API key sent as the `X-API-Key` header. Raises `ValueError` if empty. |
+| `timeout` | `float` | `30.0` | Per-request timeout in seconds. A breach raises `OpenWATimeoutError`. |
+| `default_headers` | `Mapping[str, str] \| None` | `None` | Extra headers applied to every request. Applied **first**, so the SDK's `X-API-Key` and `Content-Type: application/json` always win. |
+| `transport` | `httpx.BaseTransport \| None` | `None` | Optional `httpx` transport override (e.g. `httpx.MockTransport`) sharing the one connection pool. Useful for testing. |
+
+The client also exposes a few non-resource members:
+
+| Member | Signature | Description |
+| --- | --- | --- |
+| `auth` | `auth() -> AuthValidateResponse` | `POST /api/auth/validate` — validate the configured API key. |
+| `request` | `request(method, path, *, query=None, body=None) -> Any` | Raw escape hatch; `path` begins with `/`. |
+| `close` | `close() -> None` | Close the underlying `httpx.Client`. |
+
+### Resources & Methods
+
+Resources are accessed as properties on the client (e.g. `client.messages`). All methods are **snake_case**; `body`/`query` arguments are plain dicts. Methods marked **OPERATOR** require an `OPERATOR`-level API key.
+
+#### `client.sessions`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list() -> list[SessionResponse]` | List all sessions. |
+| `get` | `get(session_id) -> SessionResponse` | Get one session. |
+| `create` | `create(body) -> SessionResponse` | Create a session (`body["name"]` required). |
+| `delete` | `delete(session_id) -> None` | Delete a session. |
+| `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. |
+| `stop` | `stop(session_id) -> SessionResponse` | Stop a session. |
+| `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. |
+| `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. |
+| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. |
+| `stats` | `stats() -> SessionStatsOverview` | Session statistics overview. |
+
+#### `client.messages`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id, query=None) -> MessageListResponse` | List stored messages. |
+| `send_text` | `send_text(session_id, body) -> MessageResponse` | Send a text message. |
+| `send_image` | `send_image(session_id, body) -> MessageResponse` | Send an image. |
+| `send_video` | `send_video(session_id, body) -> MessageResponse` | Send a video. |
+| `send_audio` | `send_audio(session_id, body) -> MessageResponse` | Send audio. |
+| `send_document` | `send_document(session_id, body) -> MessageResponse` | Send a document. |
+| `send_sticker` | `send_sticker(session_id, body) -> MessageResponse` | Send a sticker. |
+| `send_location` | `send_location(session_id, body) -> MessageResponse` | Send a location. |
+| `send_contact` | `send_contact(session_id, body) -> MessageResponse` | Send a contact card. |
+| `send_template` | `send_template(session_id, body) -> MessageResponse` | Send a stored template. |
+| `reply` | `reply(session_id, body) -> MessageResponse` | Reply to a message. |
+| `forward` | `forward(session_id, body) -> MessageResponse` | Forward a message. |
+| `react` | `react(session_id, body) -> SuccessResult` | React to a message. |
+| `delete` | `delete(session_id, body) -> SuccessResult` | Delete a message. |
+| `history` | `history(session_id, chat_id, query=None) -> list[ChatHistoryMessage]` | Fetch chat history. |
+| `reactions` | `reactions(session_id, chat_id, message_id) -> list[ReactionRecord]` | List reactions on a message. |
+| `send_bulk` | `send_bulk(session_id, body) -> BulkMessageResponse` | Enqueue a bulk send batch. |
+| `batch_status` | `batch_status(session_id, batch_id) -> BatchStatusResponse` | Get bulk batch status. |
+| `cancel_batch` | `cancel_batch(session_id, batch_id) -> BatchStatusResponse` | Cancel a running batch. **OPERATOR** |
+
+#### `client.contacts`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id, query=None) -> list[ContactRecord]` | List contacts (`query`: `limit`, `offset`). |
+| `get` | `get(session_id, contact_id) -> ContactRecord` | Get one contact. |
+| `check` | `check(session_id, number) -> CheckNumberResponse` | Check whether a number is on WhatsApp. |
+| `profile_picture` | `profile_picture(session_id, contact_id) -> ProfilePictureResponse` | Get a contact's profile picture. |
+| `phone` | `phone(session_id, contact_id) -> ContactPhoneResponse` | Resolve a contact's phone number. |
+| `block` | `block(session_id, contact_id) -> SuccessResult` | Block a contact. **OPERATOR** |
+| `unblock` | `unblock(session_id, contact_id) -> SuccessResult` | Unblock a contact. **OPERATOR** |
+
+#### `client.groups`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id, query=None) -> list[GroupSummary]` | List groups (`query`: `limit`, `offset`). |
+| `get` | `get(session_id, group_id) -> GroupInfo` | Get group details. |
+| `create` | `create(session_id, body) -> GroupInfo` | Create a group. **OPERATOR** |
+| `add_participants` | `add_participants(session_id, group_id, participants) -> SuccessResult` | Add participants (`list[str]`). **OPERATOR** |
+| `remove_participants` | `remove_participants(session_id, group_id, participants) -> SuccessResult` | Remove participants. **OPERATOR** |
+| `promote_participants` | `promote_participants(session_id, group_id, participants) -> SuccessResult` | Promote to admin. **OPERATOR** |
+| `demote_participants` | `demote_participants(session_id, group_id, participants) -> SuccessResult` | Demote from admin. **OPERATOR** |
+| `set_subject` | `set_subject(session_id, group_id, subject) -> SuccessResult` | Set group subject. **OPERATOR** |
+| `set_description` | `set_description(session_id, group_id, description) -> SuccessResult` | Set group description. **OPERATOR** |
+| `leave` | `leave(session_id, group_id) -> SuccessResult` | Leave the group. **OPERATOR** |
+| `invite_code` | `invite_code(session_id, group_id) -> InviteCodeResponse` | Get the invite code. |
+| `revoke_invite_code` | `revoke_invite_code(session_id, group_id) -> InviteCodeResponse` | Revoke and regenerate the invite code. **OPERATOR** |
+
+#### `client.chats`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id, query=None) -> list[ChatSummary]` | List chats (`query`: `limit`, `offset`). |
+| `mark_read` | `mark_read(session_id, body) -> SuccessResult` | Mark a chat as read. **OPERATOR** |
+| `mark_unread` | `mark_unread(session_id, body) -> SuccessResult` | Mark a chat as unread. **OPERATOR** |
+| `delete` | `delete(session_id, body) -> SuccessResult` | Delete a chat. **OPERATOR** |
+| `send_state` | `send_state(session_id, body) -> SuccessResult` | Send a typing/recording chat state. **OPERATOR** |
+
+#### `client.webhooks`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id) -> list[WebhookResponse]` | List webhooks. |
+| `get` | `get(session_id, webhook_id) -> WebhookResponse` | Get one webhook. |
+| `create` | `create(session_id, body) -> WebhookResponse` | Create a webhook. **OPERATOR** |
+| `update` | `update(session_id, webhook_id, body) -> WebhookResponse` | Update a webhook. **OPERATOR** |
+| `delete` | `delete(session_id, webhook_id) -> None` | Delete a webhook. **OPERATOR** |
+| `test` | `test(session_id, webhook_id) -> WebhookTestResult` | Send a test delivery. **OPERATOR** |
+
+#### `client.labels` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id) -> list[LabelRecord]` | List labels. |
+| `get` | `get(session_id, label_id) -> LabelRecord` | Get one label. |
+| `for_chat` | `for_chat(session_id, chat_id) -> list[LabelRecord]` | Labels applied to a chat. |
+| `add_to_chat` | `add_to_chat(session_id, chat_id, body) -> SuccessResult` | Add a label to a chat. **OPERATOR** |
+| `remove_from_chat` | `remove_from_chat(session_id, chat_id, label_id) -> SuccessResult` | Remove a label from a chat. **OPERATOR** |
+
+#### `client.channels` *(Newsletters)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id) -> list[ChannelRecord]` | List subscribed channels. |
+| `get` | `get(session_id, channel_id) -> ChannelRecord` | Get one channel. |
+| `messages` | `messages(session_id, channel_id, query=None) -> list[MessageRecord]` | List channel messages. |
+| `subscribe` | `subscribe(session_id, body) -> ChannelRecord` | Subscribe via invite code. **OPERATOR** |
+| `unsubscribe` | `unsubscribe(session_id, channel_id) -> SuccessResult` | Unsubscribe from a channel. **OPERATOR** |
+
+#### `client.catalog` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `info` | `info(session_id) -> CatalogInfo` | Get catalog info. |
+| `products` | `products(session_id, query=None) -> PaginatedProducts` | List products (paginated). |
+| `product` | `product(session_id, product_id) -> CatalogProduct` | Get one product. |
+| `send_product` | `send_product(session_id, body) -> MessageResponse` | Send a product message. **OPERATOR** |
+| `send_catalog` | `send_catalog(session_id, body) -> MessageResponse` | Send a catalog link message. **OPERATOR** |
+
+#### `client.status` *(Stories)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id) -> dict[str, list[StatusRecord]]` | List all status updates. |
+| `from_contact` | `from_contact(session_id, contact_id) -> dict[str, list[StatusRecord]]` | Status updates from one contact. |
+| `send_text` | `send_text(session_id, body) -> StatusRecord` | Post a text status. **OPERATOR** |
+| `send_image` | `send_image(session_id, body) -> StatusRecord` | Post an image status. **OPERATOR** |
+| `send_video` | `send_video(session_id, body) -> StatusRecord` | Post a video status. **OPERATOR** |
+| `delete` | `delete(session_id, status_id) -> None` | Delete a status. **OPERATOR** |
+
+#### `client.templates`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(session_id) -> list[TemplateRecord]` | List templates. |
+| `get` | `get(session_id, template_id) -> TemplateRecord` | Get one template. |
+| `create` | `create(session_id, body) -> TemplateRecord` | Create a template. **OPERATOR** |
+| `update` | `update(session_id, template_id, body) -> TemplateRecord` | Update a template. **OPERATOR** |
+| `delete` | `delete(session_id, template_id) -> None` | Delete a template. **OPERATOR** |
+
+#### `client.health`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `check` | `check() -> HealthResponse` | Aggregate health check. |
+| `live` | `live() -> dict[str, str]` | Liveness probe. |
+| `ready` | `ready() -> HealthReadyResponse` | Readiness probe. |
- def create(self, **kwargs):
- return self._run(self._async.create(**kwargs))
+### Error Handling
- def get(self, id):
- return self._run(self._async.get(id))
+Every error inherits from `OpenWAError`. A non-2xx response raises an `OpenWAApiError` (or a more specific subclass picked by status); a timeout raises `OpenWATimeoutError`. The API-error classes carry `.status` (HTTP code), `.body` (parsed JSON or raw text), and `.error_kind` (the NestJS `error` field).
- def delete(self, id, **kwargs):
- return self._run(self._async.delete(id, **kwargs))
+| Exception | Trigger |
+| --- | --- |
+| `OpenWAAuthError` | HTTP `401` — missing or invalid API key |
+| `OpenWAForbiddenError` | HTTP `403` — insufficient role |
+| `OpenWANotFoundError` | HTTP `404` — resource not found |
+| `OpenWAConflictError` | HTTP `409` — typically engine-not-ready |
+| `OpenWARateLimitError` | HTTP `429` — too many requests |
+| `OpenWANotImplementedError` | HTTP `501` — active engine doesn't support the operation |
+| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |
+| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |
+```python
+from openwa import (
+ OpenWAClient,
+ OpenWAConflictError,
+ OpenWANotFoundError,
+ OpenWARateLimitError,
+ OpenWATimeoutError,
+ OpenWAApiError,
+)
+
+client = OpenWAClient(base_url="http://localhost:2785", api_key="owa_k1_…")
+
+try:
+ client.messages.send_text("my-session", {
+ "chatId": "[email protected]",
+ "text": "Hi!",
+ })
+except OpenWAConflictError:
+ print("Session engine not ready yet — start it first.")
+except OpenWANotFoundError:
+ print("Session does not exist.")
+except OpenWARateLimitError:
+ print("Rate limited — back off and retry.")
+except OpenWATimeoutError as e:
+ print(f"Timed out after {e.timeout}s")
+except OpenWAApiError as e:
+ print(f"API error {e.status} ({e.error_kind}): {e.body}")
+```
-# Usage
-from openwa.sync import OpenWASync
+### Notable Behaviors
-client = OpenWASync(base_url="http://localhost:2785", api_key="your-key")
-sessions = client.sessions.list()
-```
+- **Redirects are never followed.** `follow_redirects` is forced off so the `X-API-Key` header is never re-sent to a redirect target. An unfollowed `3xx` therefore surfaces as an `OpenWAApiError` rather than a success.
+- **Auth/JSON headers always win.** `default_headers` are applied first; the SDK then sets `Content-Type: application/json` and `X-API-Key`, so caller headers can never clobber them.
+- **Path segments are percent-encoded.** Each path value (session/chat/message id, etc.) is encoded so a `/`, `#`, or `?` can't break out of its position; already-safe id characters `@`, `:`, `+` are left readable. Boolean query params are serialized lowercase (`true`/`false`); `None` query values are dropped.
+- **Base-URL path prefix is preserved.** A trailing `/` is stripped from `base_url`, but any path prefix (e.g. when running behind a reverse proxy) is kept on every request.
+- **No automatic retries.** Each call issues exactly one request; retry/backoff is the caller's responsibility. Wrap or inject a custom `transport` for retry or observability middleware.
+- **Testable transport injection.** Pass `transport=httpx.MockTransport(handler)` to intercept requests in tests — no global monkey-patching.
+- **204 / non-JSON handling.** A `204` (or empty body) returns `None`; a 2xx body that isn't valid JSON is returned as raw text instead of raising.
+- **PEP 561 typed.** The package ships `py.typed`, so type-checkers consume the bundled hints directly.
## 18.4 PHP SDK
+The PHP SDK is a hand-written, synchronous client built on Guzzle 7. It mirrors the full user-facing API surface: every resource method maps to one REST endpoint, request/response payloads are plain associative arrays, and non-2xx responses are translated into a typed `OpenWA*Exception` hierarchy.
+
### Installation
```bash
-composer require openwa/sdk
+composer require rmyndharis/openwa
```
+Requirements:
+
+- **PHP 8.1+** (`declare(strict_types=1)` throughout; typed properties, `match`).
+- **Guzzle 7** (`guzzlehttp/guzzle: ^7.9`).
+- PSR-4 autoloaded under the `OpenWA\` namespace (`"OpenWA\\": "src/"`).
+
### Quick Start
```php
<?php
+require 'vendor/autoload.php';
use OpenWA\Client;
-use OpenWA\Resources\Messages;
$client = new Client([
'baseUrl' => 'http://localhost:2785',
- 'apiKey' => 'your-api-key',
+ 'apiKey' => 'owa_k1_…',
]);
-// Create session
-$session = $client->sessions->create([
- 'id' => 'my-session',
- 'name' => 'My WhatsApp',
-]);
+$client->sessions->start('my-session');
-// Send message
-$message = $client->messages->send('my-session', [
- 'phone' => '[email protected]',
- 'type' => 'text',
- 'body' => 'Hello from PHP!',
+$result = $client->messages->sendText('my-session', [
+ 'chatId' => '[email protected]',
+ 'text' => 'Hello from the OpenWA PHP SDK!',
]);
-echo "Message sent: " . $message->id;
+echo $result['messageId'];
```
-### SDK Structure
-
-```php
-<?php
-// src/Client.php
-
-namespace OpenWA;
-
-use GuzzleHttp\Client as HttpClient;
-use OpenWA\Resources\Sessions;
-use OpenWA\Resources\Messages;
-use OpenWA\Resources\Contacts;
-use OpenWA\Resources\Groups;
-use OpenWA\Resources\Webhooks;
-use OpenWA\Exceptions\OpenWAException;
-
-class Client
-{
- private HttpClient $http;
- private array $config;
-
- public Sessions $sessions;
- public Messages $messages;
- public Contacts $contacts;
- public Groups $groups;
- public Webhooks $webhooks;
-
- public function __construct(array $config)
- {
- $this->config = array_merge([
- 'timeout' => 30,
- ], $config);
-
- $this->http = new HttpClient([
- 'base_uri' => rtrim($this->config['baseUrl'], '/'),
- 'timeout' => $this->config['timeout'],
- 'headers' => [
- 'X-API-Key' => $this->config['apiKey'],
- 'Content-Type' => 'application/json',
- 'Accept' => 'application/json',
- ],
- ]);
-
- $this->sessions = new Sessions($this);
- $this->messages = new Messages($this);
- $this->contacts = new Contacts($this);
- $this->groups = new Groups($this);
- $this->webhooks = new Webhooks($this);
- }
-
- public function request(string $method, string $path, array $options = []): array
- {
- try {
- $response = $this->http->request($method, $path, $options);
- $data = json_decode($response->getBody()->getContents(), true);
-
- return $data ?? [];
- } catch (\GuzzleHttp\Exception\RequestException $e) {
- $response = $e->getResponse();
- $data = $response ? json_decode($response->getBody()->getContents(), true) : null;
-
- throw new OpenWAException(
- $data['message'] ?? $e->getMessage(),
- 'HTTP_ERROR',
- $response ? $response->getStatusCode() : 0
- );
- }
- }
-
- public function health(): array
- {
- return $this->request('GET', '/health');
- }
-}
-```
+The entry class is `OpenWA\Client`. It validates that `baseUrl` and `apiKey` are present (throwing `OpenWAException` otherwise), constructs the shared HTTP transport, and exposes each resource as a public property: `$client->sessions`, `$client->messages`, `$client->contacts`, `$client->groups`, `$client->webhooks`, `$client->chats`, `$client->status`, `$client->health`, `$client->labels`, `$client->channels`, `$client->catalog`, `$client->templates`.
+
+Two escape hatches sit on the client itself:
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `auth` | `auth(): array` | `POST /api/auth/validate` — validate the configured key and resolve its role. |
+| `request` | `request(string $method, string $path, array $query = [], mixed $body = null): mixed` | Raw request against any path (advanced use); returns decoded JSON or `null` for empty/204. |
+
+### Client Configuration
+
+The constructor takes a single associative `$config` array:
+
+| Key | Type | Default | Description |
+| --- | --- | --- | --- |
+| `baseUrl` | `string` | — (**required**) | API base URL, e.g. `http://localhost:2785`. A trailing `/` is stripped; any path prefix (e.g. `/v1` behind a proxy) is preserved. |
+| `apiKey` | `string` | — (**required**) | Sent as the `X-API-Key` header on every request. |
+| `timeout` | `float` | `30.0` | Per-request timeout in seconds. |
+| `httpClient` | `?\GuzzleHttp\ClientInterface` | `null` | Inject a Guzzle client (e.g. one built on a `MockHandler`) for testing or middleware. When `null`, a default Guzzle client is created with the configured timeout. |
+| `defaultHeaders` | `array<string,string>` | `[]` | Extra headers applied on every request, **under** the SDK's auth/JSON headers (which always win). |
+
+Missing `baseUrl` or `apiKey` throws `OpenWA\Exceptions\OpenWAException` from the constructor.
+
+### Resources & Methods
+
+All payloads are associative arrays; all listed methods are synchronous and return the decoded JSON (an `array`), except the `void` deletes. Methods marked **OPERATOR** require an operator-level API key.
+
+#### `sessions`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(): array` | List all sessions. |
+| `get` | `get(string $id): array` | Get one session. |
+| `create` | `create(array $body): array` | Create a session (`$body['name']` required). |
+| `delete` | `delete(string $id): void` | Delete a session. |
+| `start` | `start(string $id): array` | Start a session. |
+| `stop` | `stop(string $id): array` | Stop a session. |
+| `forceKill` | `forceKill(string $id): array` | Force-kill a session. |
+| `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. |
+| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. |
+| `stats` | `stats(): array` | `GET /api/sessions/stats/overview`. |
+
+#### `messages`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId, array $query = []): array` | List stored messages. |
+| `sendText` | `sendText(string $sessionId, array $body): array` | Send a text message (`send-text`). |
+| `sendImage` | `sendImage(string $sessionId, array $body): array` | Send an image. |
+| `sendVideo` | `sendVideo(string $sessionId, array $body): array` | Send a video. |
+| `sendAudio` | `sendAudio(string $sessionId, array $body): array` | Send audio. |
+| `sendDocument` | `sendDocument(string $sessionId, array $body): array` | Send a document. |
+| `sendSticker` | `sendSticker(string $sessionId, array $body): array` | Send a sticker. |
+| `sendLocation` | `sendLocation(string $sessionId, array $body): array` | Send a location. |
+| `sendContact` | `sendContact(string $sessionId, array $body): array` | Send a contact card. |
+| `sendTemplate` | `sendTemplate(string $sessionId, array $body): array` | Send a stored template. |
+| `reply` | `reply(string $sessionId, array $body): array` | Reply to a message. |
+| `forward` | `forward(string $sessionId, array $body): array` | Forward a message. |
+| `react` | `react(string $sessionId, array $body): array` | React to a message. |
+| `delete` | `delete(string $sessionId, array $body): array` | Delete a message. |
+| `history` | `history(string $sessionId, string $chatId, array $query = []): array` | Fetch chat history. |
+| `reactions` | `reactions(string $sessionId, string $chatId, string $messageId): array` | List reactions on a message. |
+| `sendBulk` | `sendBulk(string $sessionId, array $body): array` | Enqueue a bulk send batch. |
+| `batchStatus` | `batchStatus(string $sessionId, string $batchId): array` | Get bulk batch status. |
+| `cancelBatch` | `cancelBatch(string $sessionId, string $batchId): array` | Cancel a bulk batch. **OPERATOR** |
+
+#### `contacts`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId, array $query = []): array` | List contacts. |
+| `get` | `get(string $sessionId, string $contactId): array` | Get one contact. |
+| `check` | `check(string $sessionId, string $number): array` | Check whether a number is on WhatsApp. |
+| `profilePicture` | `profilePicture(string $sessionId, string $contactId): array` | Get a contact's profile picture. |
+| `phone` | `phone(string $sessionId, string $contactId): array` | Resolve a contact's phone number. |
+| `block` | `block(string $sessionId, string $contactId): array` | Block a contact. **OPERATOR** |
+| `unblock` | `unblock(string $sessionId, string $contactId): array` | Unblock a contact. **OPERATOR** |
+
+#### `groups`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId, array $query = []): array` | List groups. |
+| `get` | `get(string $sessionId, string $groupId): array` | Get one group. |
+| `create` | `create(string $sessionId, array $body): array` | Create a group. **OPERATOR** |
+| `addParticipants` | `addParticipants(string $sessionId, string $groupId, array $participants): array` | Add participants. **OPERATOR** |
+| `removeParticipants` | `removeParticipants(string $sessionId, string $groupId, array $participants): array` | Remove participants. **OPERATOR** |
+| `promoteParticipants` | `promoteParticipants(string $sessionId, string $groupId, array $participants): array` | Promote to admin. **OPERATOR** |
+| `demoteParticipants` | `demoteParticipants(string $sessionId, string $groupId, array $participants): array` | Demote admins. **OPERATOR** |
+| `setSubject` | `setSubject(string $sessionId, string $groupId, string $subject): array` | Update the group subject. **OPERATOR** |
+| `setDescription` | `setDescription(string $sessionId, string $groupId, string $description): array` | Update the group description. **OPERATOR** |
+| `leave` | `leave(string $sessionId, string $groupId): array` | Leave the group. **OPERATOR** |
+| `inviteCode` | `inviteCode(string $sessionId, string $groupId): array` | Get the invite code. |
+| `revokeInviteCode` | `revokeInviteCode(string $sessionId, string $groupId): array` | Revoke and regenerate the invite code. **OPERATOR** |
+
+#### `chats`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId, array $query = []): array` | List chats. |
+| `markRead` | `markRead(string $sessionId, array $body): array` | Mark chat(s) read. **OPERATOR** |
+| `markUnread` | `markUnread(string $sessionId, array $body): array` | Mark chat(s) unread. **OPERATOR** |
+| `delete` | `delete(string $sessionId, array $body): array` | Delete chat(s). **OPERATOR** |
+| `sendState` | `sendState(string $sessionId, array $body): array` | Send a typing/recording state. **OPERATOR** |
+
+#### `webhooks`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId): array` | List webhooks. |
+| `get` | `get(string $sessionId, string $id): array` | Get one webhook. |
+| `create` | `create(string $sessionId, array $body): array` | Create a webhook. **OPERATOR** |
+| `update` | `update(string $sessionId, string $id, array $body): array` | Update a webhook. **OPERATOR** |
+| `delete` | `delete(string $sessionId, string $id): void` | Delete a webhook. **OPERATOR** |
+| `test` | `test(string $sessionId, string $id): array` | Send a test event. **OPERATOR** |
+
+#### `labels` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId): array` | List labels. |
+| `get` | `get(string $sessionId, string $labelId): array` | Get one label. |
+| `forChat` | `forChat(string $sessionId, string $chatId): array` | List labels applied to a chat. |
+| `addToChat` | `addToChat(string $sessionId, string $chatId, array $body): array` | Add a label to a chat (`$body` needs `labelId`). **OPERATOR** |
+| `removeFromChat` | `removeFromChat(string $sessionId, string $chatId, string $labelId): array` | Remove a label from a chat. **OPERATOR** |
+
+#### `channels` *(Newsletters)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId): array` | List channels. |
+| `get` | `get(string $sessionId, string $channelId): array` | Get one channel. |
+| `messages` | `messages(string $sessionId, string $channelId, array $query = []): array` | Recent channel messages. |
+| `subscribe` | `subscribe(string $sessionId, array $body): array` | Subscribe via invite code (`$body` needs `inviteCode`). **OPERATOR** |
+| `unsubscribe` | `unsubscribe(string $sessionId, string $channelId): array` | Unsubscribe from a channel. **OPERATOR** |
+
+#### `catalog` *(WhatsApp Business)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `info` | `info(string $sessionId): array` | Get catalog info. |
+| `products` | `products(string $sessionId, array $query = []): array` | List products (e.g. `['page' => 1, 'limit' => 20]`). |
+| `product` | `product(string $sessionId, string $productId): array` | Get one product. |
+| `sendProduct` | `sendProduct(string $sessionId, array $body): array` | Send a product message (`chatId` + `productId`). **OPERATOR** |
+| `sendCatalog` | `sendCatalog(string $sessionId, array $body): array` | Send a catalog link (`chatId`). **OPERATOR** |
+
+#### `status` *(Stories)*
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId): array` | List status updates. |
+| `fromContact` | `fromContact(string $sessionId, string $contactId): array` | Status updates from one contact. |
+| `sendText` | `sendText(string $sessionId, array $body): array` | Post a text status. **OPERATOR** |
+| `sendImage` | `sendImage(string $sessionId, array $body): array` | Post an image status. **OPERATOR** |
+| `sendVideo` | `sendVideo(string $sessionId, array $body): array` | Post a video status. **OPERATOR** |
+| `delete` | `delete(string $sessionId, string $statusId): void` | Delete a status. **OPERATOR** |
+
+#### `templates`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `list` | `list(string $sessionId): array` | List templates. |
+| `get` | `get(string $sessionId, string $templateId): array` | Get one template. |
+| `create` | `create(string $sessionId, array $body): array` | Create a template (`$body` needs `name` and `body`; `header`/`footer` optional). **OPERATOR** |
+| `update` | `update(string $sessionId, string $templateId, array $body): array` | Update a template. **OPERATOR** |
+| `delete` | `delete(string $sessionId, string $templateId): void` | Delete a template. **OPERATOR** |
+
+#### `health`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `check` | `check(): array` | `GET /api/health`. |
+| `live` | `live(): array` | Liveness probe. |
+| `ready` | `ready(): array` | Readiness probe. |
-```php
-<?php
-// src/Resources/Sessions.php
+### Error Handling
-namespace OpenWA\Resources;
+All exceptions live in `OpenWA\Exceptions` and descend from `OpenWAException` (which extends PHP's `\Exception`). Any non-2xx response is raised as an `OpenWAApiException`; the static `classify()` factory picks the most specific subclass by status code. An `OpenWAApiException` carries the HTTP status (`getStatus(): int`), the parsed error body (`getBody(): mixed`), and the NestJS `error` kind when present (`getErrorKind(): ?string`).
-use OpenWA\Client;
-use OpenWA\Models\Session;
-
-class Sessions
-{
- private Client $client;
-
- public function __construct(Client $client)
- {
- $this->client = $client;
- }
-
- public function list(array $params = []): array
- {
- $data = $this->client->request('GET', '/api/sessions', [
- 'query' => $params,
- ]);
-
- return array_map(fn($s) => new Session($s), $data);
- }
-
- public function create(array $input): Session
- {
- $data = $this->client->request('POST', '/api/sessions', [
- 'json' => $input,
- ]);
-
- return new Session($data);
- }
-
- public function get(string $id): Session
- {
- $data = $this->client->request('GET', "/api/sessions/{$id}");
- return new Session($data);
- }
-
- public function delete(string $id, bool $keepAuth = false): void
- {
- $this->client->request('DELETE', "/api/sessions/{$id}", [
- 'query' => ['keepAuth' => $keepAuth],
- ]);
- }
-
- public function getQr(string $id, string $format = 'base64'): array
- {
- return $this->client->request('GET', "/api/sessions/{$id}/qr", [
- 'query' => ['format' => $format],
- ]);
- }
-
- public function restart(string $id): Session
- {
- $data = $this->client->request('POST', "/api/sessions/{$id}/restart");
- return new Session($data);
- }
-
- public function logout(string $id): void
- {
- $this->client->request('POST', "/api/sessions/{$id}/logout");
- }
-}
-```
+| Exception | Extends | Trigger |
+| --- | --- | --- |
+| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). |
+| `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). |
+| `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |
+| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — insufficient role (e.g. operator-only endpoint). |
+| `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. |
+| `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). |
+| `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. |
+| `OpenWANotImplementedException` | `OpenWAApiException` | `501` — active engine does not support the operation. |
+| `OpenWATimeoutException` | `OpenWAException` | Request exceeded the timeout (`getTimeout(): float`). Not an API error — has no status/body. |
```php
<?php
-// src/Resources/Messages.php
-
-namespace OpenWA\Resources;
-
use OpenWA\Client;
-use OpenWA\Models\Message;
-
-class Messages
-{
- private Client $client;
-
- public function __construct(Client $client)
- {
- $this->client = $client;
- }
-
- public function send(string $sessionId, array $input): Message
- {
- $data = $this->client->request(
- 'POST',
- "/api/sessions/{$sessionId}/messages",
- ['json' => $input]
- );
-
- return new Message($data);
- }
-
- public function sendText(string $sessionId, string $phone, string $text): Message
- {
- return $this->send($sessionId, [
- 'phone' => $phone,
- 'type' => 'text',
- 'body' => $text,
- ]);
- }
-
- public function sendImage(
- string $sessionId,
- string $phone,
- string $url,
- ?string $caption = null
- ): Message {
- return $this->send($sessionId, [
- 'phone' => $phone,
- 'type' => 'image',
- 'media' => ['url' => $url],
- 'caption' => $caption,
- ]);
- }
-
- public function sendDocument(
- string $sessionId,
- string $phone,
- string $url,
- string $filename,
- ?string $caption = null
- ): Message {
- return $this->send($sessionId, [
- 'phone' => $phone,
- 'type' => 'document',
- 'media' => ['url' => $url, 'filename' => $filename],
- 'caption' => $caption,
- ]);
- }
-
- public function list(string $sessionId, string $phone, array $params = []): array
- {
- $data = $this->client->request(
- 'GET',
- "/api/sessions/{$sessionId}/messages",
- ['query' => array_merge(['phone' => $phone], $params)]
- );
-
- return array_map(fn($m) => new Message($m), $data);
- }
-
- public function delete(string $sessionId, string $messageId, bool $forEveryone = true): void
- {
- $this->client->request(
- 'DELETE',
- "/api/sessions/{$sessionId}/messages/{$messageId}",
- ['query' => ['forEveryone' => $forEveryone]]
- );
- }
+use OpenWA\Exceptions\OpenWAConflictException;
+use OpenWA\Exceptions\OpenWARateLimitException;
+use OpenWA\Exceptions\OpenWATimeoutException;
+use OpenWA\Exceptions\OpenWAApiException;
+
+try {
+ $result = $client->messages->sendText('my-session', [
+ 'chatId' => '[email protected]',
+ 'text' => 'Hello!',
+ ]);
+} catch (OpenWAConflictException $e) {
+ // 409 — engine not ready yet
+} catch (OpenWARateLimitException $e) {
+ // 429 — back off and retry yourself (no auto-retry)
+} catch (OpenWATimeoutException $e) {
+ fwrite(STDERR, "timed out after {$e->getTimeout()}s\n");
+} catch (OpenWAApiException $e) {
+ // any other non-2xx
+ fwrite(STDERR, "API {$e->getStatus()}: {$e->getMessage()}\n");
+ var_dump($e->getBody());
}
```
-## 18.5 n8n Community Node
+### Notable Behaviors
-### Installation
+- **Redirects are never followed.** Guzzle is configured with `allow_redirects => false`, so a `3xx` surfaces as an `OpenWAApiException` rather than being followed — the `X-API-Key` header is never re-sent to a redirect target.
+- **Auth/JSON headers take precedence.** `defaultHeaders` are merged in first, then `X-API-Key`, `Content-Type: application/json`, and `Accept: application/json` are applied on top, so they can't be clobbered.
+- **Path segments are percent-encoded.** Ids (chat/message/group ids, session names) pass through `encodeSegment()`, which `rawurlencode`s the value but keeps the WhatsApp-id-safe characters `@`, `:`, and `+` readable — so a value containing `/`, `#`, or `?` cannot break out of its path position.
+- **Base-URL path prefix is preserved.** The base URL has its trailing `/` trimmed and requests are issued against an absolute `baseUrl . $path`; Guzzle's `base_uri` is intentionally unset, so a prefix like `/v1` behind a reverse proxy is retained.
+- **Null query values are dropped.** Absent optional query parameters (`null`) are filtered out before the request, so they are never sent.
+- **No automatic retries.** A failed request throws immediately; wrap calls in your own backoff if you need retries (notably for `429`). The injectable `httpClient` is the extension point for retry/observability middleware.
+- **Empty/204 responses return `null`.** A `204` or empty body decodes to `null`; resource methods that promise an `array` coalesce this to `[]` (or to the resource object for single-item gets).
+- **Testing without the network.** Inject a Guzzle client built on a `GuzzleHttp\Handler\MockHandler` via the `httpClient` config key — no global state, no live calls. The shipped test suite asserts on the exact path, method, and body.
+- **PSR-4 autoloading.** Everything lives under the `OpenWA\` namespace mapped to `src/`; `composer require rmyndharis/openwa` wires up the autoloader.
-```bash
-npm install @rmyndharis/n8n-nodes-openwa
-```
+## 18.5 n8n Community Node
-### Node Configuration
+OpenWA's n8n integration is **not** part of these SDK packages. It is a separate community node maintained in its own repository, which speaks the same REST + webhook contract documented in [API Specification](./06-api-specification.md):
-```typescript
-// nodes/OpenWA/OpenWA.node.ts
-
-import { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow';
-
-export class OpenWA implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'OpenWA',
- name: 'openWA',
- icon: 'file:openwa.svg',
- group: ['transform'],
- version: 1,
- subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
- description: 'Send WhatsApp messages via OpenWA',
- defaults: {
- name: 'OpenWA',
- },
- inputs: ['main'],
- outputs: ['main'],
- credentials: [
- {
- name: 'openWAApi',
- required: true,
- },
- ],
- properties: [
- // Resource
- {
- displayName: 'Resource',
- name: 'resource',
- type: 'options',
- noDataExpression: true,
- options: [
- { name: 'Message', value: 'message' },
- { name: 'Session', value: 'session' },
- { name: 'Contact', value: 'contact' },
- { name: 'Group', value: 'group' },
- ],
- default: 'message',
- },
-
- // Message Operations
- {
- displayName: 'Operation',
- name: 'operation',
- type: 'options',
- noDataExpression: true,
- displayOptions: {
- show: { resource: ['message'] },
- },
- options: [
- { name: 'Send Text', value: 'sendText' },
- { name: 'Send Image', value: 'sendImage' },
- { name: 'Send Document', value: 'sendDocument' },
- { name: 'Send Location', value: 'sendLocation' },
- ],
- default: 'sendText',
- },
-
- // Session ID
- {
- displayName: 'Session ID',
- name: 'sessionId',
- type: 'string',
- default: 'default',
- required: true,
- description: 'The session ID to use',
- },
-
- // Phone Number
- {
- displayName: 'Phone Number',
- name: 'phone',
- type: 'string',
- default: '',
- required: true,
- displayOptions: {
- show: {
- resource: ['message'],
- },
- },
- description: 'Phone number (e.g., 628123456789)',
- },
-
- // Message Text
- {
- displayName: 'Message',
- name: 'message',
- type: 'string',
- typeOptions: {
- rows: 4,
- },
- default: '',
- displayOptions: {
- show: {
- resource: ['message'],
- operation: ['sendText'],
- },
- },
- description: 'The message text to send',
- },
-
- // Image URL
- {
- displayName: 'Image URL',
- name: 'imageUrl',
- type: 'string',
- default: '',
- displayOptions: {
- show: {
- resource: ['message'],
- operation: ['sendImage'],
- },
- },
- description: 'URL of the image to send',
- },
-
- // Caption
- {
- displayName: 'Caption',
- name: 'caption',
- type: 'string',
- default: '',
- displayOptions: {
- show: {
- resource: ['message'],
- operation: ['sendImage', 'sendDocument'],
- },
- },
- description: 'Caption for the media',
- },
- ],
- };
-
- async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
- const items = this.getInputData();
- const returnData: INodeExecutionData[] = [];
- const credentials = await this.getCredentials('openWAApi');
-
- const baseUrl = credentials.baseUrl as string;
- const apiKey = credentials.apiKey as string;
-
- for (let i = 0; i < items.length; i++) {
- const resource = this.getNodeParameter('resource', i) as string;
- const operation = this.getNodeParameter('operation', i) as string;
- const sessionId = this.getNodeParameter('sessionId', i) as string;
-
- let response;
-
- if (resource === 'message') {
- const phone = this.getNodeParameter('phone', i) as string;
- const formattedPhone = this.formatPhone(phone);
-
- if (operation === 'sendText') {
- const message = this.getNodeParameter('message', i) as string;
-
- response = await this.helpers.request({
- method: 'POST',
- url: `${baseUrl}/api/sessions/${sessionId}/messages`,
- headers: { 'X-API-Key': apiKey },
- body: {
- phone: formattedPhone,
- type: 'text',
- body: message,
- },
- json: true,
- });
- } else if (operation === 'sendImage') {
- const imageUrl = this.getNodeParameter('imageUrl', i) as string;
- const caption = this.getNodeParameter('caption', i) as string;
-
- response = await this.helpers.request({
- method: 'POST',
- url: `${baseUrl}/api/sessions/${sessionId}/messages`,
- headers: { 'X-API-Key': apiKey },
- body: {
- phone: formattedPhone,
- type: 'image',
- media: { url: imageUrl },
- caption,
- },
- json: true,
- });
- }
- }
-
- returnData.push({ json: response });
- }
-
- return [returnData];
- }
+- An **action/HTTP** path that calls the REST endpoints (e.g. `POST /api/sessions/:id/messages/send-text`) with the `X-API-Key` header.
+- A **trigger** path that registers a webhook (the `webhooks` resource) and receives inbound events, verifying the `X-OpenWA-Signature` HMAC.
- private formatPhone(phone: string): string {
- let cleaned = phone.replace(/\D/g, '');
- if (!cleaned.endsWith('@c.us')) {
- cleaned = `${cleaned}@c.us`;
- }
- return cleaned;
- }
-}
-```
+For installation and node-by-node configuration, see the dedicated [n8n Integration guide](./22-n8n-integration.md). Because the node consumes the public API contract, the verified route/event reference in docs 06 and §6.6 (Webhook Events) is the authority for what it can call and receive.
-### Trigger Node
+## 18.6 SDK Versioning & Releases
-```typescript
-// nodes/OpenWA/OpenWATrigger.node.ts
-
-import { IHookFunctions, IWebhookFunctions, INodeType, INodeTypeDescription, IWebhookResponseData } from 'n8n-workflow';
-
-export class OpenWATrigger implements INodeType {
- description: INodeTypeDescription = {
- displayName: 'OpenWA Trigger',
- name: 'openWATrigger',
- icon: 'file:openwa.svg',
- group: ['trigger'],
- version: 1,
- description: 'Starts workflow on OpenWA events',
- defaults: {
- name: 'OpenWA Trigger',
- },
- inputs: [],
- outputs: ['main'],
- credentials: [
- {
- name: 'openWAApi',
- required: true,
- },
- ],
- webhooks: [
- {
- name: 'default',
- httpMethod: 'POST',
- responseMode: 'onReceived',
- path: 'webhook',
- },
- ],
- properties: [
- {
- displayName: 'Events',
- name: 'events',
- type: 'multiOptions',
- options: [
- { name: 'Message Received', value: 'message.received' },
- { name: 'Message Acknowledged', value: 'message.ack' },
- { name: 'Session Status Change', value: 'session.status' },
- { name: 'QR Code Received', value: 'session.qr' },
- ],
- default: ['message.received'],
- required: true,
- },
- {
- displayName: 'Session Filter',
- name: 'sessionFilter',
- type: 'string',
- default: '',
- description: 'Only trigger for specific session (leave empty for all)',
- },
- ],
- };
-
- webhookMethods = {
- default: {
- async checkExists(this: IHookFunctions): Promise<boolean> {
- // Check if webhook already exists in OpenWA
- const webhookUrl = this.getNodeWebhookUrl('default');
- const credentials = await this.getCredentials('openWAApi');
-
- const sessionId = this.getNodeParameter('sessionFilter') as string;
- const response = await this.helpers.request({
- method: 'GET',
- url: `${credentials.baseUrl}/api/sessions/${sessionId}/webhooks`,
- headers: { 'X-API-Key': credentials.apiKey as string },
- json: true,
- });
-
- return response.some((w: any) => w.url === webhookUrl);
- },
-
- async create(this: IHookFunctions): Promise<boolean> {
- const webhookUrl = this.getNodeWebhookUrl('default');
- const events = this.getNodeParameter('events') as string[];
- const credentials = await this.getCredentials('openWAApi');
-
- const sessionId = this.getNodeParameter('sessionFilter') as string;
- await this.helpers.request({
- method: 'POST',
- url: `${credentials.baseUrl}/api/sessions/${sessionId}/webhooks`,
- headers: { 'X-API-Key': credentials.apiKey as string },
- body: {
- url: webhookUrl,
- events,
- },
- json: true,
- });
-
- return true;
- },
-
- async delete(this: IHookFunctions): Promise<boolean> {
- const webhookUrl = this.getNodeWebhookUrl('default');
- const credentials = await this.getCredentials('openWAApi');
-
- // Find and delete the webhook
- const sessionId = this.getNodeParameter('sessionFilter') as string;
- const response = await this.helpers.request({
- method: 'GET',
- url: `${credentials.baseUrl}/api/sessions/${sessionId}/webhooks`,
- headers: { 'X-API-Key': credentials.apiKey as string },
- json: true,
- });
-
- const webhook = response.find((w: any) => w.url === webhookUrl);
- if (webhook) {
- await this.helpers.request({
- method: 'DELETE',
- url: `${credentials.baseUrl}/api/sessions/${sessionId}/webhooks/${webhook.id}`,
- headers: { 'X-API-Key': credentials.apiKey as string },
- json: true,
- });
- }
-
- return true;
- },
- },
- };
-
- async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
- const body = this.getBodyData() as any;
-
- return {
- workflowData: [this.helpers.returnJsonArray(body)],
- };
- }
-}
-```
+### Versioning
-## 18.6 SDK Release & Versioning
+The three SDKs are versioned **independently of the gateway** and of each other, each following SemVer. They are currently published at `0.1.0` while the gateway is at `0.7.3`; an SDK version does **not** track the gateway version. Pin the SDK version your code is tested against and treat a major SDK bump as potentially breaking.
-### Version Strategy
+| SDK | Registry | Package |
+| --- | --- | --- |
+| JavaScript/TypeScript | npm | `@rmyndharis/openwa` |
+| Python | PyPI | `rmyndharis-openwa` |
+| PHP | Packagist | `rmyndharis/openwa` |
-SDK versions follow API versions:
+### Contract-drift protection
-```
-API v1.0.0 → SDK v1.0.x
-API v1.1.0 → SDK v1.1.x
-API v2.0.0 → SDK v2.0.x (breaking changes)
-```
+The wire types live in a dedicated module (`types.ts` / `types.py`) so they can later be regenerated by an OpenAPI codegen pass without touching the hand-written resource methods. Until then, each SDK's test suite mocks the HTTP transport and **asserts on the exact request path, method, and body** — so a drift between an SDK method and the real API (the class of bug that once shipped `messages/text` instead of the real `messages/send-text`) breaks a test rather than reaching users.
-### Release Checklist
-
-```markdown
-## SDK Release Checklist
-
-- [ ] Update version number in package.json/setup.py/composer.json
-- [ ] Update CHANGELOG
-- [ ] Run all tests
-- [ ] Generate/update API types from OpenAPI spec
-- [ ] Update documentation
-- [ ] Build distribution packages
-- [ ] Test installation in clean environment
-- [ ] Publish to package registry
-- [ ] Tag release in Git
-- [ ] Update examples repository
-```
-
----
-
-<div align="center">
+### Release process
-[← 17 - Dashboard Design](./17-dashboard-design.md) · [Documentation Index](./README.md) · [Next: 19 - Plugin Architecture →](./19-plugin-architecture.md)
+```bash
+# JavaScript
+cd sdk/javascript && npm test && npm run build && npm run smoke # smoke = require()+import() packaging check
+# Python
+cd sdk/python && python -m pytest -q
+# PHP
+cd sdk/php && composer install && ./vendor/bin/phpunit
+```
-</div>
+CI runs all three suites (path-filtered to `sdk/**`). The PHP package is mirrored to its own Packagist repository via a `git subtree split`, and that mirror publish is gated on the PHP tests passing, so a broken SDK cannot auto-publish. Bump the version, update the SDK's CHANGELOG, run the suite above, then tag/publish to the relevant registry.
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index e4d40efc6..8c67b141e 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -2,9 +2,10 @@
## Implementation Status
-> **Current Status: ⚠️ Partially Implemented**
+> **Current Status: ✅ Implemented**
>
-> The core plugin infrastructure is functional. Advanced features are planned for future releases.
+> The plugin runtime — loader, hook bus, capability facade, permission enforcement, per-session
+> activation, and a `worker_thread` sandbox for untrusted plugins — is shipped and wired.
| Component | Status | Location |
|-----------|--------|----------|
@@ -12,17 +13,19 @@
| **PluginLoaderService** | ✅ Implemented | `src/core/plugins/plugin-loader.service.ts` |
| **PluginStorageService** | ✅ Implemented | `src/core/plugins/plugin-storage.service.ts` |
| **Manifest loading** | ✅ Implemented | Loads from `plugins/` directory |
-| **Plugin lifecycle** | ✅ Implemented | load, enable, disable, unload |
+| **Plugin lifecycle** | ✅ Implemented | onLoad, onEnable, onDisable, onUnload, onConfigChange, healthCheck |
| **Dashboard UI** | ✅ Implemented | `dashboard/src/pages/Plugins.tsx` |
| **REST API** | ✅ Implemented | `src/modules/plugins/plugins.controller.ts` |
| Component | Status | Notes |
|-----------|--------|-------|
-| **@openwa/plugin-sdk** | 🔜 Planned | NPM package not yet published |
-| **Sandboxed execution** | 🔜 Planned | vm2 isolation not implemented |
-| **Permission enforcement** | ⚠️ Partial | Defined in manifest, not enforced |
-| **Built-in plugins** | ✅ Implemented | `auto-reply` + group auto-translation ship with v0.3.0, disabled by default |
-| **Plugin marketplace** | 🔜 Planned | Install from npm/github |
+| **Sandboxed execution** | ✅ Implemented | Untrusted (disk-loaded) plugins run in a `worker_thread`; see [23 — Plugin Sandboxing](./23-plugin-sandboxing.md). No `vm2`. |
+| **Permission enforcement** | ✅ Implemented | Capability permissions enforced at the call boundary via `assertPermission` |
+| **Per-session activation** | ✅ Implemented | A session-scoped plugin runs only for the sessions an operator activated it for |
+| **Per-session config** | ✅ Implemented | Per-session config overrides shallow-merged over the base config at hook time |
+| **Built-in plugins** | ✅ Implemented | The two engine adapters (`whatsapp-web.js`, `baileys`) register as in-process built-ins |
+| **Plugin install / catalog** | ✅ Implemented | Install a `.zip` by upload or URL, or from the remote catalog |
+| **@openwa/plugin-sdk** | 🔜 Planned | NPM package not yet published; plugins implement `IPlugin` directly today |
---
@@ -49,9 +52,9 @@ flowchart TB
end
```
-1. **Isolation** - _Planned, NOT enforced._ Plugins currently run in-process with full Node privileges (`require()`), guarded only by a path-containment check. **Load only trusted plugins** until sandboxed (vm2/worker) execution ships.
+1. **Isolation** - Untrusted plugins (anything loaded from the `plugins/` directory) run in a `worker_thread`, separate from in-process built-ins; capability calls round-trip to the host. First-party built-ins (the engine adapters) run in-process. A `worker_thread` is V8-context isolation in the same OS process, not an OS-level sandbox — see [23 — Plugin Sandboxing](./23-plugin-sandboxing.md) for what it does and does not guarantee, and the OS-containment guidance.
2. **Extensibility** - Easy to add new features
-3. **Safety** - Permission-based access control (planned; not yet enforced)
+3. **Safety** - Capability permissions are enforced at the call boundary (`assertPermission` throws `PluginCapabilityError`), session scope is enforced per call, and outbound HTTP is SSRF-guarded.
4. **Performance** - Lazy loading, minimal overhead
## 19.2 Plugin Types
@@ -105,297 +108,216 @@ plugins/
### Manifest File
+`id`, `name`, `version`, `type`, and `main` are required; the rest are optional. There is **no**
+`types` field and **no** version-compatibility (`min`/`maxVersion`) check — the loader does not gate on
+a host version. The config schema is the top-level `configSchema` (note: not nested under `config`).
+
```json
{
- "name": "my-awesome-plugin",
+ "id": "my-awesome-plugin",
+ "name": "My Awesome Plugin",
"version": "1.0.0",
+ "type": "extension",
"description": "An awesome plugin for OpenWA",
"author": "Your Name",
"license": "MIT",
"main": "dist/index.js",
- "types": "dist/index.d.ts",
- "openwa": {
- "minVersion": "0.3.0",
- "maxVersion": "2.0.0"
- },
+ "permissions": ["messages:send", "engine:read", "net:fetch"],
- "permissions": [
- "messages:read",
- "messages:write",
- "contacts:read",
- "storage:read",
- "storage:write",
- "http:outbound"
- ],
-
- "hooks": [
- "message:received",
- "message:sending",
- "session:connected",
- "webhook:before"
- ],
-
- "config": {
- "schema": {
- "type": "object",
- "properties": {
- "enabled": {
- "type": "boolean",
- "default": true
- },
- "apiKey": {
- "type": "string",
- "secret": true
- },
- "options": {
- "type": "object",
- "properties": {
- "autoReply": { "type": "boolean", "default": false },
- "language": { "type": "string", "default": "id" }
- }
- }
- }
+ "sessionScoped": true,
+ "sessions": ["*"],
+
+ "net": { "allow": ["api.example.com"] },
+
+ "hooks": ["message:received", "message:sending"],
+
+ "provides": ["greeter"],
+ "requires": [],
+
+ "configSchema": {
+ "type": "object",
+ "properties": {
+ "greeting": { "type": "string", "title": "Greeting", "default": "Hello" },
+ "apiKey": { "type": "string", "title": "API key", "secret": true }
}
+ },
+
+ "configUi": { "entry": "config-ui.html", "height": 480 },
+
+ "i18n": {
+ "es": { "name": "Mi complemento", "config": { "greeting": { "title": "Saludo" } } }
}
}
```
+| Field | Required | Meaning |
+|-------|----------|---------|
+| `id` | ✅ | Unique identifier (also the plugin's on-disk directory name) |
+| `name` | ✅ | Display name |
+| `version` | ✅ | Semver |
+| `type` | ✅ | One of `engine`, `storage`, `queue`, `auth`, `extension` |
+| `main` | ✅ | Entry file, resolved **inside** the plugin directory (a path that escapes it is rejected) |
+| `permissions` | — | Capability permissions this plugin declares; absent/empty = no capability access |
+| `sessions` | — | Session ids this plugin may act on, or `['*']`. Absent = `['*']`. Static — editing config can't widen it |
+| `sessionScoped` | — | Default `true`. A scoped plugin only sees events for the sessions it's activated for; `false` = always runs |
+| `net.allow` | — | Outbound-HTTP host allowlist for `ctx.net.fetch` (`host`, `host:port`, or `'*'`). Absent = deny all |
+| `configSchema` | — | Declarative config schema the dashboard renders into a form |
+| `configUi` | — | Optional self-contained HTML config editor served into a sandboxed iframe (preferred over `configSchema` when present) |
+| `hooks` | — | Hook events this plugin listens to (informational) |
+| `provides` / `requires` | — | Features this plugin provides / depends on |
+| `i18n` | — | Localized dashboard text per locale (dashboard-only) |
+
+A `configSchema` field may set `secret: true` (e.g. an API key): the value is masked on read and
+preserved on an unchanged write.
+
### Plugin Entry Point
+A plugin's `main` module **default-exports a class** that implements `IPlugin`. All lifecycle methods
+are optional and each receives only the `PluginContext` — there is no second `config` argument; config
+is read from `ctx.config`.
+
```typescript
// plugins/my-plugin/index.ts
-import { OpenWAPlugin, PluginContext, MessageEvent, HookResult } from '@openwa/plugin-sdk';
+import type { IPlugin, PluginContext } from '@openwa/plugin-sdk'; // shape only; implement IPlugin
-export interface MyPluginConfig {
- enabled: boolean;
- apiKey: string;
- options: {
- autoReply: boolean;
- language: string;
- };
+interface MyPluginConfig {
+ greeting: string;
+ apiKey?: string;
}
-export default class MyAwesomePlugin implements OpenWAPlugin<MyPluginConfig> {
- name = 'my-awesome-plugin';
- version = '1.0.0';
-
- private ctx!: PluginContext;
- private config!: MyPluginConfig;
-
- /**
- * Called when plugin is loaded
- */
- async onLoad(ctx: PluginContext, config: MyPluginConfig): Promise<void> {
- this.ctx = ctx;
- this.config = config;
-
- ctx.logger.info('Plugin loaded', { version: this.version });
+export default class MyAwesomePlugin implements IPlugin {
+ async onLoad(ctx: PluginContext): Promise<void> {
+ ctx.logger.log('Plugin loaded', { version: ctx.manifest.version });
- // Register message handler
- ctx.hooks.on('message:received', this.handleIncomingMessage.bind(this));
+ // Register a hook handler. Handlers receive a HookContext and return a HookResult.
+ ctx.registerHook('message:received', async hookCtx => {
+ const cfg = ctx.config as MyPluginConfig; // per-session-merged config for this event
+ const { sessionId, data } = hookCtx;
+ const message = data as { from: string; body?: string };
- // Register API routes (optional)
- ctx.router.get('/my-plugin/status', this.getStatus.bind(this));
- ctx.router.post('/my-plugin/action', this.doAction.bind(this));
- }
-
- /**
- * Called when plugin is unloaded
- */
- async onUnload(): Promise<void> {
- this.ctx.logger.info('Plugin unloading');
- // Cleanup resources
- }
-
- /**
- * Handle incoming message
- */
- async handleIncomingMessage(event: MessageEvent): Promise<HookResult> {
- if (!this.config.enabled) {
+ if (message.body?.toLowerCase() === 'help' && sessionId) {
+ // Capability call — requires the 'messages:send' permission + an in-scope, live session.
+ await ctx.messages.sendText(sessionId, message.from, cfg.greeting ?? 'How can I help you?');
+ return { continue: false }; // stop the chain
+ }
return { continue: true };
- }
-
- const { message, session } = event;
-
- // Example: Auto-reply to specific keyword
- if (this.config.options.autoReply && message.body?.toLowerCase() === 'help') {
- await this.ctx.api.messages.send(session.id, {
- phone: message.from,
- type: 'text',
- body: 'How can I help you?',
- });
-
- // Stop processing (don't trigger webhook)
- return { continue: false };
- }
-
- // Continue to next handler/webhook
- return { continue: true };
+ });
}
- /**
- * Custom API endpoint
- */
- async getStatus(req: Request, res: Response): Promise<void> {
- res.json({
- plugin: this.name,
- version: this.version,
- enabled: this.config.enabled,
- stats: await this.getStats(),
- });
+ async onEnable(_ctx: PluginContext): Promise<void> {}
+ async onDisable(_ctx: PluginContext): Promise<void> {}
+ async onUnload(ctx: PluginContext): Promise<void> {
+ ctx.logger.log('Plugin unloading');
}
- async doAction(req: Request, res: Response): Promise<void> {
- // Perform action
- res.json({ success: true });
+ async onConfigChange(ctx: PluginContext, newConfig: Record<string, unknown>): Promise<void> {
+ ctx.logger.log('Config changed', { keys: Object.keys(newConfig) });
}
- private async getStats(): Promise<object> {
- // Get plugin stats from storage
- return this.ctx.storage.get('stats') || {};
+ async healthCheck(): Promise<{ healthy: boolean; message?: string }> {
+ return { healthy: true };
}
}
```
## 19.4 Plugin SDK
+> Plugins implement the `IPlugin` interface directly. An `@openwa/plugin-sdk` npm package is planned
+> but not yet published; the interfaces below are the live runtime contract from
+> `src/core/plugins/plugin.interfaces.ts`.
+
### Core Interfaces
```typescript
-// @openwa/plugin-sdk/types.ts
-
-export interface OpenWAPlugin<TConfig = any> {
- name: string;
- version: string;
-
- onLoad(ctx: PluginContext, config: TConfig): Promise<void>;
- onUnload(): Promise<void>;
+// src/core/plugins/plugin.interfaces.ts
+
+export interface IPlugin {
+ // All optional; each receives only the PluginContext.
+ onLoad?: (context: PluginContext) => Promise<void>;
+ onEnable?: (context: PluginContext) => Promise<void>;
+ onDisable?: (context: PluginContext) => Promise<void>;
+ onUnload?: (context: PluginContext) => Promise<void>;
+ onConfigChange?: (context: PluginContext, newConfig: Record<string, unknown>) => Promise<void>;
+ healthCheck?: () => Promise<{ healthy: boolean; message?: string }>;
}
export interface PluginContext {
- // Logging
- logger: Logger;
-
- // Hook registration
- hooks: HookRegistry;
-
- // API access (permission-based)
- api: PluginAPI;
+ pluginId: string;
+ manifest: PluginManifest;
- // Plugin storage
- storage: PluginStorage;
+ // Effective config for the firing session (per-session override merged over the base). A getter,
+ // so it reflects live config edits; outside a hook it returns the base config.
+ config: Record<string, unknown>;
- // HTTP router for custom endpoints
- router: PluginRouter;
+ hookManager: HookManager;
+ logger: PluginLogger; // log / debug / warn / error
+ storage: PluginStorage; // get / set / delete / list — scoped to this plugin
- // Configuration
- config: ConfigService;
+ // Register a hook handler (optionally with a priority; lower runs first).
+ registerHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;
- // Event emitter
- events: EventEmitter;
+ // Capability facade (permission- + scope-checked on each call):
+ messages: PluginMessagingCapability; // requires 'messages:send'
+ engine: PluginEngineReadCapability; // requires 'engine:read' (read-only)
+ net: PluginNetCapability; // requires 'net:fetch' (SSRF-guarded, net.allow-scoped)
}
-export interface Logger {
- debug(message: string, meta?: object): void;
- info(message: string, meta?: object): void;
- warn(message: string, meta?: object): void;
- error(message: string, meta?: object): void;
+export interface PluginLogger {
+ log(message: string, meta?: Record<string, unknown>): void;
+ debug(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+ error(message: string, error?: unknown, meta?: Record<string, unknown>): void;
}
+```
-export interface HookRegistry {
- on(event: HookEvent, handler: HookHandler): void;
- off(event: HookEvent, handler: HookHandler): void;
- once(event: HookEvent, handler: HookHandler): void;
-}
+There is **no** `ctx.api`, `ctx.router`, or `ctx.events` — plugins do not mount HTTP routes or get an
+event emitter. Hook handlers use the host `HookContext` / `HookResult` shape (see §19.5), not a
+`{ continue, modified }` shape.
-export type HookEvent =
- | 'message:received'
- | 'message:sending'
- | 'message:sent'
- | 'message:failed'
- | 'session:created'
- | 'session:connected'
- | 'session:disconnected'
- | 'session:deleted'
- | 'webhook:before'
- | 'webhook:after'
- | 'webhook:error';
+### Capability facade
-export type HookHandler<T = any> = (event: T) => Promise<HookResult>;
+A plugin reaches WhatsApp, the engine, and the network **only** through these three namespaces. Each
+call is gated by the matching declared permission (and, for `messages`/`engine`, the session scope) —
+a missing grant throws a `PluginCapabilityError`.
-export interface HookResult {
- continue: boolean; // Whether to continue to next handler
- modified?: any; // Modified event data
- error?: Error; // Error to stop processing
+```typescript
+// ctx.messages — requires 'messages:send'. Routes through MessageService (persistence preserved).
+export interface PluginMessagingCapability {
+ sendText(sessionId: string, chatId: string, text: string): Promise<MessageResponseDto>;
+ reply(sessionId: string, chatId: string, quotedMessageId: string, text: string): Promise<MessageResponseDto>;
}
-```
-### Plugin API
+// ctx.engine — requires 'engine:read'. Read-only, scoped engine queries.
+export interface PluginEngineReadCapability {
+ getGroupInfo(sessionId: string, groupId: string): Promise<...>;
+ getContacts(sessionId: string): Promise<...>;
+ getContactById(sessionId: string, contactId: string): Promise<...>;
+ checkNumberExists(sessionId: string, phone: string): Promise<...>;
+ getChats(sessionId: string): Promise<...>;
+}
-```typescript
-// @openwa/plugin-sdk/api.ts
-
-export interface PluginAPI {
- // Sessions (requires: sessions:read/write)
- sessions: {
- list(): Promise<Session[]>;
- get(id: string): Promise<Session>;
- getStatus(id: string): Promise<SessionStatus>;
- };
-
- // Messages (requires: messages:read/write)
- messages: {
- send(sessionId: string, input: SendMessageInput): Promise<Message>;
- get(sessionId: string, messageId: string): Promise<Message>;
- list(sessionId: string, phone: string): Promise<Message[]>;
- };
-
- // Contacts (requires: contacts:read/write)
- contacts: {
- list(sessionId: string): Promise<Contact[]>;
- get(sessionId: string, phone: string): Promise<Contact>;
- exists(sessionId: string, phone: string): Promise<boolean>;
- };
-
- // Groups (requires: groups:read/write)
- groups: {
- list(sessionId: string): Promise<Group[]>;
- get(sessionId: string, groupId: string): Promise<Group>;
- getParticipants(sessionId: string, groupId: string): Promise<Participant[]>;
- };
-
- // HTTP (requires: http:outbound)
- http: {
- get(url: string, options?: HttpOptions): Promise<HttpResponse>;
- post(url: string, body: any, options?: HttpOptions): Promise<HttpResponse>;
- put(url: string, body: any, options?: HttpOptions): Promise<HttpResponse>;
- delete(url: string, options?: HttpOptions): Promise<HttpResponse>;
- };
+// ctx.net — requires 'net:fetch'. Always through the host SSRF guard, scoped to manifest net.allow.
+export interface PluginNetCapability {
+ fetch(url: string, init?: PluginNetRequestInit): Promise<PluginNetResponse>;
}
```
+`ctx.net.fetch` returns a serializable response (`{ ok, status, statusText, headers, body }`, body as
+a string) — no streaming and no live `Response` object, because it must cross the worker boundary via
+structured clone. The request has a default 15 s / hard-cap 30 s timeout and a 10 MB response cap.
+
### Plugin Storage
```typescript
-// @openwa/plugin-sdk/storage.ts
-
+// Key-value storage, scoped to the plugin (values cross structuredClone, so keep them serializable).
export interface PluginStorage {
- // Key-value storage (scoped to plugin)
- get<T = any>(key: string): Promise<T | null>;
- set<T = any>(key: string, value: T, ttl?: number): Promise<void>;
+ get<T = unknown>(key: string): Promise<T | null>;
+ set<T = unknown>(key: string, value: T): Promise<void>;
delete(key: string): Promise<void>;
- has(key: string): Promise<boolean>;
-
- // List operations
- keys(pattern?: string): Promise<string[]>;
- clear(): Promise<void>;
-
- // Atomic operations
- increment(key: string, by?: number): Promise<number>;
- decrement(key: string, by?: number): Promise<number>;
+ list(prefix?: string): Promise<string[]>;
}
```
@@ -413,707 +335,265 @@ sequenceDiagram
Core->>HM: Message Received
HM->>P1: message:received
- P1->>HM: {continue: true, modified: msg}
- HM->>P2: message:received (modified)
+ P1->>HM: {continue: true, data: msg}
+ HM->>P2: message:received (with P1's data)
P2->>HM: {continue: true}
HM->>Core: Continue processing
Core->>WH: Deliver webhook
```
-### Hook Implementation
-
-```typescript
-// src/core/hooks/hook-manager.ts
-
-export class HookManager {
- private hooks: Map<HookEvent, HookHandler[]> = new Map();
- private pluginHooks: Map<string, Map<HookEvent, HookHandler[]>> = new Map();
-
- /**
- * Register hook handler for a plugin
- */
- register(pluginId: string, event: HookEvent, handler: HookHandler): void {
- // Get plugin's hooks map
- if (!this.pluginHooks.has(pluginId)) {
- this.pluginHooks.set(pluginId, new Map());
- }
-
- const pluginMap = this.pluginHooks.get(pluginId)!;
- if (!pluginMap.has(event)) {
- pluginMap.set(event, []);
- }
-
- pluginMap.get(event)!.push(handler);
+A handler returns `{ continue: false }` to stop the chain. To transform the event it returns
+`{ continue: true, data: <new value> }`; the next handler (and the host) sees that `data`. (There is
+no `modified` field — the result type uses `data`.)
- // Add to global hooks
- if (!this.hooks.has(event)) {
- this.hooks.set(event, []);
- }
- this.hooks.get(event)!.push(handler);
- }
-
- /**
- * Unregister all hooks for a plugin
- */
- unregisterPlugin(pluginId: string): void {
- const pluginMap = this.pluginHooks.get(pluginId);
- if (!pluginMap) return;
-
- // Remove from global hooks
- for (const [event, handlers] of pluginMap.entries()) {
- const globalHandlers = this.hooks.get(event);
- if (globalHandlers) {
- const filtered = globalHandlers.filter(h => !handlers.includes(h));
- this.hooks.set(event, filtered);
- }
- }
-
- this.pluginHooks.delete(pluginId);
- }
-
- /**
- * Execute hooks for an event
- */
- async execute<T>(event: HookEvent, data: T): Promise<HookExecutionResult<T>> {
- const handlers = this.hooks.get(event) || [];
- let currentData = data;
- let shouldContinue = true;
-
- for (const handler of handlers) {
- try {
- const result = await handler(currentData);
-
- if (result.modified) {
- currentData = result.modified;
- }
-
- if (!result.continue) {
- shouldContinue = false;
- break;
- }
-
- if (result.error) {
- throw result.error;
- }
- } catch (error) {
- // Log error but continue to next handler
- console.error(`Hook handler error for ${event}:`, error);
- }
- }
-
- return {
- data: currentData,
- shouldContinue,
- handlersExecuted: handlers.length,
- };
- }
-}
-
-export interface HookExecutionResult<T> {
- data: T;
- shouldContinue: boolean;
- handlersExecuted: number;
-}
-```
-
-## 19.6 Plugin Loader
+### Hook events
```typescript
-// src/core/plugins/plugin-loader.ts
-
-import { OpenWAPlugin, PluginContext, PluginManifest } from './types';
-import { HookManager } from '../hooks/hook-manager';
-import { PluginSandbox } from './plugin-sandbox';
-import { PluginStorageImpl } from './plugin-storage';
-import { PluginAPIImpl } from './plugin-api';
-
-export class PluginLoader {
- private plugins: Map<string, LoadedPlugin> = new Map();
- private hookManager: HookManager;
-
- constructor(
- private pluginDir: string,
- hookManager: HookManager,
- ) {
- this.hookManager = hookManager;
- }
-
- /**
- * Discover and load all plugins
- */
- async loadAll(): Promise<void> {
- const pluginDirs = await this.discoverPlugins();
-
- for (const dir of pluginDirs) {
- try {
- await this.load(dir);
- } catch (error) {
- console.error(`Failed to load plugin from ${dir}:`, error);
- }
- }
- }
-
- /**
- * Load a single plugin
- */
- async load(pluginPath: string): Promise<void> {
- // 1. Read manifest
- const manifest = await this.readManifest(pluginPath);
-
- // 2. Validate manifest
- this.validateManifest(manifest);
-
- // 3. Check version compatibility
- this.checkVersionCompatibility(manifest);
-
- // 4. Check permissions
- await this.checkPermissions(manifest);
-
- // 5. Load plugin module
- const PluginClass = await this.loadModule(pluginPath, manifest);
-
- // 6. Create plugin instance
- const plugin = new PluginClass();
-
- // 7. Create plugin context
- const ctx = this.createContext(manifest);
-
- // 8. Load configuration
- const config = await this.loadConfig(manifest);
+// src/core/hooks/hook.interfaces.ts
- // 9. Initialize plugin
- await plugin.onLoad(ctx, config);
-
- // 10. Store loaded plugin
- this.plugins.set(manifest.name, {
- instance: plugin,
- manifest,
- context: ctx,
- config,
- });
-
- console.log(`Plugin loaded: ${manifest.name}@${manifest.version}`);
- }
-
- /**
- * Unload a plugin
- */
- async unload(pluginName: string): Promise<void> {
- const loaded = this.plugins.get(pluginName);
- if (!loaded) return;
-
- // Call plugin cleanup
- await loaded.instance.onUnload();
-
- // Unregister hooks
- this.hookManager.unregisterPlugin(pluginName);
-
- // Remove from loaded plugins
- this.plugins.delete(pluginName);
-
- console.log(`Plugin unloaded: ${pluginName}`);
- }
-
- /**
- * Reload a plugin
- */
- async reload(pluginName: string): Promise<void> {
- const loaded = this.plugins.get(pluginName);
- if (!loaded) {
- throw new Error(`Plugin ${pluginName} not loaded`);
- }
-
- const pluginPath = loaded.manifest._path;
- await this.unload(pluginName);
- await this.load(pluginPath);
- }
-
- /**
- * Create plugin context with permissions
- */
- private createContext(manifest: PluginManifest): PluginContext {
- const permissions = new Set(manifest.permissions);
-
- return {
- logger: this.createLogger(manifest.name),
- hooks: this.createHookRegistry(manifest.name),
- api: new PluginAPIImpl(permissions),
- storage: new PluginStorageImpl(manifest.name),
- router: this.createRouter(manifest.name),
- config: this.createConfigService(manifest),
- events: this.createEventEmitter(manifest.name),
- };
- }
-
- private createHookRegistry(pluginId: string) {
- return {
- on: (event: HookEvent, handler: HookHandler) => {
- this.hookManager.register(pluginId, event, handler);
- },
- off: (event: HookEvent, handler: HookHandler) => {
- // Implementation
- },
- once: (event: HookEvent, handler: HookHandler) => {
- // Implementation
- },
- };
- }
-
- private async discoverPlugins(): Promise<string[]> {
- const fs = require('fs').promises;
- const path = require('path');
-
- const entries = await fs.readdir(this.pluginDir, { withFileTypes: true });
- const dirs = entries
- .filter((e: any) => e.isDirectory())
- .map((e: any) => path.join(this.pluginDir, e.name));
-
- return dirs.filter(async (dir: string) => {
- try {
- await fs.access(path.join(dir, 'manifest.json'));
- return true;
- } catch {
- return false;
- }
- });
- }
-
- // ... other helper methods
-}
-
-interface LoadedPlugin {
- instance: OpenWAPlugin;
- manifest: PluginManifest;
- context: PluginContext;
- config: any;
-}
+export type HookEvent =
+ // Session lifecycle
+ | 'session:created'
+ | 'session:starting'
+ | 'session:ready'
+ | 'session:qr'
+ | 'session:disconnected'
+ | 'session:error'
+ | 'session:deleted'
+ // Message lifecycle
+ | 'message:received'
+ | 'message:sending'
+ | 'message:sent'
+ | 'message:failed'
+ | 'message:ack'
+ // Webhook lifecycle
+ | 'webhook:before'
+ | 'webhook:queued'
+ | 'webhook:delivered'
+ | 'webhook:after'
+ | 'webhook:error';
```
-## 19.7 Built-in Plugins
-
-### Auto-Reply Plugin
+### Hook context and result
```typescript
-// plugins/auto-reply/index.ts
-
-import { OpenWAPlugin, PluginContext, MessageEvent } from '@openwa/plugin-sdk';
-
-interface AutoReplyConfig {
- enabled: boolean;
- rules: AutoReplyRule[];
- defaultReply?: string;
+export interface HookContext<T = unknown> {
+ event: HookEvent;
+ data: T; // the event payload (mutate via the returned HookResult.data)
+ sessionId?: string; // the session the event belongs to (used for activation + capability scope)
+ timestamp: Date;
+ source: string; // which service emitted this
}
-interface AutoReplyRule {
- trigger: string | RegExp;
- reply: string;
- caseSensitive?: boolean;
- matchType: 'exact' | 'contains' | 'regex' | 'startsWith';
+export interface HookResult<T = unknown> {
+ continue: boolean; // false = stop the chain
+ data?: T; // replacement payload for the next handler (only applied when error is absent)
+ error?: Error; // an error to propagate; the handler's data mutation is discarded
}
-export default class AutoReplyPlugin implements OpenWAPlugin<AutoReplyConfig> {
- name = 'auto-reply';
- version = '1.0.0';
-
- private ctx!: PluginContext;
- private config!: AutoReplyConfig;
- private compiledRules: CompiledRule[] = [];
-
- async onLoad(ctx: PluginContext, config: AutoReplyConfig): Promise<void> {
- this.ctx = ctx;
- this.config = config;
-
- // Compile rules for faster matching
- this.compiledRules = this.compileRules(config.rules);
-
- // Register hook
- ctx.hooks.on('message:received', this.handleMessage.bind(this));
-
- ctx.logger.info('Auto-reply plugin loaded', {
- rulesCount: this.compiledRules.length,
- });
- }
-
- async onUnload(): Promise<void> {
- this.ctx.logger.info('Auto-reply plugin unloaded');
- }
-
- private compileRules(rules: AutoReplyRule[]): CompiledRule[] {
- return rules.map(rule => ({
- ...rule,
- matcher: this.createMatcher(rule),
- }));
- }
-
- private createMatcher(rule: AutoReplyRule): (text: string) => boolean {
- const trigger = rule.caseSensitive ? rule.trigger : String(rule.trigger).toLowerCase();
-
- switch (rule.matchType) {
- case 'exact':
- return (text) => text === trigger;
- case 'contains':
- return (text) => text.includes(trigger as string);
- case 'startsWith':
- return (text) => text.startsWith(trigger as string);
- case 'regex':
- const regex = new RegExp(trigger as string, rule.caseSensitive ? '' : 'i');
- return (text) => regex.test(text);
- default:
- return () => false;
- }
- }
-
- async handleMessage(event: MessageEvent): Promise<HookResult> {
- if (!this.config.enabled) {
- return { continue: true };
- }
+export type HookHandler<T = unknown> = (ctx: HookContext<T>) => Promise<HookResult<T>>;
+```
- const { message, session } = event;
- const text = this.config.rules[0]?.caseSensitive
- ? message.body || ''
- : (message.body || '').toLowerCase();
+### Hook Manager behavior
- // Find matching rule
- const matchedRule = this.compiledRules.find(rule => rule.matcher(text));
+`HookManager` (`src/core/hooks/hook-manager.service.ts`) is a NestJS provider. Handlers are stored per
+event and run in **priority order** (lower `priority` first; default `100`). On `execute(event, data,
+{ sessionId, source })` it walks the chain, threading each handler's returned `data` into the next; a
+handler that returns `{ continue: false }` stops the chain. A handler that **throws** is logged and the
+chain continues with the previous data (one bad plugin can't break the chain). Same-event re-entrancy
+is blocked: a handler that re-fires the event it is handling is short-circuited (guards synchronous
+re-entry only). Plugins never call `HookManager` directly — they use `ctx.registerHook(...)`, which
+also applies the per-session activation gate.
- if (matchedRule) {
- await this.sendReply(session.id, message.from, matchedRule.reply);
+## 19.6 Plugin Loader
- // Track stats
- await this.ctx.storage.increment('stats:replies');
+`PluginLoaderService` (`src/core/plugins/plugin-loader.service.ts`) is the NestJS provider that
+discovers, loads, and runs plugins.
+
+**Discovery & load.** On `onModuleInit` it registers built-in plugins programmatically (the engine
+adapters; see §19.7), then scans the plugins directory (`plugins.dir`, default `./plugins`). For each
+sub-directory with a `manifest.json` it reads the manifest, validates the required fields
+(`id`/`name`/`version`/`type`/`main`), and records an `INSTALLED` plugin plus a persisted registry
+entry — **without running any plugin code**. Persisted config and per-session activation/config are
+read back so an operator's choices survive a restart. There is **no** version-compatibility check.
+
+> Loading a plugin from disk never auto-enables it. A previously-enabled plugin returns as `INSTALLED`
+> after a restart and must be re-enabled — enabling is always an explicit ADMIN action.
+
+**Enable.** `enablePlugin(id)` runs the lifecycle by trust tier (a synchronous lock prevents a racing
+double-enable, and engines must match the configured active engine):
+
+- **Built-in (trusted)** → `enableInProcess`: `require()` the `main` module (path-contained to the
+ plugin dir), instantiate the default-exported class, and run `onLoad` then `onEnable` in-process with
+ the live capability context.
+- **Untrusted (disk-loaded)** → `enableSandboxed`: spawn a `worker_thread`, load the module there, and
+ drive `onLoad`/`onEnable` over the channel. Capability calls and hook dispatches round-trip to the
+ host, which runs the **same** permission + session-scope checks. Lifecycle calls are bounded by a
+ 30 s timeout and hooks by a 5 s timeout; a failure tears the worker back down. See
+ [23 — Plugin Sandboxing](./23-plugin-sandboxing.md).
+
+**Disable / unload / uninstall.** `disablePlugin` runs `onDisable` (force-terminating the worker for a
+sandboxed plugin, even if `onDisable` hangs or throws) and unregisters the plugin's hooks. `onModuleDestroy`
+disables every enabled plugin on graceful shutdown so stateful plugins can flush. `uninstallPlugin`
+disables + unloads, drops the registry entry, and deletes the plugin's directory (built-ins are
+protected and cannot be uninstalled).
+
+**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger, plugin-scoped
+storage, `registerHook` (wrapped with the per-session activation gate), the live `config` getter, and
+the permission-checked `messages` / `engine` / `net` capabilities. The capability methods call
+`assertPermission` (and, for messages/engine, `resolveEngine` → `assertSessionAllowed`) before doing any
+work, so a missing grant or out-of-scope session fails fast with a `PluginCapabilityError`.
- return { continue: true }; // Still trigger webhook
- }
+## 19.7 Built-in Plugins
- // Default reply if configured
- if (this.config.defaultReply) {
- await this.sendReply(session.id, message.from, this.config.defaultReply);
- }
+The only plugins **shipped** as built-ins are the two WhatsApp **engine adapters**, registered
+programmatically (not loaded from disk) by `EngineFactory` via `registerBuiltInPlugin`:
- return { continue: true };
- }
+| Plugin id | Type | Notes |
+|-----------|------|-------|
+| `whatsapp-web.js` | `engine` | Default engine adapter (browser-based) |
+| `baileys` | `engine` | WebSocket engine adapter (no browser) |
- private async sendReply(sessionId: string, to: string, reply: string): Promise<void> {
- await this.ctx.api.messages.send(sessionId, {
- phone: to,
- type: 'text',
- body: reply,
- });
- }
-}
+Engines are mutually exclusive: the active one is pinned by `engine.type` config, and `enablePlugin`
+rejects any engine that is not the configured active one. Built-ins run **in-process** (trusted) — they
+are not sandboxed. There is no `auto-reply` / `translation` plugin bundled in the source tree today.
-interface CompiledRule extends AutoReplyRule {
- matcher: (text: string) => boolean;
-}
-```
+### Example: a hook-based message plugin
-### Translation Plugin
+A disk-installed extension implements `IPlugin`, registers hooks in `onLoad`, and uses the capability
+facade. This auto-reply sketch needs only `messages:send` in its manifest `permissions`:
```typescript
-// plugins/translation/index.ts
-
-import { OpenWAPlugin, PluginContext, MessageEvent } from '@openwa/plugin-sdk';
+// plugins/auto-reply/index.ts
+import type { IPlugin, PluginContext } from '@openwa/plugin-sdk'; // shape only; implement IPlugin
-interface TranslationConfig {
- enabled: boolean;
- provider: 'google' | 'deepl' | 'libre';
- apiKey?: string;
- sourceLanguage: 'auto' | string;
- targetLanguage: string;
- translateIncoming: boolean;
- translateOutgoing: boolean;
+interface AutoReplyConfig {
+ enabled?: boolean;
+ rules?: { match: string; reply: string }[];
}
-export default class TranslationPlugin implements OpenWAPlugin<TranslationConfig> {
- name = 'translation';
- version = '1.0.0';
-
- private ctx!: PluginContext;
- private config!: TranslationConfig;
-
- async onLoad(ctx: PluginContext, config: TranslationConfig): Promise<void> {
- this.ctx = ctx;
- this.config = config;
-
- if (config.translateIncoming) {
- ctx.hooks.on('message:received', this.translateIncoming.bind(this));
- }
-
- if (config.translateOutgoing) {
- ctx.hooks.on('message:sending', this.translateOutgoing.bind(this));
- }
- }
-
- async onUnload(): Promise<void> {}
-
- async translateIncoming(event: MessageEvent): Promise<HookResult> {
- if (!this.config.enabled || !event.message.body) {
- return { continue: true };
- }
-
- try {
- const translated = await this.translate(
- event.message.body,
- this.config.sourceLanguage,
- this.config.targetLanguage
- );
-
- // Add translation to message metadata
- const modified = {
- ...event,
- message: {
- ...event.message,
- metadata: {
- ...event.message.metadata,
- originalText: event.message.body,
- translatedText: translated,
- translatedFrom: this.config.sourceLanguage,
- translatedTo: this.config.targetLanguage,
- },
- },
- };
-
- return { continue: true, modified };
- } catch (error) {
- this.ctx.logger.error('Translation failed', { error });
- return { continue: true };
- }
- }
-
- async translateOutgoing(event: MessageEvent): Promise<HookResult> {
- // Similar implementation for outgoing messages
- return { continue: true };
- }
-
- private async translate(
- text: string,
- from: string,
- to: string
- ): Promise<string> {
- switch (this.config.provider) {
- case 'google':
- return this.translateWithGoogle(text, from, to);
- case 'deepl':
- return this.translateWithDeepL(text, from, to);
- case 'libre':
- return this.translateWithLibre(text, from, to);
- default:
- throw new Error(`Unknown provider: ${this.config.provider}`);
- }
- }
-
- private async translateWithGoogle(
- text: string,
- from: string,
- to: string
- ): Promise<string> {
- const response = await this.ctx.api.http.post(
- 'https://translation.googleapis.com/language/translate/v2',
- {
- q: text,
- source: from === 'auto' ? undefined : from,
- target: to,
- key: this.config.apiKey,
+export default class AutoReplyPlugin implements IPlugin {
+ async onLoad(ctx: PluginContext): Promise<void> {
+ ctx.registerHook('message:received', async hookCtx => {
+ const cfg = ctx.config as AutoReplyConfig; // per-session-merged config for this event
+ const { sessionId, data } = hookCtx;
+ const message = data as { from: string; body?: string };
+ if (cfg.enabled === false || !sessionId || !message.body) return { continue: true };
+
+ const text = message.body.toLowerCase();
+ const rule = (cfg.rules ?? []).find(r => text.includes(r.match.toLowerCase()));
+ if (rule) {
+ await ctx.messages.sendText(sessionId, message.from, rule.reply);
+ await ctx.storage.set(`stats:replies:${Date.now()}`, rule.match);
}
- );
+ return { continue: true }; // keep the chain going (still delivers the webhook)
+ });
- return response.data.translations[0].translatedText;
+ ctx.logger.log('Auto-reply plugin loaded');
}
-
- // ... other provider implementations
}
```
-## 19.8 Plugin Management API
-
-### REST Endpoints
-
-```typescript
-// src/api/plugins/plugins.controller.ts
-
-@Controller('api/plugins')
-@UseGuards(ApiKeyGuard)
-export class PluginsController {
- constructor(private pluginService: PluginService) {}
-
- @Get()
- async listPlugins(): Promise<PluginInfo[]> {
- return this.pluginService.listAll();
- }
-
- @Get(':id')
- async getPlugin(@Param('id') id: string): Promise<PluginInfo> {
- return this.pluginService.get(id);
- }
-
- @Post(':id/enable')
- async enablePlugin(@Param('id') id: string): Promise<void> {
- await this.pluginService.enable(id);
- }
-
- @Post(':id/disable')
- async disablePlugin(@Param('id') id: string): Promise<void> {
- await this.pluginService.disable(id);
- }
-
- @Post(':id/reload')
- async reloadPlugin(@Param('id') id: string): Promise<void> {
- await this.pluginService.reload(id);
- }
-
- @Get(':id/config')
- async getPluginConfig(@Param('id') id: string): Promise<any> {
- return this.pluginService.getConfig(id);
- }
-
- @Put(':id/config')
- async updatePluginConfig(
- @Param('id') id: string,
- @Body() config: any
- ): Promise<void> {
- await this.pluginService.updateConfig(id, config);
- }
-
- @Post('install')
- async installPlugin(@Body() input: InstallPluginInput): Promise<PluginInfo> {
- return this.pluginService.install(input);
- }
-
- @Delete(':id')
- async uninstallPlugin(@Param('id') id: string): Promise<void> {
- await this.pluginService.uninstall(id);
- }
-}
+A plugin that calls an external API instead would declare `net:fetch` plus the host in `net.allow`, and
+use `await ctx.net.fetch('https://api.example.com/...', { method: 'POST', body, headers })` — the
+SSRF-guarded outbound HTTP capability. A read-only plugin (e.g. enriching events with group/contact
+data) would declare `engine:read` and call `ctx.engine.getGroupInfo(...)` / `ctx.engine.getContacts(...)`.
-interface PluginInfo {
- id: string;
- name: string;
- version: string;
- description: string;
- author: string;
- enabled: boolean;
- permissions: string[];
- config: any;
-}
+## 19.8 Plugin Management API
-interface InstallPluginInput {
- source: 'npm' | 'github' | 'local';
- package: string; // npm package name, github repo, or local path
-}
-```
+`PluginsController` (`src/modules/plugins/plugins.controller.ts`) is mounted at `plugins` and **every
+route requires the `ADMIN` role** (`@RequireRole(ApiKeyRole.ADMIN)` — not a bare API-key guard). There
+is **no** `POST :id/reload` and **no** `GET :id/config`. Install is a multipart `.zip` upload (or by
+URL / catalog), not an npm/github source descriptor.
+
+| Method & path | Purpose |
+|---------------|---------|
+| `GET /plugins` | List all plugins |
+| `GET /plugins/catalog` | List the remote plugin catalog, annotated with install state |
+| `GET /plugins/:id` | Get a single plugin |
+| `POST /plugins/install` | Install from an uploaded `.zip` (`multipart/form-data`, field `file`, ≤ 5 MB) |
+| `POST /plugins/install-url` | Install by downloading a `.zip` from a URL (SSRF-guarded) |
+| `POST /plugins/:id/update` | Update an installed plugin in place from a URL (preserves config + enabled state) |
+| `POST /plugins/:id/enable` | Enable a plugin |
+| `POST /plugins/:id/disable` | Disable a plugin |
+| `PUT /plugins/:id/config` | Update the plugin's base config |
+| `PUT /plugins/:id/config/:sessionId` | Set (or clear, when empty) a per-session config override |
+| `PUT /plugins/:id/sessions` | Set which sessions a session-scoped plugin is activated for (`['*']` = all) |
+| `GET /plugins/:id/config-ui` | Serve the plugin's sandboxed config-UI HTML (for an iframe `srcdoc`) |
+| `GET /plugins/:id/health` | Run the plugin's `healthCheck` |
+| `DELETE /plugins/:id` | Uninstall a plugin (removes its files; built-ins are protected) |
+
+> `GET /plugins/:id/config-ui` returns untrusted HTML served with `Content-Security-Policy: sandbox`
+> and `X-Content-Type-Options: nosniff`. The dashboard fetches it **with** the API key and injects the
+> body as an iframe `srcdoc` (opaque origin); the editor exchanges config over a `postMessage` bridge,
+> so the API key never reaches the iframe.
## 19.9 Plugin Security
-### Permission Model
-
-```typescript
-// src/core/plugins/permissions.ts
-
-export const PERMISSIONS = {
- // Sessions
- 'sessions:read': 'Read session information',
- 'sessions:write': 'Create/delete sessions',
-
- // Messages
- 'messages:read': 'Read messages',
- 'messages:write': 'Send messages',
+### Permission model
- // Contacts
- 'contacts:read': 'Read contacts',
- 'contacts:write': 'Block/unblock contacts',
+There are exactly **three** capability permissions, declared in the manifest `permissions` array and
+enforced at the capability boundary:
- // Groups
- 'groups:read': 'Read group information',
- 'groups:write': 'Manage groups',
-
- // Storage
- 'storage:read': 'Read plugin storage',
- 'storage:write': 'Write to plugin storage',
-
- // HTTP
- 'http:outbound': 'Make outbound HTTP requests',
-
- // System
- 'system:info': 'Read system information',
- 'system:config': 'Read/write system config',
+```typescript
+// src/core/plugins/plugin.interfaces.ts
+
+export const PluginCapabilityPermission = {
+ /** ctx.messages.* — send / reply on a session. */
+ MESSAGES_SEND: 'messages:send',
+ /** ctx.engine.* — read-only engine queries (group info, contacts, chats, number check). */
+ ENGINE_READ: 'engine:read',
+ /** ctx.net.fetch — SSRF-guarded outbound HTTP, scoped to the manifest net.allow host list. */
+ NET_FETCH: 'net:fetch',
} as const;
+```
-export type Permission = keyof typeof PERMISSIONS;
-
-export class PermissionChecker {
- constructor(private allowedPermissions: Set<Permission>) {}
-
- check(required: Permission): boolean {
- return this.allowedPermissions.has(required);
- }
+There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement lives in the loader:
+each capability method calls `assertPermission(manifest, permission)` before doing any work, and a
+plugin whose manifest does not declare the matching permission (or declares none) is rejected with a
+`PluginCapabilityError`:
- require(required: Permission): void {
- if (!this.check(required)) {
- throw new PermissionDeniedError(required);
- }
- }
-}
+```typescript
+// src/core/plugins/plugin-loader.service.ts (paraphrased)
-export class PermissionDeniedError extends Error {
- constructor(permission: Permission) {
- super(`Permission denied: ${permission}`);
- this.name = 'PermissionDeniedError';
+private assertPermission(manifest: PluginManifest, permission: PluginCapabilityPermission): void {
+ if (!(manifest.permissions ?? []).includes(permission)) {
+ throw new PluginCapabilityError(
+ `Plugin ${manifest.id} is missing the '${permission}' permission required for this capability`,
+ );
}
}
```
-### Sandboxed Execution
+Two further checks apply on top of the permission:
-```typescript
-// src/core/plugins/sandbox.ts
-
-import { VM } from 'vm2';
-
-export class PluginSandbox {
- private vm: VM;
-
- constructor(permissions: Set<Permission>) {
- this.vm = new VM({
- timeout: 10000, // 10 second timeout
- sandbox: {
- // Only expose allowed APIs
- console: this.createSafeConsole(),
- setTimeout: this.createSafeTimeout(),
- setInterval: this.createSafeInterval(),
- // ... other safe APIs
- },
- eval: false,
- wasm: false,
- });
- }
+- **Session scope.** `messages` and `engine` calls run `assertSessionAllowed(manifest, sessionId)` —
+ the plugin may only act on sessions in its manifest `sessions` list (`['*']` = all). The `sessionId`
+ comes from the plugin, so this is the security boundary; it is static (editing config can't widen it).
+- **Network allowlist.** `ctx.net.fetch` additionally requires the target host to be in `manifest.net.allow`,
+ and the request always passes through the SSRF guard (which blocks internal IPs even for an allowlisted host).
- async execute(code: string, context: object): Promise<any> {
- return this.vm.run(code);
- }
+### Sandboxed execution
- private createSafeConsole() {
- return {
- log: (...args: any[]) => console.log('[Plugin]', ...args),
- error: (...args: any[]) => console.error('[Plugin]', ...args),
- warn: (...args: any[]) => console.warn('[Plugin]', ...args),
- };
- }
+Untrusted plugins (anything loaded from the plugins directory) run in a Node `worker_thread`; there is
+**no `vm2`**. First-party built-ins (the engine adapters) run in-process. The loader routes by trust
+tier automatically. Key properties:
- private createSafeTimeout() {
- return (fn: Function, ms: number) => {
- if (ms > 30000) ms = 30000; // Max 30 seconds
- return setTimeout(fn, ms);
- };
- }
+- Each worker has a heap cap (`maxOldGenerationSizeMb`, default **256 MB**) — an OOM terminates the
+ worker, not the host.
+- A sandboxed hook handler has a **5 s** time budget (`SANDBOX_HOOK_TIMEOUT_MS`); on timeout the host
+ resolves `{ continue: true }` (fail-open) so a slow/wedged handler never stalls the hook chain. The
+ same fail-open value drains in-flight hooks if the worker crashes.
+- Lifecycle methods (`load`/`onLoad`/`onEnable`/`onDisable`) and `healthCheck` are bounded by a **30 s**
+ / **5 s** timeout respectively, so a wedged plugin can't hang an ADMIN enable/disable or the health endpoint.
+- The worker gets a **minimal allowlisted env** (`NODE_ENV`, `NODE_EXTRA_CA_CERTS`, `TZ`) — host secrets
+ (master key, DB/Redis vars, …) are withheld.
+
+This is V8-context isolation in the same OS process, not an OS-level sandbox: a worker can still reach
+Node built-ins (`fs`, `process`, sockets). For genuinely untrusted plugins, combine it with OS
+containment (the shipped Docker image runs read-only rootfs, non-root, `cap_drop: ALL`). See
+[23 — Plugin Sandboxing](./23-plugin-sandboxing.md) for the full security model and author rules.
- private createSafeInterval() {
- return (fn: Function, ms: number) => {
- if (ms < 1000) ms = 1000; // Min 1 second
- return setInterval(fn, ms);
- };
- }
-}
-```
---
<div align="center">