Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
chore(format): format the markdown tree with Prettier
Yudhi Armyndharis8b939f0ab150
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex d13be4fa8..1f91530fb 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -1,13 +1,16 @@## Description+Brief description of changes## Type of Change+- [ ] Bug fix- [ ] New feature- [ ] Breaking change- [ ] Documentation update## Checklist+- [ ] Tests added/updated- [ ] Documentation updated- [ ] Lint passes@@ -16,4 +19,5 @@ Brief description of changes## Screenshots (if applicable)## Related Issues+Closes #diff --git a/README.md b/README.mdindex bcf757f68..cc0784c16 100644--- a/README.md+++ b/README.md@@ -33,16 +33,16 @@Built on a **pluggable architecture**, OpenWA lets you select database engines (SQLite/PostgreSQL), backup/migration storage backends (Local/S3), and cache layers (disabled/Redis) through configuration rather than application-code changes. Message media itself is returned inline to API and webhook consumers; it is not automatically persisted to the storage backend.-| | |-| ----------------------------- | ------------------------------------------------------------------------------------------ |-| π **100% Open Source** | No licensing fees, no feature locks, full source code access |-| ποΈ **Pluggable Architecture** | Swap adapters for database, storage, and cache via config |-| π₯οΈ **Full Dashboard** | Modern React UI for session, webhook, and API key management |-| πΉ **Multi-Session Ready** | Run multiple WhatsApp sessions concurrently on one instance |-| π³ **Docker Native** | Production-ready with zero configuration |+| | |+| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |+| π **100% Open Source** | No licensing fees, no feature locks, full source code access |+| ποΈ **Pluggable Architecture** | Swap adapters for database, storage, and cache via config |+| π₯οΈ **Full Dashboard** | Modern React UI for session, webhook, and API key management |+| πΉ **Multi-Session Ready** | Run multiple WhatsApp sessions concurrently on one instance |+| π³ **Docker Native** | Production-ready with zero configuration || π§© **Official Plugins** | Chatwoot, Typebot & more as sandboxed plugins on the Integration Fabric β [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) |-| π **n8n Integration** | Community nodes for workflow automation |-| π§© **Community Adapters** | Third-party integrations (e.g. ioBroker) β see [docs](./docs/23-community-integrations.md) |+| π **n8n Integration** | Community nodes for workflow automation |+| π§© **Community Adapters** | Third-party integrations (e.g. ioBroker) β see [docs](./docs/23-community-integrations.md) |---@@ -104,27 +104,27 @@ For any deployment where ethical, legal, or regulatory compliance matters (healt### Messaging-| Feature | Status | Description |-| ----------------- | ------ | -------------------------------------------- |-| Text Messages | β | Send/receive text messages |-| Media Messages | β | Images, videos, documents, audio |-| Message Reactions | β | React to messages with emoji |-| Message Editing | β | Send edits + live `message.edited` events on both engines |-| Bulk Messaging | β | Send to multiple recipients |-| Message Status | β | Track delivery and read receipts |+| Feature | Status | Description |+| ----------------- | ------ | --------------------------------------------------------- |+| Text Messages | β | Send/receive text messages |+| Media Messages | β | Images, videos, documents, audio |+| Message Reactions | β | React to messages with emoji |+| Message Editing | β | Send edits + live `message.edited` events on both engines |+| Bulk Messaging | β | Send to multiple recipients |+| Message Status | β | Track delivery and read receipts |### Advanced-| Feature | Status | Description |-| ------------------- | ------ | ---------------------------------- |-| Groups API | β | Create, manage, join (invite code), and configure groups |-| Profile Management | β | Set own display name, about text, and profile picture |-| Call Handling | β | `call.received` events, reject calls, per-session auto-reject |-| Channels/Newsletter | β | WhatsApp Channels support |-| Labels Management | β | Organize chats with labels |-| Proxy Support | β | Per-session proxy configuration |-| Rate Limiting | β | Configurable request limits |-| CIDR Whitelisting | β | IP-based access control |+| Feature | Status | Description |+| ------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Groups API | β | Create, manage, join (invite code), and configure groups |+| Profile Management | β | Set own display name, about text, and profile picture |+| Call Handling | β | `call.received` events, reject calls, per-session auto-reject |+| Channels/Newsletter | β | WhatsApp Channels support |+| Labels Management | β | Organize chats with labels |+| Proxy Support | β | Per-session proxy configuration |+| Rate Limiting | β | Configurable request limits |+| CIDR Whitelisting | β | IP-based access control || Audit Logging | β | Audit trail for API-key, session, integration-instance, and infra admin operations (message sends and webhook deliveries are tracked in their own tables, not the audit log) |### Infrastructurediff --git a/docs/01-project-overview.md b/docs/01-project-overview.mdindex 2369d46c1..03a774e94 100644--- a/docs/01-project-overview.md+++ b/docs/01-project-overview.md@@ -21,9 +21,11 @@## 1.2 Vision & Mission### Vision+To become the most reliable open-source WhatsApp API gateway for production use.### Mission+1. Provide a complete and free WhatsApp REST API2. Build an active open-source community3. Deliver excellent documentation and tooling@@ -39,14 +41,14 @@ flowchart LRP3[Vendor lock-in]P4[Data privacy concerns]end-+subgraph Solution["β OpenWA Solution"]S1[100% Free & Open Source]S2[All features included]S3[Self-hosted, no lock-in]S4[Data stays on your server]end-+P1 --> S1P2 --> S2P3 --> S3@@ -55,13 +57,13 @@ flowchart LR### Pain Points Addressed-| Pain Point | OpenWA Solution |-|------------|------------------|+| Pain Point | OpenWA Solution |+| ----------------------------------- | ---------------------------- || WAHA Plus charges for multi-session | Free unlimited multi-session |-| Dashboard only in paid tiers | Free dashboard |-| PostgreSQL support is paid | PostgreSQL included |-| Limited webhook management | Full webhook management |-| No source code access | Full source code available |+| Dashboard only in paid tiers | Free dashboard |+| PostgreSQL support is paid | PostgreSQL included |+| Limited webhook management | Full webhook management |+| No source code access | Full source code available |## 1.4 Project Goals@@ -89,13 +91,13 @@ mindmap### Success Metrics-| Metric | Target (6 months) | Target (1 year) |-|--------|-------------------|-----------------|-| GitHub Stars | 500+ | 2000+ |-| Active Contributors | 10+ | 30+ |-| Docker Pulls | 5,000+ | 20,000+ |-| Production Users | 100+ | 500+ |-| API Uptime | 99.5% | 99.9% |+| Metric | Target (6 months) | Target (1 year) |+| ------------------- | ----------------- | --------------- |+| GitHub Stars | 500+ | 2000+ |+| Active Contributors | 10+ | 30+ |+| Docker Pulls | 5,000+ | 20,000+ |+| Production Users | 100+ | 500+ |+| API Uptime | 99.5% | 99.9% |## 1.5 Project Scope@@ -157,19 +159,19 @@ flowchart TBB[Small Businesses]S[Startups]end-+subgraph Secondary["Secondary Stakeholders"]C[Community Contributors]I[Integration Partners]O[Open Source Community]end-+subgraph Users["End Users"]U1[Self-hosted Users]U2[Docker Users]U3[Cloud Deploy Users]end-+Primary --> UsersSecondary --> Primary```@@ -192,7 +194,7 @@ quadrantChartquadrant-2 Our Targetquadrant-3 Limited Freequadrant-4 Expensive Basic-+WAHA Plus: [0.7, 0.8]WAHA Core: [0.2, 0.4]Whapi.cloud: [0.8, 0.75]@@ -202,16 +204,16 @@ quadrantChart### Feature Comparison-| Feature | OpenWA | WAHA Core | WAHA Plus | Whapi.cloud |-|---------|--------|-----------|-----------|-------------|-| Price | Free | Free | $50+/mo | $30+/mo |-| Open Source | β | β | β | β |-| Multi-session | β | Limited | β | β |-| Dashboard | β | β | β | β |-| PostgreSQL | β | β | β | N/A |-| Webhook UI | β | β | β | β |-| Self-hosted | β | β | β | β |-| Source code | β | β | β | β |+| Feature | OpenWA | WAHA Core | WAHA Plus | Whapi.cloud |+| ------------- | ------ | --------- | --------- | ----------- |+| Price | Free | Free | $50+/mo | $30+/mo |+| Open Source | β | β | β | β |+| Multi-session | β | Limited | β | β |+| Dashboard | β | β | β | β |+| PostgreSQL | β | β | β | N/A |+| Webhook UI | β | β | β | β |+| Self-hosted | β | β | β | β |+| Source code | β | β | β | β |## 1.8 Technology Decisions@@ -223,18 +225,18 @@ flowchart TBN[Node.js 22 LTS] --> |"TypeScript support, async/await"| NE[NestJS]NE --> |"Modular, scalable, DI"| API[REST API]end-+subgraph Engine["WhatsApp Engine (pluggable)"]WW[whatsapp-web.js] --> |"Puppeteer based"| P[More stealth]P --> |"Real browser fingerprint"| S[Lower ban risk]BA[baileys] --> |"Browser-free / WebSocket"| BL[Lower resource usage]end-+subgraph Storage["Data Storage"]SQ[SQLite] --> |"Development"| DEV[Easy setup]PG[PostgreSQL] --> |"Production"| PROD[Scalable]end-+subgraph Frontend["Dashboard"]R[React] --> V[Vite]V --> C[Bespoke CSS]@@ -245,20 +247,20 @@ flowchart TB### Technology Stack Summary-| Layer | Technology | Rationale |-|-------|------------|-----------|-| Runtime | Node.js 22 LTS | Stable, long-term support |-| Language | TypeScript | Type safety, better developer experience |-| Framework | NestJS | Enterprise-grade, modular |-| WA Engine | whatsapp-web.js (default) or baileys | Pluggable via `ENGINE_TYPE` env var; wwebjs = Puppeteer/stealth, baileys = browser-free |-| Browser | Puppeteer/Chrome | Used by default (whatsapp-web.js) engine; not required for baileys engine |-| Database | SQLite (default) / PostgreSQL | Zero-config default, PostgreSQL for scaling |-| Cache | Redis | Fast, pub/sub support |-| Queue | BullMQ | Reliable job processing |-| Dashboard | React + Vite | Fast, modern |-| Styling | Bespoke CSS modules/stylesheets | Lightweight dashboard styling without Tailwind |-| UI Components | Custom React components + Lucide | Accessible, polished |-| Container | Docker | Portable, consistent |+| Layer | Technology | Rationale |+| ------------- | ------------------------------------ | --------------------------------------------------------------------------------------- |+| Runtime | Node.js 22 LTS | Stable, long-term support |+| Language | TypeScript | Type safety, better developer experience |+| Framework | NestJS | Enterprise-grade, modular |+| WA Engine | whatsapp-web.js (default) or baileys | Pluggable via `ENGINE_TYPE` env var; wwebjs = Puppeteer/stealth, baileys = browser-free |+| Browser | Puppeteer/Chrome | Used by default (whatsapp-web.js) engine; not required for baileys engine |+| Database | SQLite (default) / PostgreSQL | Zero-config default, PostgreSQL for scaling |+| Cache | Redis | Fast, pub/sub support |+| Queue | BullMQ | Reliable job processing |+| Dashboard | React + Vite | Fast, modern |+| Styling | Bespoke CSS modules/stylesheets | Lightweight dashboard styling without Tailwind |+| UI Components | Custom React components + Lucide | Accessible, polished |+| Container | Docker | Portable, consistent |## 1.9 Constraints & Assumptions@@ -286,9 +288,10 @@ flowchart TB## 1.10 Document History-| Version | Date | Author | Changes |-|---------|------|--------|---------|-| 1.0 | 2026-02-02 | Team | Initial document |+| Version | Date | Author | Changes |+| ------- | ---------- | ------ | ---------------- |+| 1.0 | 2026-02-02 | Team | Initial document |+---<div align="center">diff --git a/docs/02-requirements-specification.md b/docs/02-requirements-specification.mdindex 3d0e53e96..e57532fa0 100644--- a/docs/02-requirements-specification.md+++ b/docs/02-requirements-specification.md@@ -19,23 +19,23 @@ flowchart LRend```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-SM-001 | The system must create new sessions | High | 1 |-| FR-SM-002 | The system must generate a QR code for authentication | High | 1 |-| FR-SM-003 | The system must persist session state for reconnection | High | 1 |-| FR-SM-004 | The system must delete a session | High | 1 |-| FR-SM-005 | The system must display session status | High | 1 |-| FR-SM-006 | The system must support multiple sessions | High | 2 |-| FR-SM-007 | The system must auto-reconnect when the connection is lost | Medium | 2 |-| FR-SM-008 | The system must support session naming | Low | 2 |+| ID | Requirement | Priority | Phase |+| --------- | ---------------------------------------------------------- | -------- | ----- |+| FR-SM-001 | The system must create new sessions | High | 1 |+| FR-SM-002 | The system must generate a QR code for authentication | High | 1 |+| FR-SM-003 | The system must persist session state for reconnection | High | 1 |+| FR-SM-004 | The system must delete a session | High | 1 |+| FR-SM-005 | The system must display session status | High | 1 |+| FR-SM-006 | The system must support multiple sessions | High | 2 |+| FR-SM-007 | The system must auto-reconnect when the connection is lost | Medium | 2 |+| FR-SM-008 | The system must support session naming | Low | 2 |### 2.2.2 Messaging```mermaidflowchart TBsubgraph Outbound["Outbound Messages"]- T[Text]+ T[Text]I[Image]V[Video]A[Audio]@@ -44,38 +44,38 @@ flowchart TBCT[Contact]S[Sticker]end-+subgraph Inbound["Inbound Messages"]W[Webhook] --> P[Process]P --> ACK[Acknowledgment]end-+Outbound --> API[REST API]API --> WA[WhatsApp]WA --> Inbound```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-MSG-001 | The system must send text messages | High | 1 |-| FR-MSG-002 | The system must send images with captions | High | 1 |-| FR-MSG-003 | The system must send video messages | High | 1 |-| FR-MSG-004 | The system must send audio/voice notes | High | 1 |-| FR-MSG-005 | The system must send documents/files | High | 1 |-| FR-MSG-006 | The system must send locations | Medium | 2 |-| FR-MSG-007 | The system must send contact cards | Medium | 2 |-| FR-MSG-008 | The system must send stickers | Medium | 2 |-| FR-MSG-009 | The system must reply to a message | Medium | 2 |-| FR-MSG-010 | The system must forward messages | Low | 3 |-| FR-MSG-011 | The system must delete messages | Low | 3 |-| FR-MSG-012 | The system must react to messages | Low | 3 |-| FR-MSG-013 | The system must send bulk messages (batch) | Medium | 2 |-| FR-MSG-014 | The system must support template variables in bulk messages | Medium | 2 |-| FR-MSG-015 | The system must track status per message in a batch | Medium | 2 |-| FR-MSG-016 | The system must cancel a running batch | Medium | 2 |-| FR-MSG-017 | The system must apply delays between messages to reduce ban risk | High | 2 |-| FR-MSG-018 | The system must validate media size before sending | High | 1 |-| FR-MSG-019 | The system must support downloading media from a URL | High | 1 |+| ID | Requirement | Priority | Phase |+| ---------- | ---------------------------------------------------------------- | -------- | ----- |+| FR-MSG-001 | The system must send text messages | High | 1 |+| FR-MSG-002 | The system must send images with captions | High | 1 |+| FR-MSG-003 | The system must send video messages | High | 1 |+| FR-MSG-004 | The system must send audio/voice notes | High | 1 |+| FR-MSG-005 | The system must send documents/files | High | 1 |+| FR-MSG-006 | The system must send locations | Medium | 2 |+| FR-MSG-007 | The system must send contact cards | Medium | 2 |+| FR-MSG-008 | The system must send stickers | Medium | 2 |+| FR-MSG-009 | The system must reply to a message | Medium | 2 |+| FR-MSG-010 | The system must forward messages | Low | 3 |+| FR-MSG-011 | The system must delete messages | Low | 3 |+| FR-MSG-012 | The system must react to messages | Low | 3 |+| FR-MSG-013 | The system must send bulk messages (batch) | Medium | 2 |+| FR-MSG-014 | The system must support template variables in bulk messages | Medium | 2 |+| FR-MSG-015 | The system must track status per message in a batch | Medium | 2 |+| FR-MSG-016 | The system must cancel a running batch | Medium | 2 |+| FR-MSG-017 | The system must apply delays between messages to reduce ban risk | High | 2 |+| FR-MSG-018 | The system must validate media size before sending | High | 1 |+| FR-MSG-019 | The system must support downloading media from a URL | High | 1 |### 2.2.3 Webhook & Events@@ -84,30 +84,30 @@ sequenceDiagramparticipant WA as WhatsAppparticipant OW as OpenWAparticipant WH as Webhook URL-+WA->>OW: New Message EventOW->>OW: Process & StoreOW->>WH: POST /webhookWH-->>OW: 200 OK-+alt Webhook FailedOW->>OW: Queue for RetryOW->>WH: Retry (up to retryCount attempts in total, default 3)end```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-WH-001 | The system must deliver events to webhook URLs | High | 1 |-| FR-WH-002 | The system must support multiple webhook URLs | Medium | 2 |-| FR-WH-003 | The system must retry failed webhooks (per-webhook `retryCount`, 0-5, default 3) | Medium | 2 |-| FR-WH-004 | The system must filter event types per webhook | Medium | 2 |-| FR-WH-005 | The system must log webhook delivery status | Medium | 2 |-| FR-WH-006 | The system must support webhook signature verification | Medium | 2 |-| FR-WH-007 | The system must provide an idempotency key per event | High | 2 |-| FR-WH-008 | The system must provide a delivery ID to track retries | Medium | 2 |-| FR-WH-009 | The system must support exponential backoff for retries | Medium | 2 |-| FR-WH-010 | The system must enable/disable webhooks without deletion | Low | 2 |+| ID | Requirement | Priority | Phase |+| --------- | -------------------------------------------------------------------------------- | -------- | ----- |+| FR-WH-001 | The system must deliver events to webhook URLs | High | 1 |+| FR-WH-002 | The system must support multiple webhook URLs | Medium | 2 |+| FR-WH-003 | The system must retry failed webhooks (per-webhook `retryCount`, 0-5, default 3) | Medium | 2 |+| FR-WH-004 | The system must filter event types per webhook | Medium | 2 |+| FR-WH-005 | The system must log webhook delivery status | Medium | 2 |+| FR-WH-006 | The system must support webhook signature verification | Medium | 2 |+| FR-WH-007 | The system must provide an idempotency key per event | High | 2 |+| FR-WH-008 | The system must provide a delivery ID to track retries | Medium | 2 |+| FR-WH-009 | The system must support exponential backoff for retries | Medium | 2 |+| FR-WH-010 | The system must enable/disable webhooks without deletion | Low | 2 |### 2.2.4 Real-time Updates (WebSocket)@@ -130,25 +130,25 @@ flowchart LRWebSocket --> Events```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-WS-001 | The system must provide a WebSocket endpoint for real-time updates | Medium | 2 |-| FR-WS-002 | The system must support API key authentication for WebSocket | Medium | 2 |-| FR-WS-003 | The system must allow subscribing to a specific session | Medium | 2 |-| FR-WS-004 | The system must allow subscribing to specific event types | Medium | 2 |-| FR-WS-005 | The system must implement ping/pong keep-alive | Medium | 2 |-| FR-WS-006 | The system must auto-reconnect with exponential backoff | Low | 3 |-| FR-WS-007 | The system must stream QR code updates in real time | High | 2 |+| ID | Requirement | Priority | Phase |+| --------- | ------------------------------------------------------------------ | -------- | ----- |+| FR-WS-001 | The system must provide a WebSocket endpoint for real-time updates | Medium | 2 |+| FR-WS-002 | The system must support API key authentication for WebSocket | Medium | 2 |+| FR-WS-003 | The system must allow subscribing to a specific session | Medium | 2 |+| FR-WS-004 | The system must allow subscribing to specific event types | Medium | 2 |+| FR-WS-005 | The system must implement ping/pong keep-alive | Medium | 2 |+| FR-WS-006 | The system must auto-reconnect with exponential backoff | Low | 3 |+| FR-WS-007 | The system must stream QR code updates in real time | High | 2 |### 2.2.5 Contact Management-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-CT-001 | The system must retrieve all contacts | High | 1 |-| FR-CT-002 | The system must retrieve a contact by ID | High | 1 |-| FR-CT-003 | The system must check if a number exists on WhatsApp | High | 1 |-| FR-CT-004 | The system must retrieve a contact profile picture | Medium | 2 |-| FR-CT-005 | The system must block/unblock a contact | Low | 3 |+| ID | Requirement | Priority | Phase |+| --------- | ---------------------------------------------------- | -------- | ----- |+| FR-CT-001 | The system must retrieve all contacts | High | 1 |+| FR-CT-002 | The system must retrieve a contact by ID | High | 1 |+| FR-CT-003 | The system must check if a number exists on WhatsApp | High | 1 |+| FR-CT-004 | The system must retrieve a contact profile picture | Medium | 2 |+| FR-CT-005 | The system must block/unblock a contact | Low | 3 |### 2.2.6 Group Management@@ -164,7 +164,7 @@ flowchart TBDM[Demote Admin]LV[Leave Group]end-+subgraph GroupInfo["Group Info"]GI[Get Info]GP[Get Participants]@@ -172,18 +172,18 @@ flowchart TBend```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-GR-001 | The system must retrieve all groups | Medium | 2 |-| FR-GR-002 | The system must retrieve group info | Medium | 2 |-| FR-GR-003 | The system must retrieve group participants | Medium | 2 |-| FR-GR-004 | The system must create a group | Medium | 3 |-| FR-GR-005 | The system must update group info | Low | 3 |-| FR-GR-006 | The system must add participants | Low | 3 |-| FR-GR-007 | The system must remove participants | Low | 3 |-| FR-GR-008 | The system must promote/demote admins | Low | 3 |-| FR-GR-009 | The system must get/revoke invite links | Low | 3 |-| FR-GR-010 | The system must leave a group | Low | 3 |+| ID | Requirement | Priority | Phase |+| --------- | ------------------------------------------- | -------- | ----- |+| FR-GR-001 | The system must retrieve all groups | Medium | 2 |+| FR-GR-002 | The system must retrieve group info | Medium | 2 |+| FR-GR-003 | The system must retrieve group participants | Medium | 2 |+| FR-GR-004 | The system must create a group | Medium | 3 |+| FR-GR-005 | The system must update group info | Low | 3 |+| FR-GR-006 | The system must add participants | Low | 3 |+| FR-GR-007 | The system must remove participants | Low | 3 |+| FR-GR-008 | The system must promote/demote admins | Low | 3 |+| FR-GR-009 | The system must get/revoke invite links | Low | 3 |+| FR-GR-010 | The system must leave a group | Low | 3 |### 2.2.7 Dashboard (Web UI)@@ -197,20 +197,20 @@ flowchart LRLG[Logs Viewer]ST[Statistics]end-+Dashboard --> API[REST API]API --> BE[Backend]```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-UI-001 | The dashboard must display the status of all sessions | High | 2 |-| FR-UI-002 | The dashboard must display QR codes | High | 2 |-| FR-UI-003 | The dashboard must manage webhooks | Medium | 2 |-| FR-UI-004 | The dashboard must view logs | Medium | 2 |-| FR-UI-005 | The dashboard must test sending messages | Medium | 2 |-| FR-UI-006 | The dashboard must display statistics | Low | 3 |-| FR-UI-007 | The dashboard must support dark mode | Low | 3 |+| ID | Requirement | Priority | Phase |+| --------- | ----------------------------------------------------- | -------- | ----- |+| FR-UI-001 | The dashboard must display the status of all sessions | High | 2 |+| FR-UI-002 | The dashboard must display QR codes | High | 2 |+| FR-UI-003 | The dashboard must manage webhooks | Medium | 2 |+| FR-UI-004 | The dashboard must view logs | Medium | 2 |+| FR-UI-005 | The dashboard must test sending messages | Medium | 2 |+| FR-UI-006 | The dashboard must display statistics | Low | 3 |+| FR-UI-007 | The dashboard must support dark mode | Low | 3 |### 2.2.8 Authentication & Authorization@@ -227,19 +227,19 @@ flowchart TBend```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-AU-001 | The system must support API key authentication | High | 2 |-| FR-AU-002 | The system must generate/revoke API keys | High | 2 |-| FR-AU-003 | The system must set permissions per API key | Medium | 3 |-| FR-AU-004 | The system must log API access | Medium | 2 |-| FR-AU-005 | The system must support IP whitelisting per API key | Medium | 2 |-| FR-AU-006 | The system must support CIDR notation for IP ranges | Low | 2 |-| FR-AU-007 | The system must set expiration dates for API keys | Medium | 2 |-| FR-AU-008 | The system must hash API keys before storage (SHA-256) | High | 2 |-| FR-AU-009 | The system must track last used timestamps per API key | Low | 2 |-| FR-AU-010 | The system must support a master API key from environment | High | 2 |-| FR-AU-011 | The system must support the `X-Request-ID` header for request tracing | Medium | 2 |+| ID | Requirement | Priority | Phase |+| --------- | --------------------------------------------------------------------- | -------- | ----- |+| FR-AU-001 | The system must support API key authentication | High | 2 |+| FR-AU-002 | The system must generate/revoke API keys | High | 2 |+| FR-AU-003 | The system must set permissions per API key | Medium | 3 |+| FR-AU-004 | The system must log API access | Medium | 2 |+| FR-AU-005 | The system must support IP whitelisting per API key | Medium | 2 |+| FR-AU-006 | The system must support CIDR notation for IP ranges | Low | 2 |+| FR-AU-007 | The system must set expiration dates for API keys | Medium | 2 |+| FR-AU-008 | The system must hash API keys before storage (SHA-256) | High | 2 |+| FR-AU-009 | The system must track last used timestamps per API key | Low | 2 |+| FR-AU-010 | The system must support a master API key from environment | High | 2 |+| FR-AU-011 | The system must support the `X-Request-ID` header for request tracing | Medium | 2 |### 2.2.9 Bulk Operations@@ -258,16 +258,16 @@ flowchart LRTRACK --> CANCEL```-| ID | Requirement | Priority | Phase |-|----|-------------|----------|-------|-| FR-BK-001 | The system must accept batches up to 100 messages | Medium | 2 |-| FR-BK-002 | The system must apply delays between messages (configurable, min 1s) | High | 2 |-| FR-BK-003 | The system must randomize delays for natural behavior | Medium | 2 |-| FR-BK-004 | The system must track batch progress (sent/failed/pending) | Medium | 2 |-| FR-BK-005 | The system must cancel a running batch | Medium | 2 |-| FR-BK-006 | The system must support template variables in batches | Low | 3 |-| FR-BK-007 | The system must return a batch ID for status tracking | High | 2 |-| FR-BK-008 | The system must clean up completed batches after 24 hours | Low | 3 |+| ID | Requirement | Priority | Phase |+| --------- | -------------------------------------------------------------------- | -------- | ----- |+| FR-BK-001 | The system must accept batches up to 100 messages | Medium | 2 |+| FR-BK-002 | The system must apply delays between messages (configurable, min 1s) | High | 2 |+| FR-BK-003 | The system must randomize delays for natural behavior | Medium | 2 |+| FR-BK-004 | The system must track batch progress (sent/failed/pending) | Medium | 2 |+| FR-BK-005 | The system must cancel a running batch | Medium | 2 |+| FR-BK-006 | The system must support template variables in batches | Low | 3 |+| FR-BK-007 | The system must return a batch ID for status tracking | High | 2 |+| FR-BK-008 | The system must clean up completed batches after 24 hours | Low | 3 |## 2.3 Non-Functional Requirements@@ -283,25 +283,25 @@ flowchart LRend```-| ID | Requirement | Target | Priority |-|----|-------------|--------|----------|-| NFR-PF-001 | API response time | < 500ms (p95) | High |-| NFR-PF-002 | Message send latency | < 2s | High |-| NFR-PF-003 | QR code generation | < 3s | High |-| NFR-PF-004 | Memory per session | < 500MB | High |-| NFR-PF-005 | Concurrent sessions | 10+ per instance | Medium |-| NFR-PF-006 | Webhook delivery | < 5s | Medium |-| NFR-PF-007 | Startup time | < 30s | Medium |+| ID | Requirement | Target | Priority |+| ---------- | -------------------- | ---------------- | -------- |+| NFR-PF-001 | API response time | < 500ms (p95) | High |+| NFR-PF-002 | Message send latency | < 2s | High |+| NFR-PF-003 | QR code generation | < 3s | High |+| NFR-PF-004 | Memory per session | < 500MB | High |+| NFR-PF-005 | Concurrent sessions | 10+ per instance | Medium |+| NFR-PF-006 | Webhook delivery | < 5s | Medium |+| NFR-PF-007 | Startup time | < 30s | Medium |### 2.3.2 Reliability & Availability-| ID | Requirement | Target | Priority |-|----|-------------|--------|----------|-| NFR-RL-001 | Uptime | 99.5% | High |-| NFR-RL-002 | Auto-recovery after crash | < 60s | High |-| NFR-RL-003 | Session persistence | Survive restart | High |-| NFR-RL-004 | Graceful shutdown | Complete pending ops | Medium |-| NFR-RL-005 | Data durability | No message loss | High |+| ID | Requirement | Target | Priority |+| ---------- | ------------------------- | -------------------- | -------- |+| NFR-RL-001 | Uptime | 99.5% | High |+| NFR-RL-002 | Auto-recovery after crash | < 60s | High |+| NFR-RL-003 | Session persistence | Survive restart | High |+| NFR-RL-004 | Graceful shutdown | Complete pending ops | Medium |+| NFR-RL-005 | Data durability | No message loss | High |### 2.3.3 Scalability@@ -312,64 +312,64 @@ flowchart TBV2[More CPU]V3[More Sessions]end-+subgraph Horizontal["Horizontal Scaling"]H1[Multiple Instances]H2[Load Balancer]H3[Shared Storage]end-+Vertical --> Single[Single Instance]Horizontal --> Cluster[Cluster Mode]```-| ID | Requirement | Target | Priority |-|----|-------------|--------|----------|-| NFR-SC-001 | Vertical scaling | 20+ sessions/instance | Medium |-| NFR-SC-002 | Horizontal scaling support | Multiple instances | Low |-| NFR-SC-003 | Stateless API design | Session-independent | High |+| ID | Requirement | Target | Priority |+| ---------- | -------------------------- | --------------------- | -------- |+| NFR-SC-001 | Vertical scaling | 20+ sessions/instance | Medium |+| NFR-SC-002 | Horizontal scaling support | Multiple instances | Low |+| NFR-SC-003 | Stateless API design | Session-independent | High |### 2.3.4 Security-| ID | Requirement | Description | Priority |-|----|-------------|-------------|----------|-| NFR-SE-001 | API Authentication | API key required | High |-| NFR-SE-002 | Data encryption | TLS for all connections | High |-| NFR-SE-003 | Secret management | Encrypted storage | High |-| NFR-SE-004 | Input validation | Sanitize all inputs | High |-| NFR-SE-005 | Rate limiting | Prevent abuse | Medium |-| NFR-SE-006 | Audit logging | Track all operations | Medium |-| NFR-SE-007 | CORS configuration | Configurable origins | Medium |+| ID | Requirement | Description | Priority |+| ---------- | ------------------ | ----------------------- | -------- |+| NFR-SE-001 | API Authentication | API key required | High |+| NFR-SE-002 | Data encryption | TLS for all connections | High |+| NFR-SE-003 | Secret management | Encrypted storage | High |+| NFR-SE-004 | Input validation | Sanitize all inputs | High |+| NFR-SE-005 | Rate limiting | Prevent abuse | Medium |+| NFR-SE-006 | Audit logging | Track all operations | Medium |+| NFR-SE-007 | CORS configuration | Configurable origins | Medium |### 2.3.5 Maintainability-| ID | Requirement | Description | Priority |-|----|-------------|-------------|----------|-| NFR-MT-001 | Code coverage | > 80% unit tests | Medium |-| NFR-MT-002 | Documentation | API docs up-to-date | High |-| NFR-MT-003 | Logging | Structured logging | High |-| NFR-MT-004 | Modular architecture | Loosely coupled | High |-| NFR-MT-005 | Configuration | Environment-based | High |+| ID | Requirement | Description | Priority |+| ---------- | -------------------- | ------------------- | -------- |+| NFR-MT-001 | Code coverage | > 80% unit tests | Medium |+| NFR-MT-002 | Documentation | API docs up-to-date | High |+| NFR-MT-003 | Logging | Structured logging | High |+| NFR-MT-004 | Modular architecture | Loosely coupled | High |+| NFR-MT-005 | Configuration | Environment-based | High |### 2.3.6 Usability-| ID | Requirement | Description | Priority |-|----|-------------|-------------|----------|-| NFR-US-001 | Setup time | < 5 minutes with Docker | High |-| NFR-US-002 | API documentation | Swagger/OpenAPI | High |-| NFR-US-003 | Error messages | Clear & actionable | High |-| NFR-US-004 | Examples | Working code examples | Medium |-| NFR-US-005 | Dashboard UX | Intuitive interface | Medium |+| ID | Requirement | Description | Priority |+| ---------- | ----------------- | ----------------------- | -------- |+| NFR-US-001 | Setup time | < 5 minutes with Docker | High |+| NFR-US-002 | API documentation | Swagger/OpenAPI | High |+| NFR-US-003 | Error messages | Clear & actionable | High |+| NFR-US-004 | Examples | Working code examples | Medium |+| NFR-US-005 | Dashboard UX | Intuitive interface | Medium |### 2.3.7 Compatibility-| ID | Requirement | Description | Priority |-|----|-------------|-------------|----------|-| NFR-CP-001 | Node.js version | 22 LTS | High |-| NFR-CP-002 | Database support | SQLite, PostgreSQL | High |-| NFR-CP-003 | OS support | Linux, macOS, Windows | High |-| NFR-CP-004 | Docker support | Official image | High |-| NFR-CP-005 | ARM64 support | Apple Silicon, ARM servers | Medium |+| ID | Requirement | Description | Priority |+| ---------- | ---------------- | -------------------------- | -------- |+| NFR-CP-001 | Node.js version | 22 LTS | High |+| NFR-CP-002 | Database support | SQLite, PostgreSQL | High |+| NFR-CP-003 | OS support | Linux, macOS, Windows | High |+| NFR-CP-004 | Docker support | Official image | High |+| NFR-CP-005 | ARM64 support | Apple Silicon, ARM servers | Medium |## 2.4 Use Cases@@ -381,7 +381,7 @@ sequenceDiagramparticipant API as OpenWA APIparticipant Engine as WA Engineparticipant WA as WhatsApp-+User->>API: POST /api/sessions/:sessionId/messages/send-textAPI->>API: Validate requestAPI->>Engine: sendMessage(chatId, text)@@ -394,12 +394,14 @@ sequenceDiagram**Actors**: External application, Developer**Precondition**: Session is active and connected**Main Flow**:+1. User sends a POST request with `chatId` and `text`2. The system validates the request3. The system sends the message via the WhatsApp engine4. The system returns the `messageId`**Alternative Flow**:+- Session not active β Return 400 error- Invalid phone number β Return 400 error- WhatsApp error β Return 500 error@@ -412,7 +414,7 @@ sequenceDiagramparticipant Engine as WA Engineparticipant API as OpenWAparticipant WH as User Webhook-+WA->>Engine: New message receivedEngine->>API: Message eventAPI->>API: Store message@@ -424,12 +426,14 @@ sequenceDiagram**Actors**: WhatsApp, External webhook endpoint**Precondition**: Webhook URL configured**Main Flow**:+1. WhatsApp sends a message to the session2. The engine receives and forwards to the API3. The API stores the message and sends it to the webhook4. The webhook endpoint acknowledges**Alternative Flow**:+- Webhook failed β Deliver at most `retryCount` times in **total**, not `retryCount` retries on top of the first try (0-5, default 3 β so the default is one delivery plus two retries, and `retryCount: 1` retries nothing)- All retries failed β Log and mark failed@@ -451,12 +455,12 @@ stateDiagram-v2## 2.5 Requirements Traceability Matrix-| Requirement ID | Use Case | Test Case | Status |-|----------------|----------|-----------|--------|-| FR-SM-001 | UC-003 | TC-SM-001 | β Implemented |-| FR-SM-002 | UC-003 | TC-SM-002 | β Implemented |-| FR-MSG-001 | UC-001 | TC-MSG-001 | β Implemented |-| FR-WH-001 | UC-002 | TC-WH-001 | β Implemented |+| Requirement ID | Use Case | Test Case | Status |+| -------------- | -------- | ---------- | -------------- |+| FR-SM-001 | UC-003 | TC-SM-001 | β Implemented |+| FR-SM-002 | UC-003 | TC-SM-002 | β Implemented |+| FR-MSG-001 | UC-001 | TC-MSG-001 | β Implemented |+| FR-WH-001 | UC-002 | TC-WH-001 | β Implemented |## 2.6 Acceptance Criteria@@ -483,6 +487,7 @@ stateDiagram-v2β API key authentication worksβ Rate limiting is enabled```+---<div align="center">diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 9084317cc..286e350bc 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -11,38 +11,38 @@ flowchart TBC2[Dashboard]C3[n8n/Automation]end-+subgraph OpenWA["OpenWA Platform"]subgraph API["API Layer"]REST[REST API<br/>NestJS]WS[WebSocket<br/>Real-time]SWAGGER[Swagger<br/>Documentation]end-+subgraph Core["Core Services"]SM[Session<br/>Manager]MM[Message<br/>Manager]WH[Webhook<br/>Manager]QM[Queue<br/>Manager]end-+subgraph Engine["WhatsApp Engine (pluggable)"]WW[whatsapp-web.js<br/>Puppeteer/Chromium]BY[Baileys<br/>WebSocket/No browser]end-+subgraph Storage["Storage Layer"]DB[(Database<br/>PostgreSQL/SQLite)]REDIS[(Redis<br/>Cache/Queue)]FS[File Storage<br/>Media Files]endend-+subgraph External["External"]WA[WhatsApp<br/>Servers]WEBHOOK[Webhook<br/>Endpoints]end-+Clients --> APIAPI --> CoreCore --> Engine@@ -61,7 +61,7 @@ sequenceDiagramparticipant Engine as WA Engineparticipant DB as Databaseparticipant WA as WhatsApp-+Client->>API: Create SessionAPI->>SM: createSession()SM->>DB: Save session config@@ -108,12 +108,12 @@ flowchart TB**Key Principles:**-| Principle | Description | Example |-|-----------|-------------|---------|-| **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 |+| Principle | Description | Example |+| ------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |+| **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@@ -171,12 +171,12 @@ REST/webhook payloads, and plugins free of that, the **engine boundary is an antevery WhatsApp id an engine emits in a neutral field (`from` / `to` / `chatId` / `author`, contact andchat `id`) is reduced to one small **neutral dialect**:-| Neutral form | Meaning |-| --- | --- |-| `<phone>@c.us` | a user, by phone (the raw `@s.whatsapp.net` form folds into this) |-| `<id>@g.us` | a group |-| `<lid>@lid` | a user known **only** by privacy id - phone genuinely unknown (a first-class state) |-| `status@broadcast`, `<id>@newsletter`, `<id>@broadcast` | special channels |+| Neutral form | Meaning |+| ------------------------------------------------------- | ----------------------------------------------------------------------------------- |+| `<phone>@c.us` | a user, by phone (the raw `@s.whatsapp.net` form folds into this) |+| `<id>@g.us` | a group |+| `<lid>@lid` | a user known **only** by privacy id - phone genuinely unknown (a first-class state) |+| `status@broadcast`, `<id>@newsletter`, `<id>@broadcast` | special channels |Never `@s.whatsapp.net`, never a `:device` suffix. **Resolution rule:** prefer `@c.us` (resolve a lidto its phone when the mapping is known), and fall back to `@lid` only when it can't be resolved - an@@ -252,15 +252,17 @@ their respective modules.ConfigModule.forRoot({ isGlobal: true, load: [configuration], validate: validateEnv }),// Auth + audit β always SQLite- TypeOrmModule.forRootAsync({ name: 'main', /* ... ./data/main.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... */+ TypeOrmModule.forRootAsync({ name: 'data' /* ... */ }),++ CacheModule, // provides CacheService+ StorageModule, // provides StorageService+ EngineModule, // provides EngineFactory+ SessionModule,+ MessageModule,+ WebhookModule /* ...other feature modules... */,],})export class AppModule {}@@ -276,11 +278,11 @@ Services receive the backends by **constructor injection of the concrete class**export class SomeService {constructor(private readonly storage: StorageService, // branches local vs s3 internally- private readonly cache: CacheService, // Redis when enabled, else a no-op+ private readonly cache: CacheService, // Redis when enabled, else a no-op) {}async saveMedia(filePath: string, data: Buffer) {- await this.storage.putFile(filePath, data); // path-safety guarded+ await this.storage.putFile(filePath, data); // path-safety guardedawait this.cache.setSessionStatus('id', 'READY'); // no-op if Redis disabled}}@@ -304,20 +306,21 @@ sequenceDiagram### Backend Selection Matrix-| Environment | Database | Storage | Cache | Engine | Use Case |-|-------------|----------|---------|-------|--------|----------|-| **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 | 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 |+| Environment | Database | Storage | Cache | Engine | Use Case |+| ----------------------- | ---------- | -------- | -------- | --------------- | ------------------------- |+| **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 | 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 |### Hot-Swap Considerations> **Note:** Adapter hot-swap (changing adapter without restart) is **not supported** in v1.0. Changing adapter requires application restart.Future considerations for hot-swap:+- Graceful connection draining- State migration between adapters- Zero-downtime switching@@ -347,7 +350,7 @@ flowchart TBWS[WebSocket Gateways]SWAGGER[OpenAPI Docs]end-+subgraph Application["Application Layer"]direction LRSESS[Session Service]@@ -355,14 +358,14 @@ flowchart TBWH[Webhook Service]AUTH[Auth Service]end-+subgraph Domain["Domain Layer"]direction LRENT[Entities]REPO[Repository Interfaces]EVT[Domain Events]end-+subgraph Infrastructure["Infrastructure Layer"]direction LRDB[Database]@@ -370,7 +373,7 @@ flowchart TBENGINE[WA Engine]HTTP[HTTP Client]end-+Presentation --> ApplicationApplication --> DomainApplication --> Infrastructure@@ -454,7 +457,7 @@ classDiagram+getAllSessions(): Session[]+restoreSessions(): void}-+class Session {+id: string+name: string@@ -466,7 +469,7 @@ classDiagram+stop(): void+getQR(): string}-+class SessionStatus {<<enumeration>>CREATED@@ -477,7 +480,7 @@ classDiagramDISCONNECTEDFAILED}-+class WhatsAppEngine {<<interface>>+initialize(callbacks): Promise~void~@@ -486,7 +489,7 @@ classDiagram+getContacts(): Promise~Contact[]~+disconnect(): Promise~void~}-+SessionManager --> SessionSession --> SessionStatusSession --> WhatsAppEngine@@ -503,7 +506,7 @@ flowchart TBP1 --> E1[Engine Send]E1 --> R1[Response]end-+subgraph Inbound["Inbound Message Flow"]E2[Engine Event] --> P2[Process]P2 --> S2[Store]@@ -525,7 +528,7 @@ classDiagram+dispatch(event): void-deliverWithRetry(webhook, payload): void}-+class Webhook {+id: string+url: string@@ -535,7 +538,7 @@ classDiagram+retryCount: number+headers: Record}-+class WebhookPayload {+event: EventType+timestamp: Date@@ -543,7 +546,7 @@ classDiagram+data: any+signature: string}-+class EventType {<<enumeration>>MESSAGE_RECEIVED@@ -552,7 +555,7 @@ classDiagramSESSION_STATUSQR_CODE}-+WebhookManager --> WebhookWebhookManager --> WebhookPayloadWebhook --> EventType@@ -567,26 +570,26 @@ flowchart LRsubgraph Request["1. Request"]A[Client] -->|POST /messages| B[Controller]end-+subgraph Validation["2. Validation"]B --> C{Valid?}C -->|No| D[400 Error]C -->|Yes| E[Service]end-+subgraph Processing["3. Processing"]E --> F[Get Session]F --> G{Session Ready?}G -->|No| H[400 Error]G -->|Yes| I[Queue Job]end-+subgraph Execution["4. Execution"]I --> J[Worker]J --> K[Engine]K --> L[WhatsApp]end-+subgraph Response["5. Response"]L --> M[Success]M --> N[Store]@@ -622,19 +625,19 @@ flowchart TBNEST[NestJS Application]WW[whatsapp-web.js<br/>or Baileys]end-+subgraph Browser["Headless Browser (wwebjs only)"]CHROME[Chromium]end-+Node -.->|ENGINE_TYPE=whatsapp-web.js| Browserend-+subgraph External["External Services"]PG[(PostgreSQL)]RD[(Redis)]end-+Container --> External```@@ -677,14 +680,14 @@ flowchart LRG["/api/sessions/:sessionId/groups"]H["/api/health"]end-+subgraph Methods["HTTP Methods"]GETPOSTPUTDELETEend-+subgraph Format["Response Format"]JSON[JSON Response]ERR[Error Format]@@ -727,7 +730,7 @@ flowchart TBsubgraph External["External Request"]R[Request]end-+subgraph Security["Security Layers"]R --> HTTPS[HTTPS/TLS]HTTPS --> CORS[CORS Check]@@ -736,7 +739,7 @@ flowchart TBAUTH --> VAL[Input Validation]VAL --> APP[Application]end-+subgraph Internal["Internal Security"]APP --> ENC[Data Encryption]ENC --> LOG[Audit Logging]@@ -790,23 +793,23 @@ flowchart TBflowchart TBsubgraph Scaling["Scaling Strategy"]direction TB-+subgraph Stateless["Stateless Components"]API[API Servers]WORKER[Queue Workers]end-+subgraph Stateful["Stateful Components"]SESSION[Session Instances]end-+subgraph Shared["Shared State"]DB[(Database)]REDIS[(Redis)]S3[(Object Storage)]endend-+Stateless --> SharedStateful --> Shared```@@ -820,7 +823,7 @@ flowchart LRH -->|Yes| A[Route to Affinity]H -->|No| B[Round Robin]end-+A --> I1[Instance 1<br/>Session A, B]A --> I2[Instance 2<br/>Session C, D]B --> I1@@ -903,7 +906,7 @@ export interface EngineEventCallbacks {onMessageRevoked?: (message: RevokedMessage) => void;onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;- onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update+ onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.updateonCall?: (event: IncomingCallEvent) => void; // incoming call ringing; rejectCall() while it ringsonHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatchonDisconnected?: (reason: string) => void; // recoverable -> reconnect@@ -916,14 +919,14 @@ export interface IWhatsAppEngine {// 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)+ logout(): Promise<void>; // clear session (requires QR scan again)destroy(): Promise<void>;forceDestroy(): Promise<void>; // kill this engine's own resources, then graceful teardown// Status / authgetStatus(): EngineStatus;probeLiveness?(): Promise<boolean>; // optional active round-trip against the live connection- getQRCode(): string | null; // synchronous+ getQRCode(): string | null; // synchronousrequestPairingCode(phoneNumber: string): Promise<string>;getPhoneNumber(): string | null;getPushName(): string | null;@@ -1055,7 +1058,7 @@ export class WhatsAppWebJsAdapter implements IWhatsAppEngine {}private setupEventHandlers(): void {- this.client!.on('qr', (qr) => {+ this.client!.on('qr', qr => {this.setStatus(EngineStatus.QR_READY);this.callbacks.onQRCode?.(qr);});@@ -1063,11 +1066,11 @@ export class WhatsAppWebJsAdapter implements IWhatsAppEngine {this.setStatus(EngineStatus.READY);this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');});- this.client!.on('disconnected', (reason) => {+ this.client!.on('disconnected', reason => {this.setStatus(EngineStatus.DISCONNECTED);this.callbacks.onDisconnected?.(String(reason));});- this.client!.on('message', (message) => {+ this.client!.on('message', message => {this.callbacks.onMessage?.(this.toIncomingMessage(message)); // mapped to the neutral shape});}@@ -1120,7 +1123,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}private setupEventHandlers(): void {- this.socket!.ev.on('connection.update', (update) => {+ this.socket!.ev.on('connection.update', update => {const { connection, lastDisconnect, qr } = update;if (qr) {this.setStatus(EngineStatus.QR_READY);@@ -1176,21 +1179,21 @@ flowchart TBA[whatsapp-web.js\nPuppeteer-based\ndefault]A2[Baileys\nWebSocket-based\nENGINE_TYPE=baileys]end-+subgraph Risk["Risk Detection"]B{Protocol\nBreaking?}end-+subgraph Migration["Migration Path"]C[Update whatsapp-web.js]D[Switch to Baileys]E[Community Fork]end-+subgraph Resolution["Resolution"]F[Service Restored]end-+A --> BB -->|Minor| C --> FB -->|Major wwebjs| D --> F@@ -1199,16 +1202,16 @@ flowchart TB### Engine Comparison-| Feature | whatsapp-web.js | Baileys |-|---------|-----------------|---------|-| **Protocol** | Web (Puppeteer) | Native WebSocket |+| Feature | whatsapp-web.js | Baileys |+| ------------------ | --------------------- | ------------------- |+| **Protocol** | Web (Puppeteer) | Native WebSocket || **Resource Usage** | High (~500MB/session) | Low (~50MB/session) |-| **Stability** | Good | Good |-| **Community** | Large | Large |-| **Multi-device** | β | β |-| **QR Code** | β | β |-| **Phone Link** | β | β |-| **Maintenance** | Active | Active |+| **Stability** | Good | Good |+| **Community** | Large | Large |+| **Multi-device** | β | β |+| **QR Code** | β | β |+| **Phone Link** | β | β |+| **Maintenance** | Active | Active |### Benefits of Abstraction@@ -1262,12 +1265,12 @@ flowchart TB### Adapter Options-| Component | Options (`ENV`) | Default | Notes |-|-----------|---------|---------|-------|-| **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 (`S3_ENDPOINT` enables path-style) |-| **Cache** | Redis or disabled (`REDIS_ENABLED`) | Disabled | When disabled/unreachable, cache fails open (no-op) |+| Component | Options (`ENV`) | Default | Notes |+| ------------------- | ---------------------------------------- | --------------- | ------------------------------------------------------------ |+| **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 (`S3_ENDPOINT` enables path-style) |+| **Cache** | Redis or disabled (`REDIS_ENABLED`) | Disabled | When disabled/unreachable, cache fails open (no-op) |### 3.13.1 Storage Service@@ -1299,8 +1302,8 @@ export class StorageService {this.localPath = this.configService.get<string>('storage.localPath') || './data/media';if (this.storageType === 's3') {- const endpoint = process.env.S3_ENDPOINT; // optional: S3-compatible stores only- const accessKeyId = process.env.S3_ACCESS_KEY_ID; // legacy S3_ACCESS_KEY also read+ const endpoint = process.env.S3_ENDPOINT; // optional: S3-compatible stores only+ const accessKeyId = process.env.S3_ACCESS_KEY_ID; // legacy S3_ACCESS_KEY also readconst secretAccessKey = process.env.S3_SECRET_ACCESS_KEY;// Credentials alone are enough β AWS S3 derives its endpoint from the region.if (accessKeyId && secretAccessKey) {@@ -1320,12 +1323,16 @@ export class StorageService {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.putS3File(filePath, data) // keyed under media/<filePath>: this.putLocalFile(filePath, data);}- async getFile(filePath: string): Promise<Buffer> { /* mirrors putFile */ }- async listFiles(): Promise<string[]> { /* local recurse, or S3 ListObjectsV2 under media/ */ }+ 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}```@@ -1336,15 +1343,15 @@ OpenWA supports SQLite for lightweight deployments and PostgreSQL for high-volum#### Database Comparison-| Feature | SQLite | PostgreSQL |-|---------|--------|------------|-| **Setup** | Zero config | Requires server |-| **Concurrent writes** | Limited (1 writer) | Excellent |-| **Horizontal scaling** | β | β |-| **Table partitioning** | β | β |-| **Memory footprint** | ~10MB | ~100MB+ |-| **Backup** | Copy file | pg_dump |-| **Best for** | 1-5 sessions | 5+ sessions |+| Feature | SQLite | PostgreSQL |+| ---------------------- | ------------------ | --------------- |+| **Setup** | Zero config | Requires server |+| **Concurrent writes** | Limited (1 writer) | Excellent |+| **Horizontal scaling** | β | β |+| **Table partitioning** | β | β |+| **Memory footprint** | ~10MB | ~100MB+ |+| **Backup** | Copy file | pg_dump |+| **Best for** | 1-5 sessions | 5+ sessions |#### TypeORM Configuration@@ -1364,7 +1371,9 @@ const baseConfig = {if (dbType === 'postgres') {return {- ...baseConfig, name: 'data', type: 'postgres',+ ...baseConfig,+ name: 'data',+ type: 'postgres',host: configService.get('dataDatabase.host'),port: configService.get('dataDatabase.port'),username: configService.get('dataDatabase.username'),@@ -1379,7 +1388,9 @@ if (dbType === 'postgres') {// SQLite (default): migration-managed unless DATABASE_SYNCHRONIZE=trueconst synchronize = configService.get<boolean>('dataDatabase.synchronize', false);return {- ...baseConfig, name: 'data', type: 'better-sqlite3' as const, // DATABASE_TYPE=sqlite -> this driver+ ...baseConfig,+ name: 'data',+ type: 'better-sqlite3' as const, // DATABASE_TYPE=sqlite -> this driverdatabase: configService.get('dataDatabase.database', './data/openwa.sqlite'),synchronize,migrationsRun: !synchronize,@@ -1444,22 +1455,28 @@ export class CacheService implements OnModuleDestroy {}async isAvailable(): Promise<boolean> {- if (!this.enabled) return false; // disabled -> always "no cache"- this.ensureClient(); // create on first use; ioredis handles (re)connecting- return this.ping(); // reflects live state: false during an outage, true once back+ if (!this.enabled) return false; // disabled -> always "no cache"+ this.ensureClient(); // create on first use; ioredis handles (re)connecting+ return this.ping(); // reflects live state: false during an outage, true once back}// 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; }+ 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 */ }+ try {+ await this.redis!.setex(`session:${id}:status`, /* TTL */ 300, status);+ } catch {+ /* logged + swallowed */+ }}}```@@ -1492,11 +1509,11 @@ flowchart LRend```-| Profile | Database | Storage | Cache | Sessions | RAM | Use Case |-|---------|----------|---------|-------|----------|-----|----------|-| **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 |+| Profile | Database | Storage | Cache | Sessions | RAM | Use Case |+| -------------- | ---------- | -------- | ----- | -------- | ----- | --------------------- |+| **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 by default. Set `MAX_CONCURRENT_SESSIONS` to a positive integer> to cap concurrently running or initializing engines; the default `0` keeps the historical@@ -1576,11 +1593,11 @@ REDIS_PORT=6379OpenWA does not auto-detect a profile at runtime; pick one by available resources and expected load:-| 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 |+| 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 |All profiles still run as a single API instance per session-data volume (see Β§3.2). Enterprise heremeans more vertical headroom and external backends, not multi-replica clustering.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 4b4c7b4f5..ea4d2b044 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1244,11 +1244,11 @@ extra work is done.When enabled, two rules can refuse a send:-| Rule | What it means |-| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Warm-up daily cap | The session has used its allowance for the current **UTC** day. The allowance grows with the session's age (`SEND_PACING_WARMUP_SCHEDULE`), because a brand-new WhatsApp account that immediately sends at volume is the pattern that gets numbers banned. The count comes from the messages table, so it survives restarts. |-| Cold-reachout cap | The session has used its allowance of **new conversations** for the UTC day (`SEND_PACING_COLD_DAILY_CAP`). A send is a cold reachout when the account has no history with that chat in **either** direction β replying to someone who wrote to you first is never counted, and never refused by this rule. Status posts address no chat and are exempt. |-| Failure breaker | Consecutive send failures reached `SEND_PACING_BREAKER_THRESHOLD`, which usually means WhatsApp has already started refusing this account. The streak has no time decay β only a successful send resets it, so failures spread across a long quiet period still accumulate toward the threshold. Sends resume after `SEND_PACING_BREAKER_COOLDOWN_MS`, or immediately after any send succeeds. |+| Rule | What it means |+| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Warm-up daily cap | The session has used its allowance for the current **UTC** day. The allowance grows with the session's age (`SEND_PACING_WARMUP_SCHEDULE`), because a brand-new WhatsApp account that immediately sends at volume is the pattern that gets numbers banned. The count comes from the messages table, so it survives restarts. |+| Cold-reachout cap | The session has used its allowance of **new conversations** for the UTC day (`SEND_PACING_COLD_DAILY_CAP`). A send is a cold reachout when the account has no history with that chat in **either** direction β replying to someone who wrote to you first is never counted, and never refused by this rule. Status posts address no chat and are exempt. |+| Failure breaker | Consecutive send failures reached `SEND_PACING_BREAKER_THRESHOLD`, which usually means WhatsApp has already started refusing this account. The streak has no time decay β only a successful send resets it, so failures spread across a long quiet period still accumulate toward the threshold. Sends resume after `SEND_PACING_BREAKER_COOLDOWN_MS`, or immediately after any send succeeds. |A refusal is `429` with a body carrying **`code: "SEND_PACING_LIMITED"`** and `retryAfterSeconds`:diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.mdindex de23dd520..2866ab083 100644--- a/docs/08-development-guidelines.md+++ b/docs/08-development-guidelines.md@@ -148,17 +148,7 @@ export class ExampleModule {}```typescript// modules/example/example.controller.ts-import {- Controller,- Get,- Post,- Body,- Headers,- Param,- Delete,- HttpCode,- HttpStatus,-} from '@nestjs/common';+import { Controller, Get, Post, Body, Headers, Param, Delete, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { ExampleService } from './example.service';import { CreateExampleDto } from './dto/create-example.dto';@@ -175,7 +165,7 @@ export class ExampleController {@ApiResponse({ status: 201, type: ExampleResponseDto })async create(@Body() dto: CreateExampleDto,- @Headers('x-request-id') requestId?: string+ @Headers('x-request-id') requestId?: string,): Promise<ExampleResponseDto> {return this.exampleService.create(dto, { requestId });}@@ -202,7 +192,7 @@ resolve an engine directly from a controller. Engine-specific details belong behservices and engine adapters.A capability service reaches the live engine through `EngineRegistry`, the narrow port exported by-the (global) `EngineModule` β not through `SessionService`, which drives the session *lifecycle*+the (global) `EngineModule` β not through `SessionService`, which drives the session _lifecycle_(start/stop/delete/reconnect, owned by `SessionEngineLifecycle`) and should only be injected by codethat actually drives it:@@ -234,30 +224,27 @@ export class ExampleService {constructor(private readonly repository: ExampleRepository) {}- async create(- dto: CreateExampleDto,- context?: { requestId?: string }- ): Promise<Example> {+ async create(dto: CreateExampleDto, context?: { requestId?: string }): Promise<Example> {this.logger.log(`Creating example: ${dto.name}`, context);-+const example = this.repository.create(dto);return this.repository.save(example);}async findOne(id: string): Promise<Example> {const example = await this.repository.findOne({ where: { id } });-+if (!example) {throw new NotFoundException(`Example with ID ${id} not found`);}-+return example;}async remove(id: string): Promise<void> {const example = await this.findOne(id);await this.repository.remove(example);-+this.logger.log(`Deleted example: ${id}`);}}@@ -375,15 +362,18 @@ Fixes #456```markdown## Description+Brief description of changes## Type of Change+- [ ] Bug fix- [ ] New feature- [ ] Breaking change- [ ] Documentation update## Checklist+- [ ] Tests added/updated- [ ] Documentation updated- [ ] Lint passes@@ -392,6 +382,7 @@ Brief description of changes## Screenshots (if applicable)## Related Issues+Closes #```@@ -464,7 +455,7 @@ describe('App (e2e)', () => {return request(app.getHttpServer()).get('/api/health').expect(200)- .expect((res) => {+ .expect(res => {expect(res.body.status).toBe('ok');});});@@ -489,10 +480,10 @@ Coverage thresholds are enforced by Jest in `package.json`. Security-sensitive c### Code Documentation-```typescript+````typescript/*** Session service handles all session-related operations.- *+ ** @example* ```typescript* const session = await sessionService.create({ name: 'my-bot' });@@ -503,7 +494,7 @@ Coverage thresholds are enforced by Jest in `package.json`. Security-sensitive cexport class SessionService {/*** Creates a new WhatsApp session.- *+ ** @param dto - Session creation parameters* @returns The created session with QR code if applicable* @throws {ConflictException} If session name already exists@@ -513,7 +504,7 @@ export class SessionService {// Implementation}}-```+````### API Documentation (Swagger)@@ -559,15 +550,15 @@ Where a failure mode recurs across engines, `src/common/errors/` defines a namedthe NestJS exception carrying the right status, so throwing it from an adapter maps to the intendedHTTP code with no filter involved:-| Error | Extends | Status |-| --- | --- | --- |-| `EngineNotSupportedError` | `NotImplementedException` | 501 |-| `ChannelMediaNotSupportedError` | `NotImplementedException` | 501 |-| `EngineNotReadyError` | `ConflictException` | 409 |-| `EngineRefusedError` | `ForbiddenException` | 403 |-| `EngineTransportError` | `ServiceUnavailableException` | 503 |-| `ChatLabelsUnsupportedError` | `UnprocessableEntityException` | 422 |-| `CallNotFoundError` / `ChannelNotFoundError` / `GroupNotFoundError` / `MessageNotFoundError` | `NotFoundException` | 404 |+| Error | Extends | Status |+| -------------------------------------------------------------------------------------------- | ------------------------------ | ------ |+| `EngineNotSupportedError` | `NotImplementedException` | 501 |+| `ChannelMediaNotSupportedError` | `NotImplementedException` | 501 |+| `EngineNotReadyError` | `ConflictException` | 409 |+| `EngineRefusedError` | `ForbiddenException` | 403 |+| `EngineTransportError` | `ServiceUnavailableException` | 503 |+| `ChatLabelsUnsupportedError` | `UnprocessableEntityException` | 422 |+| `CallNotFoundError` / `ChannelNotFoundError` / `GroupNotFoundError` / `MessageNotFoundError` | `NotFoundException` | 404 |Add a new one only when the condition is engine-agnostic and recurs; a one-off stays an inline`throw new BadRequestException(...)`.@@ -807,7 +798,7 @@ export class MyService {// Log entry with contextconst requestId = this.request?.requestId;this.logger.log(`Processing item`, { id, requestId });-+try {await this.process(id);this.logger.log(`Item processed successfully`, { id, requestId });@@ -866,7 +857,7 @@ async function bootstrap() {const client = new Client({puppeteer: {headless: false, // See browser window- devtools: true, // Open DevTools automatically+ devtools: true, // Open DevTools automatically},});@@ -958,19 +949,13 @@ const contact2 = await getContact('id2');const contact3 = await getContact('id3');// β Good: Parallel execution-const [contact1, contact2, contact3] = await Promise.all([- getContact('id1'),- getContact('id2'),- getContact('id3'),-]);+const [contact1, contact2, contact3] = await Promise.all([getContact('id1'), getContact('id2'), getContact('id3')]);// β Good: Batch processing with concurrency limitimport pLimit from 'p-limit';const limit = pLimit(5); // Max 5 concurrent-const results = await Promise.all(- chatIds.map(id => limit(() => sendMessage(id, text)))-);+const results = await Promise.all(chatIds.map(id => limit(() => sendMessage(id, text))));```### Memory Management@@ -1005,6 +990,7 @@ export class EngineTeardownService {**Symptom:** Session stuck in 'initializing' status**Causes & Solutions:**+1. **Chrome/Puppeteer issue**- Ensure Chrome for Testing is installed: `ls /usr/local/bin/puppeteer-chrome`- Check Puppeteer args: `--no-sandbox --disable-setuid-sandbox`@@ -1019,6 +1005,7 @@ export class EngineTeardownService {## Session Disconnects Randomly**Causes & Solutions:**+1. **Memory pressure**- Monitor memory: `docker stats`- Increase container memory limit@@ -1034,12 +1021,13 @@ export class EngineTeardownService {### Database Issues-```markdown+````markdown## Connection Pool Exhausted**Symptom:** "too many clients already" error**Solution:**+```typescript// config/typeorm.config.ts{@@ -1052,12 +1040,14 @@ export class EngineTeardownService {},}```+````## Migration Fails**Symptom:** "relation already exists" error**Solution:**+```bash# Check migration statusnpm run migration:show@@ -1068,7 +1058,8 @@ npm run migration:revert# Regenerate migrationnpm run migration:generate --name=FixMigration```-```++````### TypeScript/NestJS Issues@@ -1092,17 +1083,19 @@ constructor(@Inject(forwardRef(() => SessionService))private readonly sessionService: SessionService,) {}-```+````## DI Token Not Found**Symptom:** "Nest can't resolve dependencies"**Solution:**+- Ensure provider is exported from its module- Check if module is imported where needed- Use @Injectable() decorator on services-```++````### Docker Issues@@ -1112,9 +1105,10 @@ constructor(**Check logs:**```bashdocker compose logs openwa-api --tail 100-```+````**Common causes:**+1. Missing environment variables2. Database not ready (use depends_on + healthcheck)3. Port already in use@@ -1122,18 +1116,21 @@ docker compose logs openwa-api --tail 100## Chrome Crashes in Docker**Solution:**+```dockerfile# Add shared memory sizedocker run --shm-size=2gb openwa```Or in docker-compose.yml:+```yamlservices:openwa-api:shm_size: '2gb'```-```++````## 8.12 Contributing Guide@@ -1149,7 +1146,7 @@ services:7. Commit: `git commit -m 'feat(scope): add amazing feature'`8. Push: `git push origin feature/amazing-feature`9. Open Pull Request-```+````### Code Review Checklist@@ -1168,6 +1165,7 @@ services:```markdown**Bug Report Template:**+- **Description:** Clear description of the bug- **Steps to Reproduce:** Numbered steps- **Expected Behavior:** What should happen@@ -1175,6 +1173,7 @@ services:- **Environment:** Node version, OS, Docker version- **Logs:** Relevant error logs```+---<div align="center">diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex d694cee32..c0eab4f15 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -32,35 +32,35 @@ npm --prefix dashboard run test:unit## 9.2 Test Commands-| Command | Purpose |-| ----------------------------------------------------------------- | ----------------------------------------------------------------------- |-| `npm test` | Run backend Jest unit tests from `src/` |-| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |-| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |-| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |-| `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test |-| `npm run test:scripts` | Run the repo-level script tests on the Node test runner |-| `./scripts/smoke-test-backup-restore.sh` | Run the backup/restore smoke test used by the `scripts-smoke` job |-| `npm run lint` | Run backend ESLint with type-aware rules |-| `npm run format:check` | Check Prettier formatting for backend source and specs |-| `npx tsc --noEmit -p tsconfig.json` | Type-check backend source, unit specs, and e2e specs |-| `npm run openapi:check` | Verify the committed OpenAPI snapshot |-| `npm run check:versions` | Verify documentation and package version consistency |-| `npm run check:dockerignore` | Verify the Docker build context that `.dockerignore` defines |-| `cd dashboard && npm run lint` | Run dashboard ESLint |-| `cd dashboard && npm run typecheck` | Type-check dashboard test files |-| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |-| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |-| `cd dashboard && npm run build` | Type-check and build the dashboard |-| `cd sdk/javascript && npm test && npm run typecheck` | Type-check and unit-test the JavaScript SDK |-| `cd sdk/javascript && npm run build && npm run smoke` | Build and dual CJS/ESM package-smoke the JavaScript SDK |-| `cd sdk/python && pytest` | Run the Python SDK tests |-| `cd sdk/php && ./vendor/bin/phpunit` | Run the PHP SDK tests |-| `cd sdk/java && mvn -B verify` | Run the Java SDK tests |-| `cd sdk/go && gofmt -l . && go vet ./... && go test -race ./...` | List unformatted files, vet, and race-test the Go SDK |-| `npm run test:scripts` | Run the install-script tests (`node --test scripts/postinstall.spec.js`) |-| `npm run check:dockerignore` | Verify `.dockerignore` still excludes what the image must not carry |-| `npm run check:versions` | Verify docs and Swagger track the `package.json` version |+| Command | Purpose |+| ---------------------------------------------------------------- | ------------------------------------------------------------------------ |+| `npm test` | Run backend Jest unit tests from `src/` |+| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |+| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |+| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |+| `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test |+| `npm run test:scripts` | Run the repo-level script tests on the Node test runner |+| `./scripts/smoke-test-backup-restore.sh` | Run the backup/restore smoke test used by the `scripts-smoke` job |+| `npm run lint` | Run backend ESLint with type-aware rules |+| `npm run format:check` | Check Prettier formatting for backend source and specs |+| `npx tsc --noEmit -p tsconfig.json` | Type-check backend source, unit specs, and e2e specs |+| `npm run openapi:check` | Verify the committed OpenAPI snapshot |+| `npm run check:versions` | Verify documentation and package version consistency |+| `npm run check:dockerignore` | Verify the Docker build context that `.dockerignore` defines |+| `cd dashboard && npm run lint` | Run dashboard ESLint |+| `cd dashboard && npm run typecheck` | Type-check dashboard test files |+| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |+| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |+| `cd dashboard && npm run build` | Type-check and build the dashboard |+| `cd sdk/javascript && npm test && npm run typecheck` | Type-check and unit-test the JavaScript SDK |+| `cd sdk/javascript && npm run build && npm run smoke` | Build and dual CJS/ESM package-smoke the JavaScript SDK |+| `cd sdk/python && pytest` | Run the Python SDK tests |+| `cd sdk/php && ./vendor/bin/phpunit` | Run the PHP SDK tests |+| `cd sdk/java && mvn -B verify` | Run the Java SDK tests |+| `cd sdk/go && gofmt -l . && go vet ./... && go test -race ./...` | List unformatted files, vet, and race-test the Go SDK |+| `npm run test:scripts` | Run the install-script tests (`node --test scripts/postinstall.spec.js`) |+| `npm run check:dockerignore` | Verify `.dockerignore` still excludes what the image must not carry |+| `npm run check:versions` | Verify docs and Swagger track the `package.json` version |## 9.3 Backend Unit Tests@@ -234,16 +234,16 @@ on broad integration coverage.Main CI is defined in `.github/workflows/ci.yml`.-| Job | Checks |-| --------------- | ----------------------------------------------------------------------------------------------- |+| Job | Checks |+| --------------- | ----------------------------------------------------------------------------------------------------------------------- || `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, .dockerignore context, OpenAPI snapshot |-| `audit` | dependency security audit |-| `test` | backend coverage run, script unit tests (node:test), e2e smoke tests, Codecov upload |-| `test-postgres` | real PostgreSQL 16 service, backend build, migration smoke, and PostgreSQL FTS provider spec |-| `dashboard` | dashboard install, lint, test type-check, unit tests, i18n parity, build |-| `scripts-smoke` | shellcheck on the backup/restore scripts plus the backup/restore smoke test |-| `build` | backend build after lint/audit/test/dashboard/scripts-smoke jobs pass |-| `docker` | multi-arch Docker build on pushes and pull requests; publish only where workflow permissions allow |+| `audit` | dependency security audit |+| `test` | backend coverage run, script unit tests (node:test), e2e smoke tests, Codecov upload |+| `test-postgres` | real PostgreSQL 16 service, backend build, migration smoke, and PostgreSQL FTS provider spec |+| `dashboard` | dashboard install, lint, test type-check, unit tests, i18n parity, build |+| `scripts-smoke` | shellcheck on the backup/restore scripts plus the backup/restore smoke test |+| `build` | backend build after lint/audit/test/dashboard/scripts-smoke jobs pass |+| `docker` | multi-arch Docker build on pushes and pull requests; publish only where workflow permissions allow |SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus servercontract surfaces that SDKs mirror (`src/**/dto/**`, `src/**/*.controller.ts`, `src/**/*.service.ts`, anddiff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex 2607ef3d8..4df668b03 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -18,11 +18,11 @@ flowchart TBsubgraph Development["Development"]DEV[Local Docker Compose]end-+subgraph Registry["Container Registry"]GHCR["GHCR branch / SHA / release tags"]end-+subgraph Deployment["Deployment (single server)"]PROXY[Reverse Proxy]PROXY --> APP[OpenWA - one instance]@@ -30,7 +30,7 @@ flowchart TBAPP --> REDIS[(Redis - optional)]APP --> VOL["Data volume (/app/data)"]end-+DEV --> |CI builds and pushes| GHCRGHCR --> |operator pulls| Deployment```@@ -138,7 +138,7 @@ services:target: buildercommand: npm run start:devports:- - "2785:2785"+ - '2785:2785'environment:- NODE_ENV=development- DATABASE_TYPE=postgres@@ -176,14 +176,14 @@ services:volumes:- postgres-data:/var/lib/postgresql/dataports:- - "5432:5432"+ - '5432:5432'redis:image: redis:7-alpinevolumes:- redis-data:/dataports:- - "6379:6379"+ - '6379:6379'# No separate dashboard service: the `app` image bundles the dashboard SPA and serves it# from the same port (2785) via NestJS. Open http://localhost:2785 for the UI.@@ -240,7 +240,7 @@ services:# this volume loses the linked WhatsApp sessions and the API keys.- openwa-data:/app/datahealthcheck:- test: ["CMD", "curl", "-f", "http://localhost:2785/api/health/ready"]+ test: ['CMD', 'curl', '-f', 'http://localhost:2785/api/health/ready']interval: 30stimeout: 10sretries: 3@@ -249,8 +249,8 @@ services:nginx:image: nginx:alpineports:- - "80:80"- - "443:443"+ - '80:80'+ - '443:443'volumes:- ./nginx.conf:/etc/nginx/nginx.conf:ro- ./certs:/etc/nginx/certs:ro@@ -300,16 +300,16 @@ an illustrative design sketch; the chart is the authoritative artifact.SHA image tags to GHCR; `latest` is deliberately not set there and moves only through the separate,boot-smoke-gated release workflow.-| Job | Needs | What it runs |-|-----|-------|--------------|-| `lint` | β | ESLint, `tsc --noEmit -p tsconfig.json` (full program, so spec files are type-checked too), `format:check`, `check:versions`, `check:dockerignore`, `openapi:check` |-| `audit` | β | `npm audit --audit-level=high`, split out of `lint` so a newly published advisory can't abort the code-quality gates |-| `test` | β | `npm test -- --coverage`, `test:scripts`, `test:e2e` (a `redis:7-alpine` service backs the queue-on e2e suite), coverage upload |-| `test-postgres` | β | `npm run build`, then `test:pg-smoke` (migrations + uuid-default) and the Postgres FTS migration spec against a `postgres:16-alpine` service |-| `dashboard` | β | In `dashboard/`: `lint`, `typecheck`, `i18n:check`, `build`, `test:unit` |-| `scripts-smoke` | β | `shellcheck` plus the backup/restore smoke test for `scripts/backup.sh` and `scripts/restore.sh` |-| `build` | lint, audit, test, dashboard, scripts-smoke | `npm run build`, uploads the `dist` artifact |-| `docker` | build, test-postgres | Buildx multi-arch build (`linux/amd64,linux/arm64`) with provenance + SBOM attestations; pushes to `ghcr.io/<owner>/<repo>` on push events (fork PRs build both architectures without publishing) |+| Job | Needs | What it runs |+| --------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `lint` | β | ESLint, `tsc --noEmit -p tsconfig.json` (full program, so spec files are type-checked too), `format:check`, `check:versions`, `check:dockerignore`, `openapi:check` |+| `audit` | β | `npm audit --audit-level=high`, split out of `lint` so a newly published advisory can't abort the code-quality gates |+| `test` | β | `npm test -- --coverage`, `test:scripts`, `test:e2e` (a `redis:7-alpine` service backs the queue-on e2e suite), coverage upload |+| `test-postgres` | β | `npm run build`, then `test:pg-smoke` (migrations + uuid-default) and the Postgres FTS migration spec against a `postgres:16-alpine` service |+| `dashboard` | β | In `dashboard/`: `lint`, `typecheck`, `i18n:check`, `build`, `test:unit` |+| `scripts-smoke` | β | `shellcheck` plus the backup/restore smoke test for `scripts/backup.sh` and `scripts/restore.sh` |+| `build` | lint, audit, test, dashboard, scripts-smoke | `npm run build`, uploads the `dist` artifact |+| `docker` | build, test-postgres | Buildx multi-arch build (`linux/amd64,linux/arm64`) with provenance + SBOM attestations; pushes to `ghcr.io/<owner>/<repo>` on push events (fork PRs build both architectures without publishing) |Rollout is left to the operator β the repo has no SSH deploy step, no staging/productionenvironments and no auto-deploy on merge.@@ -327,7 +327,7 @@ flowchart TBAPP --> RD[(Redis)]APP --> FS[File Storage]end-+Internet --> NGINX```@@ -343,24 +343,24 @@ flowchart TBsubgraph External["External"]CDN[CDN / CloudFlare]end-+subgraph LoadBalancer["Load Balancer"]LB[HAProxy / Nginx]end-+subgraph AppServers["Application Servers"]APP1[OpenWA 1]APP2[OpenWA 2]APP3[OpenWA N]end-+subgraph DataLayer["Data Layer"]PG[(PostgreSQL Primary)]PGR[(PostgreSQL Replica)]RD[(Redis Cluster)]S3[(S3 Storage)]end-+CDN --> LBLB --> APP1 & APP2 & APP3APP1 & APP2 & APP3 --> PG@@ -511,7 +511,10 @@ export default () => ({// API_MASTER_KEY is NOT part of this factory β `security` holds only trustedProxies, and the// master key is read straight from process.env by the auth service.security: {- trustedProxies: (process.env.TRUSTED_PROXIES || '').split(',').map(proxy => proxy.trim()).filter(Boolean),+ trustedProxies: (process.env.TRUSTED_PROXIES || '')+ .split(',')+ .map(proxy => proxy.trim())+ .filter(Boolean),},// Session data path and Puppeteer both live under `engine` β there is no top-level// `session` or `puppeteer` key.@@ -522,7 +525,9 @@ export default () => ({executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined,headless: process.env.PUPPETEER_HEADLESS !== 'false',// Split on commas AND whitespace; the default is a four-flag string, not an empty list- args: (process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu')+ args: (+ process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu'+ ).split(/[\s,]+/).filter(Boolean),},@@ -558,23 +563,23 @@ flowchart LRLOGS[Structured Logs]TRACES[Traces]end-+subgraph Collection["Collection"]PROM[Prometheus]LOKI[Loki]TEMPO[Tempo]end-+subgraph Visualization["Visualization"]GRAF[Grafana]end-+subgraph Alerting["Alerting"]AM[AlertManager]SLACK[Slack]EMAIL[Email]end-+METRICS --> PROM --> GRAFLOGS --> LOKI --> GRAFTRACES --> TEMPO --> GRAF@@ -601,7 +606,7 @@ services:- '--config.file=/etc/prometheus/prometheus.yml'- '--storage.tsdb.retention.time=30d'ports:- - "9090:9090"+ - '9090:9090'restart: unless-stoppedgrafana:@@ -614,7 +619,7 @@ services:- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:-admin}- GF_USERS_ALLOW_SIGN_UP=falseports:- - "3001:3000"+ - '3001:3000'depends_on:- prometheus- loki@@ -627,7 +632,7 @@ services:- loki-data:/lokicommand: -config.file=/etc/loki/local-config.yamlports:- - "3100:3100"+ - '3100:3100'restart: unless-stoppedpromtail:@@ -646,7 +651,7 @@ services:volumes:- ./monitoring/alertmanager.yml:/etc/alertmanager/alertmanager.ymlports:- - "9093:9093"+ - '9093:9093'restart: unless-stoppednode-exporter:@@ -659,7 +664,7 @@ services:- '--path.procfs=/host/proc'- '--path.sysfs=/host/sys'ports:- - "9100:9100"+ - '9100:9100'restart: unless-stoppedvolumes:@@ -722,8 +727,8 @@ groups:labels:severity: criticalannotations:- summary: "OpenWA service is down"- description: "The OpenWA application is not responding"+ summary: 'OpenWA service is down'+ description: 'The OpenWA application is not responding'# Session(s) disconnected- alert: SessionDisconnected@@ -732,8 +737,8 @@ groups:labels:severity: warningannotations:- summary: "WhatsApp session disconnected"- description: "{{ $value }} session(s) in disconnected state"+ summary: 'WhatsApp session disconnected'+ description: '{{ $value }} session(s) in disconnected state'# Failed messages currently stored- alert: FailedMessagesPresent@@ -742,8 +747,8 @@ groups:labels:severity: warningannotations:- summary: "Messages are failing"- description: "{{ $value }} message(s) are currently in FAILED state"+ summary: 'Messages are failing'+ description: '{{ $value }} message(s) are currently in FAILED state'# Process memory growth (app-exported RSS; ~2GB example threshold)- alert: HighProcessMemory@@ -752,8 +757,8 @@ groups:labels:severity: warningannotations:- summary: "High OpenWA process memory"- description: "RSS is {{ $value | humanize1024 }}B"+ summary: 'High OpenWA process memory'+ description: 'RSS is {{ $value | humanize1024 }}B'# Host memory pressure β EXTERNAL (node-exporter), not exported by OpenWA- alert: HighHostMemoryUsage@@ -764,8 +769,8 @@ groups:labels:severity: warningannotations:- summary: "High host memory usage"- description: "Host memory usage is {{ $value | humanizePercentage }}"+ summary: 'High host memory usage'+ description: 'Host memory usage is {{ $value | humanizePercentage }}'```### AlertManager Configuration@@ -815,16 +820,16 @@ receivers: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 |+| 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+@Public() // no API key required@SkipThrottle()export class HealthController {@Get()@@ -899,17 +904,17 @@ export class MetricsService {**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` | gauge | `direction` (`incoming`/`outgoing`) | Current stored messages by direction |-| `openwa_messages_failed_total` | gauge | β | Current messages in FAILED state |+| 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` | gauge | `direction` (`incoming`/`outgoing`) | Current stored messages by direction |+| `openwa_messages_failed_total` | gauge | β | Current messages in FAILED state |### Grafana Dashboard Definition@@ -923,41 +928,31 @@ export class MetricsService {"title": "Active Sessions","type": "stat","gridPos": { "x": 0, "y": 0, "w": 6, "h": 4 },- "targets": [- { "expr": "openwa_sessions_active" }- ]+ "targets": [{ "expr": "openwa_sessions_active" }]},{"title": "Stored Outgoing Messages","type": "stat","gridPos": { "x": 6, "y": 0, "w": 6, "h": 4 },- "targets": [- { "expr": "openwa_messages_total{direction=\"outgoing\"}" }- ]+ "targets": [{ "expr": "openwa_messages_total{direction=\"outgoing\"}" }]},{"title": "Failed Messages","type": "stat","gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 },- "targets": [- { "expr": "openwa_messages_failed_total" }- ]+ "targets": [{ "expr": "openwa_messages_failed_total" }]},{"title": "Sessions by Status","type": "timeseries","gridPos": { "x": 0, "y": 4, "w": 12, "h": 8 },- "targets": [- { "expr": "openwa_sessions", "legendFormat": "{{status}}" }- ]+ "targets": [{ "expr": "openwa_sessions", "legendFormat": "{{status}}" }]},{"title": "Stored Messages by Direction","type": "timeseries","gridPos": { "x": 12, "y": 4, "w": 12, "h": 8 },- "targets": [- { "expr": "openwa_messages_total", "legendFormat": "{{direction}}" }- ]+ "targets": [{ "expr": "openwa_messages_total", "legendFormat": "{{direction}}" }]},{"title": "Process Memory",@@ -972,9 +967,7 @@ export class MetricsService {"title": "Uptime","type": "stat","gridPos": { "x": 12, "y": 12, "w": 12, "h": 8 },- "targets": [- { "expr": "openwa_process_uptime_seconds" }- ]+ "targets": [{ "expr": "openwa_process_uptime_seconds" }]}]}@@ -1018,25 +1011,24 @@ export class MessageService {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"}` | Current stored outgoing messages | Unexpected change |-| **Messages** | `openwa_messages_total{direction="incoming"}` | Current stored incoming messages | Unexpected change |-| **Messages** | `openwa_messages_failed_total` | Current messages in FAILED state | Above acceptable threshold |-| **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) |+| 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"}` | Current stored outgoing messages | Unexpected change |+| **Messages** | `openwa_messages_total{direction="incoming"}` | Current stored incoming messages | Unexpected change |+| **Messages** | `openwa_messages_failed_total` | Current messages in FAILED state | Above acceptable threshold |+| **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### Backup Strategy@@ -1049,7 +1041,7 @@ flowchart TBCOMPRESS --> ENCRYPT[encrypt]ENCRYPT --> S3[S3 Storage]end-+subgraph Retention["Retention Policy"]D7[Daily: 7 days]W4[Weekly: 4 weeks]@@ -1080,12 +1072,12 @@ starting guidance**, not measured figures; actual usage depends heavily on engin(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 |-| 5-10 | 4GB | 4 cores | 50GB |-| 10-20 | 8GB | 8 cores | 100GB |-| 20+ | 16GB+ | 16+ cores | 200GB+ |+| Sessions | RAM | CPU | Storage |+| -------- | ----- | --------- | ------- |+| 1-5 | 2GB | 2 cores | 20GB |+| 5-10 | 4GB | 4 cores | 50GB |+| 10-20 | 8GB | 8 cores | 100GB |+| 20+ | 16GB+ | 16+ cores | 200GB+ |### Horizontal Scalingdiff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.mdindex b79cd2214..eb9c67395 100644--- a/docs/11-operational-runbooks.md+++ b/docs/11-operational-runbooks.md@@ -27,6 +27,7 @@ Each runbook follows this format:**Impact:** All sessions affected, messages not processing**Prerequisites:**+- SSH access to server- Docker CLI access- Database access@@ -108,6 +109,7 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \**Impact:** Single session affected**Prerequisites:**+- API Key- Physical access to phone (if QR needed)@@ -172,6 +174,7 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \**Impact:** Performance degradation, potential OOM**Prerequisites:**+- SSH access- Docker CLI@@ -237,6 +240,7 @@ as a delivery failure rather than retaining payloads without limit.**Impact:** External systems not receiving events**Prerequisites:**+- API Key- Access to webhook endpoint@@ -330,6 +334,7 @@ curl -H "X-API-Key: $API_KEY" \**Impact:** Service downtime during maintenance**Prerequisites:**+- Scheduled maintenance window- Backup verified- User notification sent@@ -405,6 +410,7 @@ curl -H "X-API-Key: $API_KEY" \**Impact:** Brief downtime during upgrade**Prerequisites:**+- Backup completed- Release notes reviewed- Breaking changes identified@@ -509,6 +515,7 @@ curl -H "X-API-Key: $API_KEY" http://localhost:2785/api/health**Impact:** None (online backup)**Prerequisites:**+- Sufficient disk space- Backup storage accessible@@ -578,6 +585,7 @@ tar -tzf ./backups/openwa-backup-*.tar.gz**Impact:** Service downtime during restore**Prerequisites:**+- Valid backup file- Sufficient disk space- SSH access@@ -635,14 +643,14 @@ curl -H "X-API-Key: $API_KEY" \### Alert Response Matrix-| Alert | Severity | Response Time | Runbook |-|-------|----------|---------------|---------|-| Service Down | Critical | 5 min | Service Down |-| High Memory | Warning | 30 min | High Memory Usage |-| Session Disconnected | Warning | 15 min | Session Disconnected |-| Webhook Failures > 5% | Warning | 30 min | Webhook Delivery Failure |-| Disk Space < 10% | Critical | 15 min | Disk Space Low |-| Certificate Expiry < 7 days | Warning | 24 hours | Certificate Renewal |+| Alert | Severity | Response Time | Runbook |+| --------------------------- | -------- | ------------- | ------------------------ |+| Service Down | Critical | 5 min | Service Down |+| High Memory | Warning | 30 min | High Memory Usage |+| Session Disconnected | Warning | 15 min | Session Disconnected |+| Webhook Failures > 5% | Warning | 30 min | Webhook Delivery Failure |+| Disk Space < 10% | Critical | 15 min | Disk Space Low |+| Certificate Expiry < 7 days | Warning | 24 hours | Certificate Renewal |### Runbook: Certificate Renewal@@ -772,6 +780,7 @@ External Contacts:- Domain registrar: [support email]- SSL provider: [support portal]```+---<div align="center">diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex f32d03fad..78cd7985b 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -131,6 +131,7 @@ RUN apt-get install -y ... curl ...### Issue: Container Won't Start**Symptoms:**+- `docker compose up` fails- Container exits immediately- "Port already in use" error@@ -163,8 +164,9 @@ docker compose up -d --build # `docker compose pull` never updates it### Issue: Dashboard Renders a Blank White Screen**Symptoms:**+- The API is healthy (`curl http://<host>:2785/api/health` returns `200`) but the dashboard is blank-- The startup log says `π₯οΈ Dashboard: serving bundled UI at β¦` β the UI *is* being served+- The startup log says `π₯οΈ Dashboard: serving bundled UI at β¦` β the UI _is_ being served- The browser console shows script-loading errors; DevTools β Network shows the `/assets/*.js`requests going to `https://` even though you opened the page over `http://`- You reach the instance directly over plain HTTP (a host:port allocation, a private network, a@@ -196,6 +198,7 @@ setting. If you are behind a TLS proxy, ignore that warning β the directive is### Issue: Session Won't Connect**Symptoms:**+- QR code generated but session stays `initializing`- Session ends in `failed` (with a `lastError`) after scanning the QR- Session stuck at `qr_ready` or `authenticating` and never reaches `ready`@@ -219,13 +222,13 @@ docker compose exec openwa-api ls -la /app/data/baileys/<name>/ # bai**Solutions:**-| Cause | Solution |-|-------|----------|-| Expired QR | Generate new QR (valid 60 seconds) |-| Auth folder corrupted | Delete and rescan |-| Browser crash | Restart container |-| Network issues | Check firewall/proxy |-| WhatsApp blocked | Set a per-session proxy (`proxyUrl`) |+| Cause | Solution |+| --------------------- | ------------------------------------ |+| Expired QR | Generate new QR (valid 60 seconds) |+| Auth folder corrupted | Delete and rescan |+| Browser crash | Restart container |+| Network issues | Check firewall/proxy |+| WhatsApp blocked | Set a per-session proxy (`proxyUrl`) |```bash# Clear auth and restart (the profile dir carries the session NAME, not its UUID id).@@ -244,12 +247,13 @@ docker compose restart openwa-apiProxy egress (if WhatsApp is blocked on your network) is configured **per session** via the`proxyUrl`/`proxyType` fields on `POST /api/sessions` β it is **not** an environment variable, and an-unreachable proxy silently blocks the WhatsApp WebSocket (see the *No QR code appears, or `/start`-returns `504`* entry below).+unreachable proxy silently blocks the WhatsApp WebSocket (see the _No QR code appears, or `/start`+returns `504`_ entry below).### Issue: No QR code appears, or `POST /api/sessions/:id/start` returns `504`**Symptoms:**+- `POST /api/sessions/:id/start` returns `504 Gateway Timeout`(`WhatsApp Web authentication timed out...`)- No QR code is ever produced β `GET /api/sessions/:id/qr` never has one@@ -281,8 +285,8 @@ curl -X POST "$BASE/api/sessions" -H "X-API-Key: $API_KEY" -H "Content-Type: appstuck. Often seen on ARM64 (e.g. Raspberry Pi) after upgrading to v0.2.x.**Cause:** whatsapp-web.js auto-selects a WhatsApp Web client version, and an incompatible version-stalls the post-link sync. (If you also see `chrome_crashpad_handler: --database is required` *and the-session never starts at all*, that is a different problem β see "Session fails to launch β¦" below.)+stalls the post-link sync. (If you also see `chrome_crashpad_handler: --database is required` _and the+session never starts at all_, that is a different problem β see "Session fails to launch β¦" below.)**Fix:** OpenWA reconciles a missed `ready` event when WhatsApp Web is connected, the injectedruntime is available, and whatsapp-web.js has populated the linked account identity. If your@@ -365,22 +369,23 @@ Failed to launch the browser process: Code: nulloften accompanied by a wall of `ERROR:dbus/bus.cc` / `crashpad ... /sys/devices/system/cpu/...` lines.**Those dbus/crashpad lines are non-fatal noise** that headless Chromium always prints inside a container βignore them. The actual signal is `Code: null`, which means the browser process was killed during startup-before it could report an exit code. The cause is *not* in the log β it's a host/container resource limit,+before it could report an exit code. The cause is _not_ in the log β it's a host/container resource limit,and there are three distinct ones. Diagnose which one before changing anything:**Cause A β per-container PID limit hit (most common under multi-session).**whatsapp-web.js runs a full Chromium instance per session, and Chromium is multi-process (browser + renderer-+ GPU + zygote + utilities); WhatsApp Web is itself process-heavy (service workers, iframes). A handful of-concurrent sessions can approach the container's `pids_limit`, and the next session's Chromium gets killed-mid-spawn when a `fork()` returns `EAGAIN`. This is silent in the log.-*Diagnose:* watch the PIDS column while you click **Start**:+- GPU + zygote + utilities); WhatsApp Web is itself process-heavy (service workers, iframes). A handful of+ concurrent sessions can approach the container's `pids_limit`, and the next session's Chromium gets killed+ mid-spawn when a `fork()` returns `EAGAIN`. This is silent in the log.++_Diagnose:_ watch the PIDS column while you click **Start**:```bashdocker stats openwa-api # watch the PIDS column β does it climb toward the limit right before the failure?```-*Fix:* raise the ceiling. The bundled `docker-compose.yml` exposes it as `OPENWA_PIDS_LIMIT` (default `2048`,+_Fix:_ raise the ceiling. The bundled `docker-compose.yml` exposes it as `OPENWA_PIDS_LIMIT` (default `2048`,which fits ~8-10 sessions with startup-spike headroom):```bash@@ -394,14 +399,14 @@ Do **not** set `-1` (unlimited) β the PID ceiling is a fork-bomb guard and shoThe container's `mem_limit` (or the host VM, e.g. Docker Desktop on macOS/Windows) ran out of RAM whileChromium was starting. The OOM killer sends `SIGKILL`, which Puppeteer reports as `Code: null`.-*Diagnose:* check the host kernel log for an OOM kill:+_Diagnose:_ check the host kernel log for an OOM kill:```bashdmesg -T | grep -i "killed process" # Linux host# Docker Desktop: check the VM via the app, or nudge OPENWA_MEM_LIMIT up and retry```-*Fix:* raise the ceiling (`OPENWA_MEM_LIMIT=4g` in your `.env`, or Docker Desktop β Settings β Resources β+_Fix:_ raise the ceiling (`OPENWA_MEM_LIMIT=4g` in your `.env`, or Docker Desktop β Settings β Resources βMemory for the VM).**Cause C β the XDG/crashpad home-dir crash.**@@ -411,8 +416,8 @@ immediately above this one for the fix. The bundled image already handles this;custom container that drops the `XDG_CONFIG_HOME` / `XDG_CACHE_HOME` setup or the writable `/tmp` tmpfs.**Cause D β Debian 12 OS Chromium SIGTRAP in non-root Pods.**-If `Code: null` happens on Kubernetes, and the host kernel logs or `dmesg` shows `Trace/breakpoint trap (core dumped)` with exit code 133, the underlying Debian 12 OS `chromium` package has crashed due to strict non-root or seccomp constraints (even with `--no-zygote` or `Unconfined` seccomp).-*Fix:* On amd64, do not use the `chromium` package from Debian's `apt` β it SIGTRAPs under strict non-root/seccomp. Instead, download Chrome for Testing via Puppeteer during the Docker build (`./node_modules/.bin/puppeteer browsers install '[email protected]'`) and point `PUPPETEER_EXECUTABLE_PATH` to it. (Chrome for Testing has no linux-arm64 build, so arm64 keeps Debian's `chromium`, which ships a native arm64 binary.) The official `Dockerfile` implements this mixed approach.+If `Code: null` happens on Kubernetes, and the host kernel logs or `dmesg` shows `Trace/breakpoint trap (core dumped)` with exit code 133, the underlying Debian 12 OS `chromium` package has crashed due to strict non-root or seccomp constraints (even with `--no-zygote` or `Unconfined` seccomp).+_Fix:_ On amd64, do not use the `chromium` package from Debian's `apt` β it SIGTRAPs under strict non-root/seccomp. Instead, download Chrome for Testing via Puppeteer during the Docker build (`./node_modules/.bin/puppeteer browsers install '[email protected]'`) and point `PUPPETEER_EXECUTABLE_PATH` to it. (Chrome for Testing has no linux-arm64 build, so arm64 keeps Debian's `chromium`, which ships a native arm64 binary.) The official `Dockerfile` implements this mixed approach.**Quick triage:** run `docker stats openwa-api`, click **Start**, and watch which resource spikes toward itslimit the instant before the failure β that tells you A vs B. If neither moves and you see the crashpad@@ -526,6 +531,7 @@ same stop β start clears it.### Issue: Frequent Disconnections**Symptoms:**+- Session disconnects every few hours- `disconnected` status in logs- Need to rescan QR frequently@@ -566,14 +572,15 @@ default 5000). `maxReconnectAttempts` is clamped to 0β20 β `0` disables autoleaving it unset means unlimited retries with the delay parking at a 1-hour cap. Subscribe to the`session.reconnect_loop` webhook to be alerted on every 5th consecutive attempt.-On a slow host, raise the first-boot init wait with `WWEBJS_AUTH_TIMEOUT_MS` (see *QR generation-times out on slow first boot* above).+On a slow host, raise the first-boot init wait with `WWEBJS_AUTH_TIMEOUT_MS` (see _QR generation+times out on slow first boot_ above).## 12.4 Messaging Issues### Issue: Messages Not Sending**Symptoms:**+- API returns 200 but message not delivered- "Message send failed" errors- Messages stuck in queue@@ -594,13 +601,13 @@ curl -H "X-API-Key: $API_KEY" \**Common Causes:**-| Cause | Symptom | Solution |-|-------|---------|----------|-| Invalid phone number | 400 error | Format: `[email protected]` |-| Rate limited | 429 error | Reduce sending rate |-| Session disconnected | 503 error | Reconnect session |-| Media too large | 413 error | Compress or reduce size |-| Number not on WhatsApp | Message fails silently | Verify number first |+| Cause | Symptom | Solution |+| ---------------------- | ---------------------- | --------------------------- |+| Invalid phone number | 400 error | Format: `[email protected]` |+| Rate limited | 429 error | Reduce sending rate |+| Session disconnected | 503 error | Reconnect session |+| Media too large | 413 error | Compress or reduce size |+| Number not on WhatsApp | Message fails silently | Verify number first |**Phone Number Validation:**@@ -622,7 +629,7 @@ curl -H "X-API-Key: $API_KEY" \**Symptoms:**-- `POST /api/sessions/{id}/messages/send-text` returns `{"statusCode":500,"message":"Internal server error"}` β but the message *is* delivered+- `POST /api/sessions/{id}/messages/send-text` returns `{"statusCode":500,"message":"Internal server error"}` β but the message _is_ delivered- Logs show `the engine returned no message for this send, so it may not have been delivered`- Unrelated operations fail with the minified error `r: r`: `GET /api/sessions/{id}/chats`, media downloads, typing indicators- Startup logs may contain `The installed whatsapp-web.js is missing the message-id backportβ¦`@@ -655,6 +662,7 @@ rm -rf node_modules/whatsapp-web.js && npm ci### Issue: Media Upload Fails**Symptoms:**+- "File too large" error- "Unsupported media type" error- Upload timeout@@ -697,6 +705,7 @@ curl -X POST http://localhost:2785/api/sessions/{id}/messages/send-image \### Issue: Webhook Not Receiving Messages**Symptoms:**+- Messages received but webhook not triggered- Webhook URL returns errors- Duplicate webhook calls@@ -747,6 +756,7 @@ WEBHOOK_RETRY_DELAY=5000 # base retry backoff in ms (default 5000)### Issue: High Memory Usage**Symptoms:**+- Container using > 1GB RAM per session- OOM (Out of Memory) kills- Slow response times@@ -780,15 +790,16 @@ services:**Memory Optimization Tips:**-| Optimization | Impact | Trade-off |-|--------------|--------|-----------|-| Reduce message history | -20% RAM | Less searchable history |-| Headless Chrome flags | -15% RAM (wwebjs only) | None |-| Limit concurrent sessions | Linear | Fewer sessions |+| Optimization | Impact | Trade-off |+| ------------------------- | ---------------------- | ----------------------- |+| Reduce message history | -20% RAM | Less searchable history |+| Headless Chrome flags | -15% RAM (wwebjs only) | None |+| Limit concurrent sessions | Linear | Fewer sessions |### Issue: Slow API Response**Symptoms:**+- API takes > 1 second to respond- Timeout errors- High latency for simple operations@@ -839,6 +850,7 @@ REDIS_PORT=6379### Issue: Database Locked (SQLite)**Symptoms:**+- "SQLITE_BUSY" errors- "database is locked" messages- Write operations failing@@ -876,6 +888,7 @@ flowchart TD### Issue: Database Migration Failed**Symptoms:**+- "Migration failed" errors- Schema mismatch- Missing tables@@ -904,6 +917,7 @@ npm run migration:run:main### Issue: Volume Permissions**Symptoms:**+- "Permission denied" errors- Can't write to data directory- Auth files not persisting@@ -927,6 +941,7 @@ services:### Issue: Container Networking**Symptoms:**+- Can't connect to database container- Webhook calls fail from container- "Connection refused" errors@@ -940,7 +955,7 @@ services:networks:- openwa-networkextra_hosts:- - "host.docker.internal:host-gateway" # Access host from container+ - 'host.docker.internal:host-gateway' # Access host from containerpostgres:networks:@@ -962,14 +977,18 @@ docker exec openwa-api curl http://host.docker.internal:8080### General Questions**Q: Is OpenWA safe to use?**+> A: OpenWA uses unofficial WhatsApp Web API. While we implement best practices to avoid detection, there's inherent risk of account restrictions. We recommend:+>> - Use dedicated phone number (not personal)> - Don't send spam or bulk unsolicited messages> - Follow WhatsApp's Terms of Service> - Implement rate limiting**Q: How many sessions can I run?**+> A: Depends on your server resources and the engine in use. With the default `whatsapp-web.js` engine (Chromium-based), each session uses ~300-500MB RAM:+>> - 2GB RAM: 3-5 sessions> - 4GB RAM: 8-10 sessions> - 8GB RAM: 15-20 sessions@@ -977,10 +996,13 @@ docker exec openwa-api curl http://host.docker.internal:8080> With `ENGINE_TYPE=baileys` (browser-free), RAM per session is significantly lower β you can run more sessions on the same hardware. Exact figures depend on message volume and group membership.**Q: Can I use WhatsApp Business account?**+> A: Yes, OpenWA works with both personal and WhatsApp Business accounts. Note that WhatsApp Business API (official Meta API) is different and not supported.**Q: How to avoid getting banned?**+> Best practices:+>> - Don't send > 200 messages/day for new numbers> - Gradually increase volume> - Avoid identical messages to multiple recipients@@ -990,6 +1012,7 @@ docker exec openwa-api curl http://host.docker.internal:8080### Technical Questions**Q: How to send messages to groups?**+```bash# Get group listcurl -H "X-API-Key: $API_KEY" \@@ -1006,6 +1029,7 @@ curl -X POST http://localhost:2785/api/sessions/{id}/messages/send-text \```**Q: How to handle message replies?**+```bash# Reply to specific messagecurl -X POST http://localhost:2785/api/sessions/{id}/messages/reply \@@ -1019,13 +1043,16 @@ curl -X POST http://localhost:2785/api/sessions/{id}/messages/reply \```**Q: How to use with n8n?**+> 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/send-text`> 3. Add header: `X-API-Key: your-key`> 4. Configure webhook trigger for incoming messages**Q: How to run behind reverse proxy (nginx)?**+```nginx# nginx.confserver {@@ -1093,6 +1120,7 @@ entryPoints:Remember OpenWA is **single-port**: the Dashboard, REST API, and Socket.IO all share `:2785` behind one router, so a choked upstream takes all three down at once. A Dashboard stuck on "Connectingβ¦" while `localhost` is healthy is the proxy hop, not the app.**Q: How to backup sessions automatically?**+```bash# Add to crontab, for example: 0 */6 * * * cd /path/to/openwa && ./scripts/backup.shBACKUP_DIR=/backups/openwa ./scripts/backup.sh@@ -1105,42 +1133,44 @@ retention/encryption to completed archives externally; see the [backup and resto### Webhook Questions**Q: What events can I subscribe to?**+```yamlavailable_events:# Messages- - 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- - message.edited # Message body or media caption edited+ - 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+ - message.edited # Message body or media caption edited# Status- - status.received # A contact posted a status/story (opt-in: must be listed explicitly or via "*")+ - status.received # A contact posted a status/story (opt-in: must be listed explicitly or via "*")# Session- - session.status # Session status change- - session.qr # New QR code generated- - session.authenticated # Session authenticated- - session.disconnected # Session disconnected+ - session.status # Session status change+ - session.qr # New QR code generated+ - session.authenticated # Session authenticated+ - session.disconnected # Session disconnected- session.reconnect_loop # Every 5th consecutive reconnect attempt (payload: sessionId, attempts, nextDelayMs)- - session.restriction # WhatsApp restricted the account, or lifted it (payload: sessionId, active, kind, code, expiresAt)- - presence.update # A subscribed chat's presence changed (payload: sessionId, chatId, participants, groupOnlineCount)- - call.accepted # A ringing call was answered (Baileys only; payload: sessionId, callId, from, outcome, isVideo, isGroup, timestamp)- - call.rejected # A ringing call was declined (Baileys only)- - call.missed # A ringing call was never picked up (Baileys only)+ - session.restriction # WhatsApp restricted the account, or lifted it (payload: sessionId, active, kind, code, expiresAt)+ - presence.update # A subscribed chat's presence changed (payload: sessionId, chatId, participants, groupOnlineCount)+ - call.accepted # A ringing call was answered (Baileys only; payload: sessionId, callId, from, outcome, isVideo, isGroup, timestamp)+ - call.rejected # A ringing call was declined (Baileys only)+ - call.missed # A ringing call was never picked up (Baileys only)# Groups- - group.join # Participant(s) added/joined- - group.leave # Participant(s) left/removed- - group.update # Group subject/description/announce/locked changed+ - group.join # Participant(s) added/joined+ - group.leave # Participant(s) left/removed+ - group.update # Group subject/description/announce/locked changed# Calls- - call.received # Incoming call ringing (payload: callId, from, isVideo, isGroup, timestamp)+ - call.received # Incoming call ringing (payload: callId, from, isVideo, isGroup, timestamp)```**Q: Webhook payload format?**+```json{"event": "message.received",@@ -1167,17 +1197,17 @@ available_events:### HTTP Error Codes-| Code | Meaning | Common Cause | Solution |-|------|---------|--------------|----------|-| 400 | Bad Request | Invalid parameters | Check request body/params |-| 401 | Unauthorized | Missing/invalid API key | Add X-API-Key header |-| 403 | Forbidden | Insufficient permissions | Check API key permissions |-| 404 | Not Found | Invalid session/endpoint | Verify session exists |-| 409 | Conflict | Session already exists | Use different session ID |-| 413 | Payload Too Large | File too large | Reduce file size |-| 429 | Too Many Requests | Rate limited | Reduce request rate |-| 500 | Internal Error | Server error | Check logs |-| 503 | Service Unavailable | Session disconnected | Reconnect session |+| Code | Meaning | Common Cause | Solution |+| ---- | ------------------- | ------------------------ | ------------------------- |+| 400 | Bad Request | Invalid parameters | Check request body/params |+| 401 | Unauthorized | Missing/invalid API key | Add X-API-Key header |+| 403 | Forbidden | Insufficient permissions | Check API key permissions |+| 404 | Not Found | Invalid session/endpoint | Verify session exists |+| 409 | Conflict | Session already exists | Use different session ID |+| 413 | Payload Too Large | File too large | Reduce file size |+| 429 | Too Many Requests | Rate limited | Reduce request rate |+| 500 | Internal Error | Server error | Check logs |+| 503 | Service Unavailable | Session disconnected | Reconnect session |### Error Body Shape@@ -1207,6 +1237,7 @@ When creating GitHub issue, include:```markdown## Environment+- OpenWA version: x.x.x- Docker version: x.x.x- OS: Ubuntu 22.04 / macOS / Windows@@ -1214,28 +1245,35 @@ When creating GitHub issue, include:- Sessions count: X## Issue Description+[Clear description of the problem]## Steps to Reproduce+1. Step one2. Step two3. ...## Expected Behavior+[What should happen]## Actual Behavior+[What actually happens]## Logs```+[Paste relevant logs here]-```++````## Configuration```yaml# Sanitized docker-compose.yml or .env-```+````+```### Community Resources@@ -1251,3 +1289,4 @@ When creating GitHub issue, include:[β 11 - Operational Runbooks](./11-operational-runbooks.md) Β· [Documentation Index](./README.md) Β· [Next: 13 - Horizontal Scaling Guide β](./13-horizontal-scaling.md)</div>+```diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.mdindex e0f5ad72a..0eb6b14f7 100644--- a/docs/14-migration-guide.md+++ b/docs/14-migration-guide.md@@ -221,12 +221,12 @@ REDIS_USERNAME=optionalREDIS_PASSWORD=optional```-| Scenario | Support | Notes |-| ------------------------- | ------- | ----------------------------------------- |-| Built-in β External Redis | β | Config change only |-| External β Built-in Redis | β | Config change only |+| Scenario | Support | Notes |+| ------------------------- | ------- | ------------------------------------------ |+| Built-in β External Redis | β | Config change only |+| External β Built-in Redis | β | Config change only || Enable β Disable Redis | β | Cache no-ops; reads fall through to the DB |-| Disable β Enable Redis | β | Cache rebuilds automatically |+| Disable β Enable Redis | β | Cache rebuilds automatically |> [!TIP]> **Cache Warm-up**: After switching Redis instances, the cache will automatically rebuild as requests come in. No data migration is necessary.@@ -703,13 +703,13 @@ docker compose run --rm openwa-api npm run migration:run:prod### Known Upgrade Hazards-| Release | Change | Action |-| -------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| Release | Change | Action |+| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `0.12.0` | `PUT /api/plugins/:id/sessions` is a full replacement of the global activation set and now requires an **unrestricted ADMIN** key; a session-scoped key is rejected with `403` whatever it sends | Switch any automation that drives global plugin activation from a scoped key to an unrestricted ADMIN key. The per-session config override route `PUT /api/plugins/:id/config/:sessionId` is unaffected and stays scoped to the addressed session |-| `0.8.15` | PostgreSQL schemas bootstrapped with `DATABASE_SYNCHRONIZE=true` crash-loop on boot | Self-healing guard migration; see [14.9](#149-troubleshooting-migration-issues) for the large-table window |-| `0.9.0` | `GET /api/settings` no longer returns the always-zero `general.sessionTimeout` | Remove reads of that field β there is no replacement |-| `0.10.3` | Boolean/numeric request fields are parsed strictly (`1`, `yes`, `""` now `400`) | Send canonical JSON values; JSON clients and the SDKs are unaffected |-| `0.10.3` | Status posts pass the `message:sending` plugin gate, with no `chatId` in the input | Branch on `source`/`type` before reading `input.chatId` |+| `0.8.15` | PostgreSQL schemas bootstrapped with `DATABASE_SYNCHRONIZE=true` crash-loop on boot | Self-healing guard migration; see [14.9](#149-troubleshooting-migration-issues) for the large-table window |+| `0.9.0` | `GET /api/settings` no longer returns the always-zero `general.sessionTimeout` | Remove reads of that field β there is no replacement |+| `0.10.3` | Boolean/numeric request fields are parsed strictly (`1`, `yes`, `""` now `400`) | Send canonical JSON values; JSON clients and the SDKs are unaffected |+| `0.10.3` | Status posts pass the `message:sending` plugin gate, with no `chatId` in the input | Branch on `source`/`type` before reading `input.chatId` |The authoritative list is `CHANGELOG.md`; breaking items are flagged there with β οΈ **Breaking**.diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.mdindex fce6412e6..793b9cce1 100644--- a/docs/15-project-roadmap.md+++ b/docs/15-project-roadmap.md@@ -54,35 +54,35 @@ timeline### Release Summary-| Version | Focus | Status |-| ------- | ---------------------------------------------------------- | ----------- |-| v0.0.1 | MVP - Basic API | β Released |-| v0.0.2 | Production Ready | β Released |-| v0.1.0 | Initial Stable Release | β Released |-| v0.1.7 | Maintenance & fixes | β Released |-| v0.1.8 | Maintenance & fixes | β Released |-| v0.2.0 | i18n, Real-time Chats & Hardening | β Released |-| v0.2.1 | Dashboard split-origin fix | β Released |-| v0.2.2 | Security hardening (SSRF, secrets, Prometheus metrics) | β Released |-| v0.2.3 | Plain-HTTP / LAN dashboard fixes | β Released |-| v0.2.4 | CORS LAN fix, pinnable WA-Web version | β Released |-| v0.2.5 | Pairing-code linking | β Released |-| v0.2.6 | Chromium hardened-container (read-only) fix | β Released |-| v0.2.7 | Typing simulation, delete-chat, engine-agnostic groundwork | β Released |-| v0.2.8 | Engine decoupling (ack/type/JID), templates, @lidβphone | β Released |-| v0.2.9 | Reliability/security/a11y hardening (RBAC, deps, shutdown, retention) | β Released |-| v0.2.10 | Dashboard/CI follow-ups (MessageTester JID, neutral MessageType, qemu v4) | β Released |-| v0.3.0 | Engine pluggability (Baileys engine, plugin layer) | β Released |-| v0.4.0 | Single-port deployment (dashboard on API port, Traefik removed) | β Released |-| v0.5.x | Plugin/dashboard hardening and SDK/docs increments | β Released |-| v0.6.x | Operational hardening, API surface refinements, dashboard follow-ups | β Released |-| v0.7.x | Dashboard chat UX, infra backup/restore, media-download toggle, infra follow-ups | β Released |-| v0.8.x | Integration Fabric provisioning (instance API + dashboard tab), Java & Go SDKs | β Released |-| v0.9.0 | Live message-edit events; `general.sessionTimeout` dropped from settings | β Released |-| v0.10.x | Chat `kind` discriminator, 24-hour status store, Docker Hub dual-publish | β Released |-| v0.11.0 | SDK poll / profile-picture / status-media coverage, security & reliability hardening | β Released |+| Version | Focus | Status |+| ------- | ---------------------------------------------------------------------------------------------------- | ----------- |+| v0.0.1 | MVP - Basic API | β Released |+| v0.0.2 | Production Ready | β Released |+| v0.1.0 | Initial Stable Release | β Released |+| v0.1.7 | Maintenance & fixes | β Released |+| v0.1.8 | Maintenance & fixes | β Released |+| v0.2.0 | i18n, Real-time Chats & Hardening | β Released |+| v0.2.1 | Dashboard split-origin fix | β Released |+| v0.2.2 | Security hardening (SSRF, secrets, Prometheus metrics) | β Released |+| v0.2.3 | Plain-HTTP / LAN dashboard fixes | β Released |+| v0.2.4 | CORS LAN fix, pinnable WA-Web version | β Released |+| v0.2.5 | Pairing-code linking | β Released |+| v0.2.6 | Chromium hardened-container (read-only) fix | β Released |+| v0.2.7 | Typing simulation, delete-chat, engine-agnostic groundwork | β Released |+| v0.2.8 | Engine decoupling (ack/type/JID), templates, @lidβphone | β Released |+| v0.2.9 | Reliability/security/a11y hardening (RBAC, deps, shutdown, retention) | β Released |+| v0.2.10 | Dashboard/CI follow-ups (MessageTester JID, neutral MessageType, qemu v4) | β Released |+| v0.3.0 | Engine pluggability (Baileys engine, plugin layer) | β Released |+| v0.4.0 | Single-port deployment (dashboard on API port, Traefik removed) | β Released |+| v0.5.x | Plugin/dashboard hardening and SDK/docs increments | β Released |+| v0.6.x | Operational hardening, API surface refinements, dashboard follow-ups | β Released |+| v0.7.x | Dashboard chat UX, infra backup/restore, media-download toggle, infra follow-ups | β Released |+| v0.8.x | Integration Fabric provisioning (instance API + dashboard tab), Java & Go SDKs | β Released |+| v0.9.0 | Live message-edit events; `general.sessionTimeout` dropped from settings | β Released |+| v0.10.x | Chat `kind` discriminator, 24-hour status store, Docker Hub dual-publish | β Released |+| v0.11.0 | SDK poll / profile-picture / status-media coverage, security & reliability hardening | β Released || v0.12.x | Session/engine decomposition (`EngineRegistry`), plugin lifecycle and configuration-precedence fixes | β Released |-| v1.0.0 | Enterprise Ready (K8s Operator, multi-tenant) | π Planned |+| v1.0.0 | Enterprise Ready (K8s Operator, multi-tenant) | π Planned |> SDK / docs-site / observability features are delivered **incrementally** as they're additive β they no> longer gate a single version. The five client SDKs landed this way across `0.7.3`β`0.8.19`; the docs@@ -473,11 +473,11 @@ gantt#### Scaling & Infrastructure-| Feature | Priority | Status |-| ------------------ | -------- | ------ |-| Horizontal scaling | P2 | π Design reference only; single active owner per session remains required |+| Feature | Priority | Status |+| ------------------ | -------- | --------------------------------------------------------------------------- |+| Horizontal scaling | P2 | π Design reference only; single active owner per session remains required || Session affinity | P2 | π Documented for future topology, not implemented as multi-replica runtime |-| Security audit | P0 | β |+| Security audit | P0 | β |#### Community & Tooling@@ -570,27 +570,27 @@ vars are removed. Ships with a migration guide.Delivered additively whenever ready, per SemVer (not gated to one version). Prometheus metrics shippedin `0.2.2` and the five client SDKs across `0.7.3`β`0.8.19`; the rest remain open.-| 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 |-| Java SDK | P2 | β Shipped (`com.rmyndharis:openwa`) | Java client library |-| Go SDK | P2 | β Shipped (`github.com/rmyndharis/OpenWA/sdk/go`) | Go 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 |+| 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 |+| Java SDK | P2 | β Shipped (`com.rmyndharis:openwa`) | Java client library |+| Go SDK | P2 | β Shipped (`github.com/rmyndharis/OpenWA/sdk/go`) | Go 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 | Status | Description |-| ---------------------- | -------- | ------ | -------------------------------- |+| 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 |+| 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 |### Integration Fabric β inbound integrations for plugins (in progress)@@ -605,13 +605,13 @@ through a stable, versioned **Integration SDK (v1)**. Motivated by #553.Delivered in phases (additive; see [25 - Integration Fabric](./25-integration-fabric.md) for thearchitecture and design rationale):-| Phase | Scope | Status |-| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |-| P0 | Core substrate: inbound webhook RPC, `@Public` ingress endpoint with HMAC-over-raw-body verification, plugin-instance primitive, normalized send capability, identity/dedup/DLQ tables, ingress queue. SDK v1 frozen. | β Merged (internal substrate) |-| P1 | Scale-correctness: per-conversation FIFO ordering, per-instance fairness, DLQ redrive, bot/human handover. | β Merged (internal substrate) |-| P2 | Operator provisioning (mint plugin instances and secrets, dashboard) + the first adapter (helpdesk inbox) shipped as a marketplace plugin β closes #553 end-to-end. | β Shipped (provisioning `0.8.0`; adapter needs `0.8.7`+) |-| P3 | A second ingress adapter β validates the substrate generalizes beyond the first consumer. | β Shipped (`supabase-otp-hook`) |-| P4 | Developer experience: SDK reference docs, compatibility test suite, multi-node routing. | π Planned |+| Phase | Scope | Status |+| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |+| P0 | Core substrate: inbound webhook RPC, `@Public` ingress endpoint with HMAC-over-raw-body verification, plugin-instance primitive, normalized send capability, identity/dedup/DLQ tables, ingress queue. SDK v1 frozen. | β Merged (internal substrate) |+| P1 | Scale-correctness: per-conversation FIFO ordering, per-instance fairness, DLQ redrive, bot/human handover. | β Merged (internal substrate) |+| P2 | Operator provisioning (mint plugin instances and secrets, dashboard) + the first adapter (helpdesk inbox) shipped as a marketplace plugin β closes #553 end-to-end. | β Shipped (provisioning `0.8.0`; adapter needs `0.8.7`+) |+| P3 | A second ingress adapter β validates the substrate generalizes beyond the first consumer. | β Shipped (`supabase-otp-hook`) |+| P4 | Developer experience: SDK reference docs, compatibility test suite, multi-node routing. | π Planned |> **Provisioning is operator-facing since `0.8.0`.** An ADMIN key mints a per-plugin instance and its> ingress secret through `POST /api/integration/plugins/:pluginId/instances`, and rotates that secret@@ -628,13 +628,13 @@ architecture and design rationale):### v1.0.0 - Enterprise Ready-| Feature | Priority | Description |-| ------------------- | -------- | ------------------------------ |-| Kubernetes Operator | P3 | Native K8s deployment |-| Multi-tenant | P3 | Enterprise SaaS features |-| Encryption at rest | P2 | Full data encryption |-| Audit compliance | P2 | SOC2, GDPR compliance |-| WhatsApp Pay | P3 | Payment links integration |+| Feature | Priority | Description |+| ------------------- | -------- | ------------------------- |+| Kubernetes Operator | P3 | Native K8s deployment |+| Multi-tenant | P3 | Enterprise SaaS features |+| Encryption at rest | P2 | Full data encryption |+| Audit compliance | P2 | SOC2, GDPR compliance |+| WhatsApp Pay | P3 | Payment links integration |## 15.7 Cutting a Release@@ -779,26 +779,26 @@ a no-op for OpenWA itself.### Phase 2 Success Criteria-| Metric | Target | Actual | Type |-| --------------------- | ------------ | ----------------- | -------- |-| Multi-session support | 10+ sessions | β Achieved | Internal |-| Dashboard functional | All features | β Achieved | Internal |-| PostgreSQL stable | β | β Achieved | Internal |-| Webhook delivery rate | > 99% | β Achieved | Internal |+| Metric | Target | Actual | Type |+| --------------------- | ------------ | ---------------------------------------------------- | -------- |+| Multi-session support | 10+ sessions | β Achieved | Internal |+| Dashboard functional | All features | β Achieved | Internal |+| PostgreSQL stable | β | β Achieved | Internal |+| Webhook delivery rate | > 99% | β Achieved | Internal || Test coverage | > 70% | β οΈ 66.87% line coverage; 80% improvement plan active | Internal |-| GitHub stars | 100+ | π Pending | External |+| GitHub stars | 100+ | π Pending | External |### Phase 3 Success Criteria-| Metric | Target | Actual | Type |-| ----------------------------- | ------- | ----------------- | -------- |-| Feature parity with WAHA Plus | 90%+ | β Achieved | Internal |-| API response time (p95) | < 200ms | β Achieved | Internal |+| Metric | Target | Actual | Type |+| ----------------------------- | ------- | ------------------------------------ | -------- |+| Feature parity with WAHA Plus | 90%+ | β Achieved | Internal |+| API response time (p95) | < 200ms | β Achieved | Internal || Test coverage | > 80% | β οΈ 66.87% line coverage; in progress | Internal |-| Documentation coverage | 100% | β 95%+ | Internal |-| Production users | 50+ | π Pending | External |-| GitHub stars | 500+ | π Pending | External |-| Community contributors | 5+ | π Pending | External |+| Documentation coverage | 100% | β 95%+ | Internal |+| Production users | 50+ | π Pending | External |+| GitHub stars | 500+ | π Pending | External |+| Community contributors | 5+ | π Pending | External |---diff --git a/docs/16-risk-management.md b/docs/16-risk-management.mdindex 6473dc749..df4484b75 100644--- a/docs/16-risk-management.md+++ b/docs/16-risk-management.md@@ -7,12 +7,12 @@ quadrantCharttitle Risk Assessment Matrixx-axis Low Impact --> High Impacty-axis Low Probability --> High Probability-+quadrant-1 Monitorquadrant-2 Criticalquadrant-3 Low Priorityquadrant-4 Mitigate-+WhatsApp Protocol Change: [0.8, 0.7]Account Ban: [0.6, 0.5]Security Breach: [0.9, 0.3]@@ -25,18 +25,19 @@ quadrantChart### R001: WhatsApp Protocol Changes-| Attribute | Value |-|-----------|-------|-| **ID** | R001 |-| **Category** | Technical |+| Attribute | Value |+| --------------- | ---------- |+| **ID** | R001 |+| **Category** | Technical || **Probability** | High (70%) |-| **Impact** | High |-| **Risk Level** | Critical |+| **Impact** | High |+| **Risk Level** | Critical |**Description:**WhatsApp can change their Web protocol at any time, which can cause the `whatsapp-web.js` library to stop working.**Indicators:**+- Spike in `whatsapp-web.js` issues- Sudden increase in error rates- Authentication failures@@ -49,7 +50,7 @@ flowchart TBR --> M2[Implement abstraction layer]R --> M3[Prepare alternative engines]R --> M4[Quick response plan]-+M1 --> A1[Watch releases & issues]M2 --> A2[Engine interface pattern]M3 --> A3[Baileys engine available - ENGINE_TYPE env]@@ -57,6 +58,7 @@ flowchart TB```**Action Items:**+1. Subscribe to `whatsapp-web.js` releases2. Engine abstraction layer β implemented (pluggable `ENGINE_TYPE`: `whatsapp-web.js` default, `baileys` alternative)3. Document fallback procedures@@ -66,18 +68,19 @@ flowchart TB### R002: User Account Banned-| Attribute | Value |-|-----------|-------|-| **ID** | R002 |-| **Category** | Operational |+| Attribute | Value |+| --------------- | ------------ |+| **ID** | R002 |+| **Category** | Operational || **Probability** | Medium (50%) |-| **Impact** | Medium |-| **Risk Level** | Medium |+| **Impact** | Medium |+| **Risk Level** | Medium |**Description:**WhatsApp users can be banned for using unofficial APIs or behavior detected as spam.**Indicators:**+- User reports of banned accounts- Sudden disconnections- QR code fails for specific numbers@@ -90,7 +93,7 @@ flowchart TBR --> M2[User education]R --> M3[Built-in safeguards]R --> M4[Clear disclaimers]-+M1 --> A1[Rate limiting defaults]M2 --> A2[Documentation & warnings]M3 --> A3[Human-like delays]@@ -103,7 +106,7 @@ flowchart TB// src/modules/message/bulk-message.service.ts β bulk-send pacing defaultsconst options = {delayBetweenMessages: dto.options?.delayBetweenMessages ?? 3000, // 3s (DTO range 1000β60000)- randomizeDelay: dto.options?.randomizeDelay ?? true, // adds 0β2s jitter per message+ randomizeDelay: dto.options?.randomizeDelay ?? true, // adds 0β2s jitter per messagestopOnError: dto.options?.stopOnError ?? false,};```@@ -129,6 +132,7 @@ gateway enforces.## Anti-Ban Best Practices### DO β+- Warm up new numbers (normal usage for 1-2 weeks)- Use realistic delays between messages- Personalize messages (avoid identical content)@@ -136,6 +140,7 @@ gateway enforces.- Use residential proxies if needed### DON'T β+- Send bulk messages to unknown numbers- Use identical message templates- Send >100 messages/day on new numbers@@ -147,18 +152,19 @@ gateway enforces.### R003: Security Breach-| Attribute | Value |-|-----------|-------|-| **ID** | R003 |-| **Category** | Security |+| Attribute | Value |+| --------------- | --------- |+| **ID** | R003 |+| **Category** | Security || **Probability** | Low (30%) |-| **Impact** | Critical |-| **Risk Level** | High |+| **Impact** | Critical |+| **Risk Level** | High |**Description:**Security vulnerabilities may lead to unauthorized access to sessions, data, or infrastructure.**Potential Vectors:**+- API key leakage- SQL injection- Insecure session storage@@ -172,7 +178,7 @@ flowchart TBR --> M2[Regular audits]R --> M3[Dependency scanning]R --> M4[Incident response plan]-+M1 --> A1[Input validation, encryption]M2 --> A2[Quarterly security review]M3 --> A3[Automated npm audit]@@ -185,6 +191,7 @@ flowchart TB## Security Review Checklist### Code Security+- [ ] Input validation on all endpoints- [ ] Parameterized database queries- [ ] API key hashing (never plain storage)@@ -192,6 +199,7 @@ flowchart TB- [ ] No secrets in codebase### Infrastructure Security+- [ ] HTTPS enforced- [ ] Security headers configured- [ ] Rate limiting enabled@@ -199,6 +207,7 @@ flowchart TB- [ ] Access logs enabled### Dependency Security+- [ ] npm audit clean- [ ] Dependabot alerts reviewed- [ ] Dependencies up to date@@ -213,7 +222,7 @@ flowchart TBA --> |Critical| C1[Immediate Response]A --> |High| C2[4-hour Response]A --> |Medium| C3[24-hour Response]-+C1 --> R1[Isolate affected systems]R1 --> R2[Patch vulnerability]R2 --> R3[Notify affected users]@@ -224,18 +233,19 @@ flowchart TB### R004: Maintainer Burnout-| Attribute | Value |-|-----------|-------|-| **ID** | R004 |-| **Category** | Organizational |-| **Probability** | Medium (40%) |-| **Impact** | Medium |-| **Risk Level** | Medium |+| Attribute | Value |+| --------------- | -------------- |+| **ID** | R004 |+| **Category** | Organizational |+| **Probability** | Medium (40%) |+| **Impact** | Medium |+| **Risk Level** | Medium |**Description:**An open-source project can stagnate if maintainers burn out or lack time.**Indicators:**+- Increasing response time to issues- PR review delays- Reduced commit frequency@@ -249,7 +259,7 @@ flowchart TBR --> M2[Documentation]R --> M3[Automation]R --> M4[Contributor onboarding]-+M1 --> A1[Active Discord/forum]M2 --> A2[Comprehensive docs]M3 --> A3[CI/CD automation]@@ -282,13 +292,13 @@ flowchart TB### R005: Dependency Vulnerabilities-| Attribute | Value |-|-----------|-------|-| **ID** | R005 |-| **Category** | Technical |+| Attribute | Value |+| --------------- | ---------- |+| **ID** | R005 |+| **Category** | Technical || **Probability** | High (60%) |-| **Impact** | Medium |-| **Risk Level** | Medium |+| **Impact** | Medium |+| **Risk Level** | Medium |**Description:**Dependencies (`whatsapp-web.js`, Puppeteer, NestJS, etc.) may have vulnerabilities or breaking changes.@@ -303,7 +313,7 @@ name: Security Scanon:schedule:- - cron: '0 0 * * *' # Daily+ - cron: '0 0 * * *' # Dailypush:branches: [main]@@ -312,10 +322,10 @@ jobs:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4-+- name: npm auditrun: npm audit --audit-level=high-+- name: Snyk scanuses: snyk/actions/node@masterenv:@@ -324,27 +334,27 @@ jobs:**Dependency Management Policy:**-| Action | Frequency |-|--------|-----------|-| npm audit (`--audit-level=high`, dedicated `audit` job in CI) | Every push / PR |-| Trivy image scan (`CRITICAL,HIGH`, `.trivyignore`) | Every release |-| Snyk scan | Not configured (planned) |-| Dependabot PRs (npm: `/` and `/dashboard`; docker) | Weekly |-| Dependabot PRs (github-actions) | Monthly |-| Major updates | Reviewed manually |-| Security patches | Immediate |+| Action | Frequency |+| ------------------------------------------------------------- | ------------------------ |+| npm audit (`--audit-level=high`, dedicated `audit` job in CI) | Every push / PR |+| Trivy image scan (`CRITICAL,HIGH`, `.trivyignore`) | Every release |+| Snyk scan | Not configured (planned) |+| Dependabot PRs (npm: `/` and `/dashboard`; docker) | Weekly |+| Dependabot PRs (github-actions) | Monthly |+| Major updates | Reviewed manually |+| Security patches | Immediate |---### R006: Legal/Compliance Issues-| Attribute | Value |-|-----------|-------|-| **ID** | R006 |-| **Category** | Legal |+| Attribute | Value |+| --------------- | --------- |+| **ID** | R006 |+| **Category** | Legal || **Probability** | Low (20%) |-| **Impact** | Critical |-| **Risk Level** | Medium |+| **Impact** | Critical |+| **Risk Level** | Medium |**Description:**WhatsApp/Meta may take legal action against unofficial APIs, or users may misuse the system for illegal activities.@@ -356,12 +366,13 @@ WhatsApp/Meta may take legal action against unofficial APIs, or users may misuse```markdown## Disclaimer-This project is not affiliated with, authorized, maintained,+This project is not affiliated with, authorized, maintained,sponsored or endorsed by WhatsApp or any of its affiliates.This is an independent and unofficial software. Use at your own risk.By using this software, you agree that:+1. You will not use it for spam or illegal activities2. You are responsible for compliance with local laws3. The maintainers are not liable for any misuse@@ -386,7 +397,7 @@ flowchart TBM4[Dependency Status]M5[Community Activity]end-+subgraph Thresholds["Alert Thresholds"]T1[Issues > 50 open]T2[Error > 5%]@@ -394,7 +405,7 @@ flowchart TBT4[Outdated > 30 days]T5[No PR > 14 days]end-+Metrics --> Thresholds --> Alert[Alert & Review]```@@ -406,26 +417,30 @@ flowchart TB### Date: YYYY-MM-DD### Technical Risks+- [ ] whatsapp-web.js status: ___- [ ] Error rate trend: ___- [ ] Security scan results: ___- [ ] Dependency updates needed: ___### Operational Risks+- [ ] User ban reports: ___- [ ] Support ticket volume: ___- [ ] Performance issues: ___### Community Health+- [ ] Open issues: ___- [ ] Open PRs: ___- [ ] New contributors: ___- [ ] Response time (avg): ___### Actions Needed-1. ___-2. ___-3. ___++1. ***+2. ***+3. ***```## 16.4 Contingency Plans@@ -437,7 +452,7 @@ flowchart TBT[Trigger: Protocol Change] --> A1[Assess Impact]A1 --> |Minor| M1[Wait for library update]A1 --> |Major| M2[Activate contingency]-+M2 --> C1[Notify users]C1 --> C2[Switch to maintenance mode]C2 --> C3[Evaluate alternatives]@@ -477,18 +492,21 @@ Hour 8-24:## Project Handover Checklist### Documentation+- [ ] Architecture documented- [ ] All decisions logged- [ ] Deployment procedures- [ ] Credentials inventory### Access+- [ ] GitHub owner transfer- [ ] npm publish rights- [ ] Domain ownership- [ ] Cloud accounts### Knowledge Transfer+- [ ] Codebase walkthrough- [ ] Known issues list- [ ] Roadmap handover@@ -499,13 +517,13 @@ Hour 8-24:### R007: Rate Limiting & WhatsApp Throttling-| Attribute | Value |-|-----------|-------|-| **ID** | R007 |-| **Category** | Operational |-| **Probability** | High (70%) |-| **Impact** | Medium |-| **Risk Level** | Medium |+| Attribute | Value |+| --------------- | ----------- |+| **ID** | R007 |+| **Category** | Operational |+| **Probability** | High (70%) |+| **Impact** | Medium |+| **Risk Level** | Medium |**Description:**WhatsApp has undocumented internal rate limits. Sending too many messages can trigger temporary blocks or permanent bans.@@ -515,15 +533,15 @@ WhatsApp has undocumented internal rate limits. Sending too many messages can trThe gateway enforces HTTP request throttling (`@nestjs/throttler`, registered globally as`ProxyAwareThrottlerGuard` and tracked per client IP) plus the bulk-send pacing described in R002:-| Control | Default | Scope |-|---------|---------|-------|-| `RATE_LIMIT_SHORT_TTL` / `RATE_LIMIT_SHORT_LIMIT` | 1000 ms / 10 requests | HTTP burst window |-| `RATE_LIMIT_MEDIUM_TTL` / `RATE_LIMIT_MEDIUM_LIMIT` | 60000 ms / 100 requests | HTTP sustained window |-| `RATE_LIMIT_LONG_TTL` / `RATE_LIMIT_LONG_LIMIT` | 3600000 ms / 1000 requests | HTTP hourly window |-| `delayBetweenMessages` / `randomizeDelay` | 3000 ms + 0β2 s jitter | Bulk send, between consecutive messages inside a batch |-| `BULK_MAX_CONCURRENT_BATCHES` | 50 (`0` = unlimited) | Concurrent bulk batches per process |-| `@ArrayMaxSize(100)` on `SendBulkMessageDto.messages` | 100 messages (hard limit) | Messages accepted per bulk request |-| `SIMULATE_TYPING` / `SIMULATE_TYPING_MAX_MS` | on / 5000 ms | Typing pause, text sends only (`send-text` / `send-template`) |+| Control | Default | Scope |+| ----------------------------------------------------- | -------------------------- | ------------------------------------------------------------- |+| `RATE_LIMIT_SHORT_TTL` / `RATE_LIMIT_SHORT_LIMIT` | 1000 ms / 10 requests | HTTP burst window |+| `RATE_LIMIT_MEDIUM_TTL` / `RATE_LIMIT_MEDIUM_LIMIT` | 60000 ms / 100 requests | HTTP sustained window |+| `RATE_LIMIT_LONG_TTL` / `RATE_LIMIT_LONG_LIMIT` | 3600000 ms / 1000 requests | HTTP hourly window |+| `delayBetweenMessages` / `randomizeDelay` | 3000 ms + 0β2 s jitter | Bulk send, between consecutive messages inside a batch |+| `BULK_MAX_CONCURRENT_BATCHES` | 50 (`0` = unlimited) | Concurrent bulk batches per process |+| `@ArrayMaxSize(100)` on `SendBulkMessageDto.messages` | 100 messages (hard limit) | Messages accepted per bulk request |+| `SIMULATE_TYPING` / `SIMULATE_TYPING_MAX_MS` | on / 5000 ms | Typing pause, text sends only (`send-text` / `send-template`) |These bound API traffic and bulk pacing β they are **not** per-session WhatsApp send caps. Thegateway does not count messages per minute, hour or day per session, so staying inside WhatsApp's@@ -532,24 +550,24 @@ operator-side monitoring, not values the gateway enforces.**Monitoring Metrics:**-| Metric | Warning Threshold | Critical Threshold |-|--------|-------------------|--------------------|-| Messages per minute | > 15 | > 25 |-| Failed sends | > 5% | > 15% |-| Connection drops | > 2/hour | > 5/hour |-| QR re-auth requests | > 1/day | > 3/day |+| Metric | Warning Threshold | Critical Threshold |+| ------------------- | ----------------- | ------------------ |+| Messages per minute | > 15 | > 25 |+| Failed sends | > 5% | > 15% |+| Connection drops | > 2/hour | > 5/hour |+| QR re-auth requests | > 1/day | > 3/day |---### R008: Data Loss-| Attribute | Value |-|-----------|-------|-| **ID** | R008 |-| **Category** | Technical |+| Attribute | Value |+| --------------- | --------- |+| **ID** | R008 |+| **Category** | Technical || **Probability** | Low (20%) |-| **Impact** | High |-| **Risk Level** | Medium |+| **Impact** | High |+| **Risk Level** | Medium |**Mitigation Strategy:**@@ -576,11 +594,11 @@ flowchart TB**Backup Coverage:**-| Data Type | Frequency | Retention | Storage |-|-----------|-----------|-----------|---------|+| Data Type | Frequency | Retention | Storage |+| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- || Databases (`main.sqlite` plus the data store, or a `pg_dump` when `DATABASE_TYPE=postgres`) | Each operator-run of `scripts/backup.sh` β the repo ships no scheduled backup | Whatever the operator keeps; the script never prunes | One `openwa-backup-<timestamp>.tar.gz` under `BACKUP_DIR` (default `./backups`) β local disk, no object-storage upload |-| Session auth state | On change | Indefinite | Filesystem β `SESSION_DATA_PATH` (default `./data/sessions`), `BAILEYS_AUTH_DIR` (default `./data/baileys`) |-| Configuration | On change | Indefinite | Git |+| Session auth state | On change | Indefinite | Filesystem β `SESSION_DATA_PATH` (default `./data/sessions`), `BAILEYS_AUTH_DIR` (default `./data/baileys`) |+| Configuration | On change | Indefinite | Git |> Session auth state is **not** in the database: whatsapp-web.js `LocalAuth` writes under> `SESSION_DATA_PATH` and Baileys writes multi-file auth state under `BAILEYS_AUTH_DIR/<sessionId>`.@@ -594,12 +612,12 @@ flowchart TB### Severity Levels-| Level | Description | Response Time | Notification |-|-------|-------------|---------------|--------------|-| **P1 - Critical** | System down, data breach | < 15 minutes | Phone + Slack |-| **P2 - High** | Major feature broken | < 1 hour | Slack + Email |-| **P3 - Medium** | Feature degraded | < 4 hours | Slack |-| **P4 - Low** | Minor issue | < 24 hours | GitHub Issue |+| Level | Description | Response Time | Notification |+| ----------------- | ------------------------ | ------------- | ------------- |+| **P1 - Critical** | System down, data breach | < 15 minutes | Phone + Slack |+| **P2 - High** | Major feature broken | < 1 hour | Slack + Email |+| **P3 - Medium** | Feature degraded | < 4 hours | Slack |+| **P4 - Low** | Minor issue | < 24 hours | GitHub Issue |### Escalation Flow@@ -631,14 +649,14 @@ flowchart TB```yaml# Example PagerDuty/Opsgenie configurationschedule:- name: "OpenWA On-Call"+ name: 'OpenWA On-Call'rotation:- week: 1- primary: "developer-a"- secondary: "developer-b"+ primary: 'developer-a'+ secondary: 'developer-b'- week: 2- primary: "developer-b"- secondary: "developer-a"+ primary: 'developer-b'+ secondary: 'developer-a'escalation:- level: 1@@ -685,6 +703,7 @@ flowchart LR## Weekly Risk Report - Week XX### Summary+- Overall Risk Status: π’ Green / π‘ Yellow / π΄ Red- New Risks Identified: X- Risks Mitigated: X@@ -692,11 +711,11 @@ flowchart LR### KRI Status-| KRI | Target | Actual | Status |-|-----|--------|--------|--------|-| Error Rate | < 1% | X.XX% | π’/π‘/π΄ |-| Uptime | > 99.5% | XX.XX% | π’/π‘/π΄ |-| Response Time | < 500ms | XXXms | π’/π‘/π΄ |+| KRI | Target | Actual | Status |+| ------------- | ------- | ------ | -------- |+| Error Rate | < 1% | X.XX% | π’/π‘/π΄ |+| Uptime | > 99.5% | XX.XX% | π’/π‘/π΄ |+| Response Time | < 500ms | XXXms | π’/π‘/π΄ |### Top Risks This Week@@ -706,12 +725,13 @@ flowchart LR### Dependencies Update-| Dependency | Current | Latest | CVEs | Action |-|------------|---------|--------|------|--------|-| whatsapp-web.js | X.X.X | X.X.X | 0 | OK |-| puppeteer | X.X.X | X.X.X | 0 | OK |+| Dependency | Current | Latest | CVEs | Action |+| --------------- | ------- | ------ | ---- | ------ |+| whatsapp-web.js | X.X.X | X.X.X | 0 | OK |+| puppeteer | X.X.X | X.X.X | 0 | OK |### Action Items+- [ ] Action 1- [ ] Action 2```@@ -720,16 +740,16 @@ flowchart LR## 16.8 Risk Summary-| ID | Risk | Probability | Impact | Level | Status |-|----|------|-------------|--------|-------|--------|-| R001 | Protocol Changes | High | High | π΄ Critical | Monitoring |-| R002 | Account Ban | Medium | Medium | π‘ Medium | Partially mitigated |-| R003 | Security Breach | Low | Critical | π‘ Medium | Mitigated |-| R004 | Maintainer Burnout | Medium | Medium | π‘ Medium | Planning |-| R005 | Dependency Issues | High | Medium | π‘ Medium | Automated |-| R006 | Legal Issues | Low | Critical | π‘ Medium | Mitigated |-| R007 | Rate Limiting | High | Medium | π‘ Medium | Partially mitigated |-| R008 | Data Loss | Low | High | π‘ Medium | Mitigated |+| ID | Risk | Probability | Impact | Level | Status |+| ---- | ------------------ | ----------- | -------- | ----------- | ------------------- |+| R001 | Protocol Changes | High | High | π΄ Critical | Monitoring |+| R002 | Account Ban | Medium | Medium | π‘ Medium | Partially mitigated |+| R003 | Security Breach | Low | Critical | π‘ Medium | Mitigated |+| R004 | Maintainer Burnout | Medium | Medium | π‘ Medium | Planning |+| R005 | Dependency Issues | High | Medium | π‘ Medium | Automated |+| R006 | Legal Issues | Low | Critical | π‘ Medium | Mitigated |+| R007 | Rate Limiting | High | Medium | π‘ Medium | Partially mitigated |+| R008 | Data Loss | Low | High | π‘ Medium | Mitigated |### Risk Trend@@ -741,6 +761,7 @@ xychart-betabar [65, 55, 45, 40, 35, 30]line [65, 55, 45, 40, 35, 30]```+---<div align="center">diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex a9c89477a..85ee0c0a9 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -2,15 +2,15 @@## 18.1 Overview-OpenWA ships five 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 drift in what an SDK *sends* is caught at test time rather than in production. That mechanism says nothing about what an SDK expects *back*; see Β§18.6 for how response shapes are held to the contract.+OpenWA ships five 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 drift in what an SDK _sends_ is caught at test time rather than in production. That mechanism says nothing about what an SDK expects _back_; see Β§18.6 for how response shapes are held to the contract.-| 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+ |-| Java | [`com.rmyndharis:openwa`](https://central.sonatype.com/artifact/com.rmyndharis/openwa) | Maven Central | Sync, `java.net.http`. See [`sdk/java/README.md`](../sdk/java/README.md). |-| Go | [`github.com/rmyndharis/OpenWA/sdk/go`](../sdk/go) | `go get` | Stdlib-only, no third-party deps. See [`sdk/go/README.md`](../sdk/go/README.md). |+| 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+ |+| Java | [`com.rmyndharis:openwa`](https://central.sonatype.com/artifact/com.rmyndharis/openwa) | Maven Central | Sync, `java.net.http`. See [`sdk/java/README.md`](../sdk/java/README.md). |+| Go | [`github.com/rmyndharis/OpenWA/sdk/go`](../sdk/go) | `go get` | Stdlib-only, no third-party deps. See [`sdk/go/README.md`](../sdk/go/README.md). |> 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.@@ -26,23 +26,23 @@ OpenWA ships five official, hand-written client libraries for the REST API. TheyAll five SDKs expose the same fluent surface:-| Resource | Methods |-| --- | --- |-| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch |-| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |-| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode |-| `webhooks` | list, get, create, update, delete, test |-| `chats` | list, markRead, markUnread, archive, clearMessages, 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, media, sendText, sendImage, sendVideo, delete *(Stories)* |-| `search` | search |-| `templates` | list, get, create, update, delete |-| `profile` | setProfileName, setProfileStatus, setProfilePicture |-| `calls` | rejectCall |-| `health` | check, live, ready |+| Resource | Methods |+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch |+| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |+| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode |+| `webhooks` | list, get, create, update, delete, test |+| `chats` | list, markRead, markUnread, archive, clearMessages, 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, media, sendText, sendImage, sendVideo, delete _(Stories)_ |+| `search` | search |+| `templates` | list, get, create, update, delete |+| `profile` | setProfileName, setProfileStatus, setProfilePicture |+| `calls` | rejectCall |+| `health` | check, live, ready |> The SDKs cover the user-facing resources above and stop there. The administrative and operational surfaces are deliberately left out β `auth/api-keys`, `audit`, `settings`, `stats`, `infra`, `plugins` and the `integration` management routes are predominantly `ADMIN`-gated; `metrics` is a `@Public()` Prometheus scrape gated by `METRICS_TOKEN` rather than by role; `mcp` is a Streamable-HTTP transport mounted straight onto the Express adapter; and `ingress` is the `@Public()` receiver that integration providers post into. `docker` has no HTTP surface at all β it is an internal service module. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.@@ -102,13 +102,13 @@ const { OpenWAClient } = require('@rmyndharis/openwa');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. |+| 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@@ -116,205 +116,205 @@ All resources are accessed as properties on the client (`client.<resource>.<methThe 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. |+| 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. **OPERATOR** |-| `stop` | `stop(id)` | Stop a session and disconnect gracefully. **OPERATOR** |-| `logout` | `logout(id)` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |-| `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). **OPERATOR** |-| `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). **OPERATOR** |-| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. **OPERATOR** |-| `stats` | `stats()` | Aggregate statistics across the key's 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. **OPERATOR** |+| `stop` | `stop(id)` | Stop a session and disconnect gracefully. **OPERATOR** |+| `logout` | `logout(id)` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |+| `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). **OPERATOR** |+| `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). **OPERATOR** |+| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. **OPERATOR** |+| `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). **OPERATOR** |-| `sendImage` | `sendImage(sessionId, body)` | Send an image (`url` or `base64`). **OPERATOR** |-| `sendVideo` | `sendVideo(sessionId, body)` | Send a video (`url` or `base64`). **OPERATOR** |-| `sendAudio` | `sendAudio(sessionId, body)` | Send an audio file (`url` or `base64`). **OPERATOR** |-| `sendDocument` | `sendDocument(sessionId, body)` | Send a document (`url` or `base64`; `filename` recommended). **OPERATOR** |-| `sendSticker` | `sendSticker(sessionId, body)` | Send a sticker (`url` or `base64`). **OPERATOR** |-| `sendLocation` | `sendLocation(sessionId, body)` | Send a location (`{ chatId, latitude, longitude, description? }`). **OPERATOR** |-| `sendContact` | `sendContact(sessionId, body)` | Send a contact card. **OPERATOR** |-| `sendTemplate` | `sendTemplate(sessionId, body)` | Render and send a stored message template. **OPERATOR** |-| `sendPoll` | `sendPoll(sessionId, body)` | Send a poll message. **OPERATOR** |-| `reply` | `reply(sessionId, body)` | Reply to a specific message. **OPERATOR** |-| `forward` | `forward(sessionId, body)` | Forward a message to another chat. **OPERATOR** |-| `react` | `react(sessionId, body)` | React to a message (empty `reaction` removes it). **OPERATOR** |-| `delete` | `delete(sessionId, body)` | Delete a message. **OPERATOR** |-| `editMessage` | `editMessage(sessionId, body)` | Edit the text of a message already sent. **OPERATOR** |-| `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`. **OPERATOR** |-| `batchStatus` | `batchStatus(sessionId, batchId)` | Poll the status/progress of a bulk-send batch. |-| `cancelBatch` | `cancelBatch(sessionId, batchId)` | Cancel a running batch. **OPERATOR** |+| 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). **OPERATOR** |+| `sendImage` | `sendImage(sessionId, body)` | Send an image (`url` or `base64`). **OPERATOR** |+| `sendVideo` | `sendVideo(sessionId, body)` | Send a video (`url` or `base64`). **OPERATOR** |+| `sendAudio` | `sendAudio(sessionId, body)` | Send an audio file (`url` or `base64`). **OPERATOR** |+| `sendDocument` | `sendDocument(sessionId, body)` | Send a document (`url` or `base64`; `filename` recommended). **OPERATOR** |+| `sendSticker` | `sendSticker(sessionId, body)` | Send a sticker (`url` or `base64`). **OPERATOR** |+| `sendLocation` | `sendLocation(sessionId, body)` | Send a location (`{ chatId, latitude, longitude, description? }`). **OPERATOR** |+| `sendContact` | `sendContact(sessionId, body)` | Send a contact card. **OPERATOR** |+| `sendTemplate` | `sendTemplate(sessionId, body)` | Render and send a stored message template. **OPERATOR** |+| `sendPoll` | `sendPoll(sessionId, body)` | Send a poll message. **OPERATOR** |+| `reply` | `reply(sessionId, body)` | Reply to a specific message. **OPERATOR** |+| `forward` | `forward(sessionId, body)` | Forward a message to another chat. **OPERATOR** |+| `react` | `react(sessionId, body)` | React to a message (empty `reaction` removes it). **OPERATOR** |+| `delete` | `delete(sessionId, body)` | Delete a message. **OPERATOR** |+| `editMessage` | `editMessage(sessionId, body)` | Edit the text of a message already sent. **OPERATOR** |+| `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`. **OPERATOR** |+| `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). |-| `profilePictures` | `profilePictures(sessionId, ids)` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |-| `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** |+| 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). |+| `profilePictures` | `profilePictures(sessionId, ids)` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |+| `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** |-| `joinGroup` | `joinGroup(sessionId, body)` | Join a group via its invite code. **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** |-| `getGroupSettings` | `getGroupSettings(sessionId, groupId)` | Get the group settings (announce / locked / ephemeral timer). |-| `updateGroupSettings` | `updateGroupSettings(sessionId, groupId, body)` | Update the group settings (at least one field required). **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** |+| 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** |+| `joinGroup` | `joinGroup(sessionId, body)` | Join a group via its invite code. **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** |+| `getGroupSettings` | `getGroupSettings(sessionId, groupId)` | Get the group settings (announce / locked / ephemeral timer). |+| `updateGroupSettings` | `updateGroupSettings(sessionId, groupId, body)` | Update the group settings (at least one field required). **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** |+| 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. **OPERATOR** |-| `get` | `get(sessionId, id)` | Get a single webhook by id. **OPERATOR** |-| `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. |-| `media` | `media(sessionId, statusId)` | Fetch the stored media bytes for a status update (404 when there is none). |-| `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** |+| Method | Signature | Description |+| -------- | ----------------------------- | ------------------------------------------------------------------------------ |+| `list` | `list(sessionId)` | List all webhooks for a session. **OPERATOR** |+| `get` | `get(sessionId, id)` | Get a single webhook by id. **OPERATOR** |+| `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. |+| `media` | `media(sessionId, statusId)` | Fetch the stored media bytes for a status update (404 when there is none). |+| `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.#### `search`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| -------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ || `search` | `search(params)` | Search persisted messages across sessions via the active search provider; a scoped key's reach is bounded by its `allowedSessions`. **OPERATOR** |#### `templates`-| Method | Signature | Description |-| --- | --- | --- |-| `list` | `list(sessionId)` | List all templates for a session. **OPERATOR** |-| `get` | `get(sessionId, id)` | Get a single template by id. **OPERATOR** |-| `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** |+| Method | Signature | Description |+| -------- | ----------------------------- | ---------------------------------------------- |+| `list` | `list(sessionId)` | List all templates for a session. **OPERATOR** |+| `get` | `get(sessionId, id)` | Get a single template by id. **OPERATOR** |+| `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** |#### `profile`-| Method | Signature | Description |-| --- | --- | --- |-| `setProfileName` | `setProfileName(sessionId, name)` | Set the account display name. **OPERATOR** |-| `setProfileStatus` | `setProfileStatus(sessionId, status)` | Set the account about/status text (empty clears it). **OPERATOR** |-| `setProfilePicture` | `setProfilePicture(sessionId, body)` | Set the account profile picture (`url` or `base64` + `mimetype`). **OPERATOR** |+| Method | Signature | Description |+| ------------------- | ------------------------------------- | ------------------------------------------------------------------------------ |+| `setProfileName` | `setProfileName(sessionId, name)` | Set the account display name. **OPERATOR** |+| `setProfileStatus` | `setProfileStatus(sessionId, status)` | Set the account about/status text (empty clears it). **OPERATOR** |+| `setProfilePicture` | `setProfilePicture(sessionId, body)` | Set the account profile picture (`url` or `base64` + `mimetype`). **OPERATOR** |#### `calls`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| ------------ | ------------------------------- | -------------------------------------------------------------------------------------------- || `rejectCall` | `rejectCall(sessionId, callId)` | Reject a ringing incoming call (`callId` comes from the `call.received` event). **OPERATOR** |#### `health`-| Method | Signature | Description |-| --- | --- | --- |-| `check` | `check()` | General health (also returns the running version). |-| `live` | `live()` | Kubernetes liveness probe (`{ status }`). |+| 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 HandlingOn 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`).-| 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. |+| 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. |```typescriptimport {@@ -427,21 +427,21 @@ OpenWAClient()```-| 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. |+| 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`. |+| 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@@ -449,194 +449,194 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All#### `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). **OPERATOR** |-| `delete` | `delete(session_id) -> None` | Delete a session. **OPERATOR** |-| `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. **OPERATOR** |-| `stop` | `stop(session_id) -> SessionResponse` | Stop a session. **OPERATOR** |-| `logout` | `logout(session_id) -> SessionResponse` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |-| `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. **OPERATOR** |-| `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. **OPERATOR** |-| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. **OPERATOR** |-| `stats` | `stats() -> SessionStatsOverview` | Session statistics overview. |+| 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). **OPERATOR** |+| `delete` | `delete(session_id) -> None` | Delete a session. **OPERATOR** |+| `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. **OPERATOR** |+| `stop` | `stop(session_id) -> SessionResponse` | Stop a session. **OPERATOR** |+| `logout` | `logout(session_id) -> SessionResponse` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |+| `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. **OPERATOR** |+| `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. **OPERATOR** |+| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. **OPERATOR** |+| `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. **OPERATOR** |-| `send_image` | `send_image(session_id, body) -> MessageResponse` | Send an image. **OPERATOR** |-| `send_video` | `send_video(session_id, body) -> MessageResponse` | Send a video. **OPERATOR** |-| `send_audio` | `send_audio(session_id, body) -> MessageResponse` | Send audio. **OPERATOR** |-| `send_document` | `send_document(session_id, body) -> MessageResponse` | Send a document. **OPERATOR** |-| `send_sticker` | `send_sticker(session_id, body) -> MessageResponse` | Send a sticker. **OPERATOR** |-| `send_location` | `send_location(session_id, body) -> MessageResponse` | Send a location. **OPERATOR** |-| `send_contact` | `send_contact(session_id, body) -> MessageResponse` | Send a contact card. **OPERATOR** |-| `send_template` | `send_template(session_id, body) -> MessageResponse` | Send a stored template. **OPERATOR** |-| `send_poll` | `send_poll(session_id, body) -> MessageResponse` | Send a poll message. **OPERATOR** |-| `reply` | `reply(session_id, body) -> MessageResponse` | Reply to a message. **OPERATOR** |-| `forward` | `forward(session_id, body) -> MessageResponse` | Forward a message. **OPERATOR** |-| `react` | `react(session_id, body) -> SuccessResult` | React to a message. **OPERATOR** |-| `delete` | `delete(session_id, body) -> SuccessResult` | Delete a message. **OPERATOR** |-| `edit_message` | `edit_message(session_id, body) -> MessageResponse` | Edit the text of a message already sent. **OPERATOR** |-| `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. **OPERATOR** |-| `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** |+| 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. **OPERATOR** |+| `send_image` | `send_image(session_id, body) -> MessageResponse` | Send an image. **OPERATOR** |+| `send_video` | `send_video(session_id, body) -> MessageResponse` | Send a video. **OPERATOR** |+| `send_audio` | `send_audio(session_id, body) -> MessageResponse` | Send audio. **OPERATOR** |+| `send_document` | `send_document(session_id, body) -> MessageResponse` | Send a document. **OPERATOR** |+| `send_sticker` | `send_sticker(session_id, body) -> MessageResponse` | Send a sticker. **OPERATOR** |+| `send_location` | `send_location(session_id, body) -> MessageResponse` | Send a location. **OPERATOR** |+| `send_contact` | `send_contact(session_id, body) -> MessageResponse` | Send a contact card. **OPERATOR** |+| `send_template` | `send_template(session_id, body) -> MessageResponse` | Send a stored template. **OPERATOR** |+| `send_poll` | `send_poll(session_id, body) -> MessageResponse` | Send a poll message. **OPERATOR** |+| `reply` | `reply(session_id, body) -> MessageResponse` | Reply to a message. **OPERATOR** |+| `forward` | `forward(session_id, body) -> MessageResponse` | Forward a message. **OPERATOR** |+| `react` | `react(session_id, body) -> SuccessResult` | React to a message. **OPERATOR** |+| `delete` | `delete(session_id, body) -> SuccessResult` | Delete a message. **OPERATOR** |+| `edit_message` | `edit_message(session_id, body) -> MessageResponse` | Edit the text of a message already sent. **OPERATOR** |+| `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. **OPERATOR** |+| `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. |-| `profile_pictures` | `profile_pictures(session_id, ids) -> ProfilePicturesResponse` | Batch-resolve profile picture URLs for up to 50 contacts. |-| `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** |+| 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. |+| `profile_pictures` | `profile_pictures(session_id, ids) -> ProfilePicturesResponse` | Batch-resolve profile picture URLs for up to 50 contacts. |+| `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** |-| `join_group` | `join_group(session_id, body) -> JoinGroupResponse` | Join a group via its invite code. **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** |-| `get_group_settings` | `get_group_settings(session_id, group_id) -> GroupSettings` | Get the group settings (announce / locked / ephemeral timer). |-| `update_group_settings` | `update_group_settings(session_id, group_id, body) -> SuccessResult` | Update the group settings (at least one field required). **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** |+| 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** |+| `join_group` | `join_group(session_id, body) -> JoinGroupResponse` | Join a group via its invite code. **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** |+| `get_group_settings` | `get_group_settings(session_id, group_id) -> GroupSettings` | Get the group settings (announce / locked / ephemeral timer). |+| `update_group_settings` | `update_group_settings(session_id, group_id, body) -> SuccessResult` | Update the group settings (at least one field required). **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** |+| 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. **OPERATOR** |-| `get` | `get(session_id, webhook_id) -> WebhookResponse` | Get one webhook. **OPERATOR** |-| `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** |+| Method | Signature | Description |+| -------- | --------------------------------------------------------- | ---------------------------------- |+| `list` | `list(session_id) -> list[WebhookResponse]` | List webhooks. **OPERATOR** |+| `get` | `get(session_id, webhook_id) -> WebhookResponse` | Get one webhook. **OPERATOR** |+| `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[ChannelMessageRecord]` | 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. |-| `media` | `media(session_id, status_id) -> StatusMedia` | Fetch the stored media bytes for a status update. |-| `send_text` | `send_text(session_id, body) -> StatusResult` | Post a text status. **OPERATOR** |-| `send_image` | `send_image(session_id, body) -> StatusResult` | Post an image status. **OPERATOR** |-| `send_video` | `send_video(session_id, body) -> StatusResult` | Post a video status. **OPERATOR** |-| `delete` | `delete(session_id, status_id) -> None` | Delete a status. **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[ChannelMessageRecord]` | 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. |+| `media` | `media(session_id, status_id) -> StatusMedia` | Fetch the stored media bytes for a status update. |+| `send_text` | `send_text(session_id, body) -> StatusResult` | Post a text status. **OPERATOR** |+| `send_image` | `send_image(session_id, body) -> StatusResult` | Post an image status. **OPERATOR** |+| `send_video` | `send_video(session_id, body) -> StatusResult` | Post a video status. **OPERATOR** |+| `delete` | `delete(session_id, status_id) -> None` | Delete a status. **OPERATOR** |#### `client.search`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| -------- | --------------------------------- | -------------------------------------------------------------------------------------- || `search` | `search(params) -> SearchResults` | Search persisted messages across sessions via the active search provider. **OPERATOR** |#### `client.templates`-| Method | Signature | Description |-| --- | --- | --- |-| `list` | `list(session_id) -> list[TemplateRecord]` | List templates. **OPERATOR** |-| `get` | `get(session_id, template_id) -> TemplateRecord` | Get one template. **OPERATOR** |-| `create` | `create(session_id, body) -> TemplateRecord` | Create a template. **OPERATOR** |+| Method | Signature | Description |+| -------- | --------------------------------------------------------- | ------------------------------- |+| `list` | `list(session_id) -> list[TemplateRecord]` | List templates. **OPERATOR** |+| `get` | `get(session_id, template_id) -> TemplateRecord` | Get one template. **OPERATOR** |+| `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** |+| `delete` | `delete(session_id, template_id) -> None` | Delete a template. **OPERATOR** |#### `client.profile`-| Method | Signature | Description |-| --- | --- | --- |-| `set_profile_name` | `set_profile_name(session_id, body) -> SuccessResult` | Set the account display name. **OPERATOR** |-| `set_profile_status` | `set_profile_status(session_id, body) -> SuccessResult` | Set the account about/status text (empty clears it). **OPERATOR** |+| Method | Signature | Description |+| --------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------ |+| `set_profile_name` | `set_profile_name(session_id, body) -> SuccessResult` | Set the account display name. **OPERATOR** |+| `set_profile_status` | `set_profile_status(session_id, body) -> SuccessResult` | Set the account about/status text (empty clears it). **OPERATOR** || `set_profile_picture` | `set_profile_picture(session_id, body) -> SuccessResult` | Set the account profile picture (`url` or `base64` + `mimetype`). **OPERATOR** |#### `client.calls`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| ------------- | --------------------------------------------------- | -------------------------------------------- || `reject_call` | `reject_call(session_id, call_id) -> SuccessResult` | Reject a ringing incoming call. **OPERATOR** |#### `client.health`-| Method | Signature | Description |-| --- | --- | --- |-| `check` | `check() -> HealthResponse` | Aggregate health check. |-| `live` | `live() -> dict[str, str]` | Liveness probe. |-| `ready` | `ready() -> HealthReadyResponse` | Readiness probe. |+| Method | Signature | Description |+| ------- | -------------------------------- | ----------------------- |+| `check` | `check() -> HealthResponse` | Aggregate health check. |+| `live` | `live() -> dict[str, str]` | Liveness probe. |+| `ready` | `ready() -> HealthReadyResponse` | Readiness probe. |### Error HandlingEvery 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).-| 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 |+| 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) |+| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |+| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |```pythonfrom openwa import (@@ -721,22 +721,22 @@ The entry class is `OpenWA\Client`. It validates that `baseUrl` and `apiKey` areTwo 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. |+| 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 ConfigurationThe 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). |+| 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.@@ -746,195 +746,195 @@ All payloads are associative arrays; all listed methods are synchronous and retu#### `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). **OPERATOR** |-| `delete` | `delete(string $id): void` | Delete a session. **OPERATOR** |-| `start` | `start(string $id): array` | Start a session. **OPERATOR** |-| `stop` | `stop(string $id): array` | Stop a session. **OPERATOR** |-| `logout` | `logout(string $id): array` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |-| `forceKill` | `forceKill(string $id): array` | Force-kill a session. **OPERATOR** |-| `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. **OPERATOR** |-| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. **OPERATOR** |-| `stats` | `stats(): array` | `GET /api/sessions/stats/overview`. |+| 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). **OPERATOR** |+| `delete` | `delete(string $id): void` | Delete a session. **OPERATOR** |+| `start` | `start(string $id): array` | Start a session. **OPERATOR** |+| `stop` | `stop(string $id): array` | Stop a session. **OPERATOR** |+| `logout` | `logout(string $id): array` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** |+| `forceKill` | `forceKill(string $id): array` | Force-kill a session. **OPERATOR** |+| `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. **OPERATOR** |+| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. **OPERATOR** |+| `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`). **OPERATOR** |-| `sendImage` | `sendImage(string $sessionId, array $body): array` | Send an image. **OPERATOR** |-| `sendVideo` | `sendVideo(string $sessionId, array $body): array` | Send a video. **OPERATOR** |-| `sendAudio` | `sendAudio(string $sessionId, array $body): array` | Send audio. **OPERATOR** |-| `sendDocument` | `sendDocument(string $sessionId, array $body): array` | Send a document. **OPERATOR** |-| `sendSticker` | `sendSticker(string $sessionId, array $body): array` | Send a sticker. **OPERATOR** |-| `sendLocation` | `sendLocation(string $sessionId, array $body): array` | Send a location. **OPERATOR** |-| `sendContact` | `sendContact(string $sessionId, array $body): array` | Send a contact card. **OPERATOR** |-| `sendTemplate` | `sendTemplate(string $sessionId, array $body): array` | Send a stored template. **OPERATOR** |-| `sendPoll` | `sendPoll(string $sessionId, array $body): array` | Send a native poll (2β12 options). **OPERATOR** |-| `reply` | `reply(string $sessionId, array $body): array` | Reply to a message. **OPERATOR** |-| `forward` | `forward(string $sessionId, array $body): array` | Forward a message. **OPERATOR** |-| `react` | `react(string $sessionId, array $body): array` | React to a message. **OPERATOR** |-| `delete` | `delete(string $sessionId, array $body): array` | Delete a message. **OPERATOR** |-| `editMessage` | `editMessage(string $sessionId, array $body): array` | Edit the text of a message already sent (`$body` needs `chatId`, `messageId`, `body`). **OPERATOR** |-| `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. **OPERATOR** |-| `batchStatus` | `batchStatus(string $sessionId, string $batchId): array` | Get bulk batch status. |-| `cancelBatch` | `cancelBatch(string $sessionId, string $batchId): array` | Cancel a bulk batch. **OPERATOR** |+| 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`). **OPERATOR** |+| `sendImage` | `sendImage(string $sessionId, array $body): array` | Send an image. **OPERATOR** |+| `sendVideo` | `sendVideo(string $sessionId, array $body): array` | Send a video. **OPERATOR** |+| `sendAudio` | `sendAudio(string $sessionId, array $body): array` | Send audio. **OPERATOR** |+| `sendDocument` | `sendDocument(string $sessionId, array $body): array` | Send a document. **OPERATOR** |+| `sendSticker` | `sendSticker(string $sessionId, array $body): array` | Send a sticker. **OPERATOR** |+| `sendLocation` | `sendLocation(string $sessionId, array $body): array` | Send a location. **OPERATOR** |+| `sendContact` | `sendContact(string $sessionId, array $body): array` | Send a contact card. **OPERATOR** |+| `sendTemplate` | `sendTemplate(string $sessionId, array $body): array` | Send a stored template. **OPERATOR** |+| `sendPoll` | `sendPoll(string $sessionId, array $body): array` | Send a native poll (2β12 options). **OPERATOR** |+| `reply` | `reply(string $sessionId, array $body): array` | Reply to a message. **OPERATOR** |+| `forward` | `forward(string $sessionId, array $body): array` | Forward a message. **OPERATOR** |+| `react` | `react(string $sessionId, array $body): array` | React to a message. **OPERATOR** |+| `delete` | `delete(string $sessionId, array $body): array` | Delete a message. **OPERATOR** |+| `editMessage` | `editMessage(string $sessionId, array $body): array` | Edit the text of a message already sent (`$body` needs `chatId`, `messageId`, `body`). **OPERATOR** |+| `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. **OPERATOR** |+| `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. |-| `profilePictures` | `profilePictures(string $sessionId, array $ids): array` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |-| `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** |+| 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. |+| `profilePictures` | `profilePictures(string $sessionId, array $ids): array` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |+| `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** |-| `joinGroup` | `joinGroup(string $sessionId, string $inviteCode): array` | Join a group via its invite code. **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** |-| `getGroupSettings` | `getGroupSettings(string $sessionId, string $groupId): array` | Get the group settings (only the ones the active engine supports are present). |-| `updateGroupSettings` | `updateGroupSettings(string $sessionId, string $groupId, array $settings): array` | Update the group settings (at least one of `announce`, `locked`, `ephemeralSeconds`). **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** |+| 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** |+| `joinGroup` | `joinGroup(string $sessionId, string $inviteCode): array` | Join a group via its invite code. **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** |+| `getGroupSettings` | `getGroupSettings(string $sessionId, string $groupId): array` | Get the group settings (only the ones the active engine supports are present). |+| `updateGroupSettings` | `updateGroupSettings(string $sessionId, string $groupId, array $settings): array` | Update the group settings (at least one of `announce`, `locked`, `ephemeralSeconds`). **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** |+| 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. **OPERATOR** |-| `get` | `get(string $sessionId, string $id): array` | Get one webhook. **OPERATOR** |-| `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. |-| `media` | `media(string $sessionId, string $statusId): array` | Fetch the stored media bytes for a status update (`{data, contentType}`; 404 when there is none). |-| `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** |+| Method | Signature | Description |+| -------- | ----------------------------------------------------------- | ------------------------------- |+| `list` | `list(string $sessionId): array` | List webhooks. **OPERATOR** |+| `get` | `get(string $sessionId, string $id): array` | Get one webhook. **OPERATOR** |+| `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. |+| `media` | `media(string $sessionId, string $statusId): array` | Fetch the stored media bytes for a status update (`{data, contentType}`; 404 when there is none). |+| `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** |#### `search`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| -------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------- || `search` | `search(array $params): array` | Search persisted messages across sessions via the active search provider (`$params['q']` required). **OPERATOR** |#### `templates`-| Method | Signature | Description |-| --- | --- | --- |-| `list` | `list(string $sessionId): array` | List templates. **OPERATOR** |-| `get` | `get(string $sessionId, string $templateId): array` | Get one template. **OPERATOR** |-| `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** |+| Method | Signature | Description |+| -------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |+| `list` | `list(string $sessionId): array` | List templates. **OPERATOR** |+| `get` | `get(string $sessionId, string $templateId): array` | Get one template. **OPERATOR** |+| `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** |#### `profile`-| Method | Signature | Description |-| --- | --- | --- |-| `setProfileName` | `setProfileName(string $sessionId, string $name): array` | Set the account display name. **OPERATOR** |-| `setProfileStatus` | `setProfileStatus(string $sessionId, string $status): array` | Set the account about/status text (empty clears it). **OPERATOR** |-| `setProfilePicture` | `setProfilePicture(string $sessionId, array $body): array` | Set the account profile picture (`url` or `base64` + `mimetype`). **OPERATOR** |+| Method | Signature | Description |+| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------ |+| `setProfileName` | `setProfileName(string $sessionId, string $name): array` | Set the account display name. **OPERATOR** |+| `setProfileStatus` | `setProfileStatus(string $sessionId, string $status): array` | Set the account about/status text (empty clears it). **OPERATOR** |+| `setProfilePicture` | `setProfilePicture(string $sessionId, array $body): array` | Set the account profile picture (`url` or `base64` + `mimetype`). **OPERATOR** |#### `calls`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| ------------ | ------------------------------------------------------ | -------------------------------------------------------------------------------------------- || `rejectCall` | `rejectCall(string $sessionId, string $callId): array` | Reject a ringing incoming call (404 when it is not found or no longer ringing). **OPERATOR** |#### `health`-| Method | Signature | Description |-| --- | --- | --- |+| Method | Signature | Description |+| ------- | ---------------- | ------------------ || `check` | `check(): array` | `GET /api/health`. |-| `live` | `live(): array` | Liveness probe. |-| `ready` | `ready(): array` | Readiness probe. |+| `live` | `live(): array` | Liveness probe. |+| `ready` | `ready(): array` | Readiness probe. |### Error HandlingAll 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`).-| 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. |+| 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@@ -989,13 +989,13 @@ For installation and node-by-node configuration, see the dedicated [n8n IntegratThe five SDKs are versioned **independently of the gateway** and of each other, each following SemVer. An SDK version does **not** track the gateway version β check the registry for the current one rather than inferring it from the gateway's. Pin the SDK version your code is tested against and treat a major SDK bump as potentially breaking.-| SDK | Registry | Package |-| --- | --- | --- |-| JavaScript/TypeScript | npm | `@rmyndharis/openwa` |-| Python | PyPI | `rmyndharis-openwa` |-| PHP | Packagist | `rmyndharis/openwa` |-| Java | Maven Central | `com.rmyndharis:openwa` |-| Go | (none β module path) | `github.com/rmyndharis/OpenWA/sdk/go` |+| SDK | Registry | Package |+| --------------------- | -------------------- | ------------------------------------- |+| JavaScript/TypeScript | npm | `@rmyndharis/openwa` |+| Python | PyPI | `rmyndharis-openwa` |+| PHP | Packagist | `rmyndharis/openwa` |+| Java | Maven Central | `com.rmyndharis:openwa` |+| Go | (none β module path) | `github.com/rmyndharis/OpenWA/sdk/go` |### Contract-drift protectiondiff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex 114da184f..8273f482c 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -7,25 +7,25 @@> 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 |-|-----------|--------|----------|-| **HookManager** | β Implemented | `src/core/hooks/hook-manager.service.ts` |-| **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 | 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 |-|-----------|--------|-------|-| **Sandboxed execution** | β Implemented | Untrusted (disk-loaded) plugins run in a `worker_thread`; see [30 β Plugin Sandboxing](./30-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 |+| Component | Status | Location |+| ------------------------ | -------------- | ------------------------------------------------------------------ |+| **HookManager** | β Implemented | `src/core/hooks/hook-manager.service.ts` |+| **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 | 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 |+| ---------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------- |+| **Sandboxed execution** | β Implemented | Untrusted (disk-loaded) plugins run in a `worker_thread`; see [30 β Plugin Sandboxing](./30-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 |---@@ -79,13 +79,13 @@ flowchart LRINT --> |External| SERVICES[External Services]```-| Type | Description | Examples |-|------|-------------|----------|-| Message Handler | Process incoming/outgoing messages | Auto-reply, Translation |-| Webhook Transformer | Transform webhook payloads | Add metadata, Filter events |-| Auth Provider | Custom authentication | OAuth, LDAP |-| Storage Provider | Alternative storage backends | Google Drive, Dropbox |-| Integration | External service integration | CRM, Analytics, n8n |+| Type | Description | Examples |+| ------------------- | ---------------------------------- | --------------------------- |+| Message Handler | Process incoming/outgoing messages | Auto-reply, Translation |+| Webhook Transformer | Transform webhook payloads | Add metadata, Filter events |+| Auth Provider | Custom authentication | OAuth, LDAP |+| Storage Provider | Alternative storage backends | Google Drive, Dropbox |+| Integration | External service integration | CRM, Analytics, n8n |## 19.3 Plugin Structure@@ -153,35 +153,35 @@ a host version, except for the SDK-major check applied to a manifest that declar}```-| Field | Required | Meaning |-|-------|----------|---------|-| `id` | β | Unique identifier (also the plugin's on-disk directory name) |-| `name` | β | Display name |-| `version` | β | Semver |-| `type` | β | The enum has five values (`engine`, `storage`, `queue`, `auth`, `extension`) but only `extension` is installable β an uploaded or hand-placed directory declaring any other type is rejected at install **and** at boot load. The other tiers are reserved for programmatically registered built-ins |-| `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, unless `net.allowConfigHosts` admits a host |-| `net.allowConfigHosts` | β | Config keys holding an https URL; each URL's host is admitted at fetch time on top of `net.allow`, so an adapter can reach an operator-configured host without `net.allow: ['*']`. Credentialed or non-https values are ignored, and the SSRF guard still applies |-| `sdkVersion` | β | Integration SDK `major` (or `major.minor`) the plugin was authored against. Absent = `'1'`. Only enforced for a manifest declaring `ingress`: a major other than `1` is refused at load |-| `ingress` | β | Inbound webhook routes this plugin claims (requires the `webhook:ingress` permission). Validated at load β route uniqueness, signature scheme, ack contract; see [25 β Integration Fabric](./25-integration-fabric.md) |-| `configSchema` | β | Declarative config schema the dashboard renders as a form when there is no `configUi`. Still required with one: it defines the fields, their types and which are `secret` |-| `configUi` | β | Optional self-contained HTML config editor served into a sandboxed iframe. When present it **replaces** the generated form and owns saving β the dashboard renders neither the form nor its Save button |-| `hooks` | β | Hook events this plugin listens to (informational) |-| `provides` / `requires` | β | Features this plugin provides / depends on |-| `i18n` | β | Localized dashboard text per locale (dashboard-only) |+| Field | Required | Meaning |+| ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `id` | β | Unique identifier (also the plugin's on-disk directory name) |+| `name` | β | Display name |+| `version` | β | Semver |+| `type` | β | The enum has five values (`engine`, `storage`, `queue`, `auth`, `extension`) but only `extension` is installable β an uploaded or hand-placed directory declaring any other type is rejected at install **and** at boot load. The other tiers are reserved for programmatically registered built-ins |+| `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, unless `net.allowConfigHosts` admits a host |+| `net.allowConfigHosts` | β | Config keys holding an https URL; each URL's host is admitted at fetch time on top of `net.allow`, so an adapter can reach an operator-configured host without `net.allow: ['*']`. Credentialed or non-https values are ignored, and the SSRF guard still applies |+| `sdkVersion` | β | Integration SDK `major` (or `major.minor`) the plugin was authored against. Absent = `'1'`. Only enforced for a manifest declaring `ingress`: a major other than `1` is refused at load |+| `ingress` | β | Inbound webhook routes this plugin claims (requires the `webhook:ingress` permission). Validated at load β route uniqueness, signature scheme, ack contract; see [25 β Integration Fabric](./25-integration-fabric.md) |+| `configSchema` | β | Declarative config schema the dashboard renders as a form when there is no `configUi`. Still required with one: it defines the fields, their types and which are `secret` |+| `configUi` | β | Optional self-contained HTML config editor served into a sandboxed iframe. When present it **replaces** the generated form and owns saving β the dashboard renders neither the form nor its Save button |+| `hooks` | β | Hook events this plugin listens to (informational) |+| `provides` / `requires` | β | Features this plugin provides / depends on |+| `i18n` | β | Localized dashboard text per locale (dashboard-only) |**The `configUi` bridge.** The editor is injected as `srcdoc` into a `sandbox="allow-scripts"` iframe, soit has an opaque origin and no access to the dashboard. It talks to the host by `postMessage`:-| Direction | Message | Notes |-| --- | --- | --- |-| iframe β host | `{ type: 'config:get' }` | Sent on load; the host answers with the current values |-| host β iframe | `{ type: 'config:value', config, schema, theme }` | `config` is already secret-redacted. `theme` is `'light'` or `'dark'`, resolved by the host |-| iframe β host | `{ type: 'config:save', config }` | The host makes the authenticated write |-| host β iframe | `{ type: 'config:saved' }` / `{ type: 'config:error', message }` | Outcome of that write |+| Direction | Message | Notes |+| ------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |+| iframe β host | `{ type: 'config:get' }` | Sent on load; the host answers with the current values |+| host β iframe | `{ type: 'config:value', config, schema, theme }` | `config` is already secret-redacted. `theme` is `'light'` or `'dark'`, resolved by the host |+| iframe β host | `{ type: 'config:save', config }` | The host makes the authenticated write |+| host β iframe | `{ type: 'config:saved' }` / `{ type: 'config:error', message }` | Outcome of that write |`theme` matters because an opaque-origin iframe cannot read the dashboard's theme for itself; without itan editor can only guess, and a light-only editor becomes a glaring white panel inside a dark modal. It is@@ -273,8 +273,8 @@ export interface PluginContext {config: Record<string, unknown>;hookManager: HookManager;- logger: PluginLogger; // log / debug / warn / error- storage: PluginStorage; // get / set / delete / list β scoped to this plugin+ logger: PluginLogger; // log / debug / warn / error+ storage: PluginStorage; // get / set / delete / list β scoped to this plugin// Register a hook handler (optionally with a priority; lower runs first).registerHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;@@ -284,12 +284,12 @@ export interface PluginContext {registerWebhook: (route: string, handler: WebhookHandler) => void;// 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, host-allowlisted)+ messages: PluginMessagingCapability; // requires 'messages:send'+ engine: PluginEngineReadCapability; // requires 'engine:read' (read-only)+ net: PluginNetCapability; // requires 'net:fetch' (SSRF-guarded, host-allowlisted)conversations: PluginConversationsCapability; // requires 'conversation:send'- handover: PluginHandoverCapability; // requires 'conversation:send'- mappings: PluginMappingsCapability; // requires 'conversation:send'+ handover: PluginHandoverCapability; // requires 'conversation:send'+ mappings: PluginMappingsCapability; // requires 'conversation:send'}export interface PluginLogger {@@ -411,10 +411,10 @@ On a **pre-action** event it is a veto, because the action has not been taken yedelivery.> **`message:sending` does not see every attempted send.** With send pacing enabled-> (`SEND_PACING_ENABLED`), the pacing governor runs *before* this hook, so a send it refuses never+> (`SEND_PACING_ENABLED`), the pacing governor runs _before_ this hook, so a send it refuses never> fires `message:sending` β plugins are not asked to moderate, and cannot rewrite, traffic that> policy already forbids. Treat the hook as a complete record of sends **actually attempted against-> WhatsApp**, not of send *requests*. A paced-out request surfaces to the caller as `429` with+> WhatsApp**, not of send _requests_. A paced-out request surfaces to the caller as `429` with> `code: SEND_PACING_LIMITED`; a plugin veto stays `400`. Pacing is off by default, so a deployment> that has not opted in sees the hook fire exactly as before.@@ -461,16 +461,16 @@ export type HookEvent =```typescriptexport 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)+ 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+ source: string; // which service emitted this}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+ 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 type HookHandler<T = unknown> = (ctx: HookContext<T>) => Promise<HookResult<T>>;@@ -557,10 +557,10 @@ missing grant or out-of-scope session fails with a `PluginCapabilityError`.The only plugins **shipped** as built-ins are the two WhatsApp **engine adapters**, registeredprogrammatically (not loaded from disk) by `EngineFactory` via `registerBuiltInPlugin`:-| Plugin id | Type | Notes |-|-----------|------|-------|+| Plugin id | Type | Notes |+| ----------------- | -------- | -------------------------------------- || `whatsapp-web.js` | `engine` | Default engine adapter (browser-based) |-| `baileys` | `engine` | WebSocket engine adapter (no browser) |+| `baileys` | `engine` | WebSocket engine adapter (no browser) |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@@ -614,22 +614,22 @@ route requires the `ADMIN` role** (`@RequireRole(ApiKeyRole.ADMIN)` β not a bais **no** `POST :id/reload` and **no** `GET :id/config`. Install is a multipart `.zip` upload (or byURL / 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 an https URL (SSRF-guarded; optional `#sha256=` digest pin) |-| `POST /plugins/:id/update` | Update an installed plugin in place from a URL (staged swap, crash-safe; 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) |+| 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 an https URL (SSRF-guarded; optional `#sha256=` digest pin) |+| `POST /plugins/:id/update` | Update an installed plugin in place from a URL (staged swap, crash-safe; 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 thediff --git a/docs/21-glossary.md b/docs/21-glossary.mdindex a3e1c364e..6b8da3f2e 100644--- a/docs/21-glossary.md+++ b/docs/21-glossary.md@@ -3,7 +3,9 @@## A### ACK (Acknowledgement)+Delivery acknowledgment. Each adapter maps its native ack code to one neutral status - `pending`, `sent`, `delivered`, `read` or `failed` - so no consumer sees engine-specific codes. The whatsapp-web.js ack integers map as:+- `-1` ERROR -> `failed`- `0` PENDING -> `pending`- `1` SERVER -> `sent`@@ -12,63 +14,81 @@ Delivery acknowledgment. Each adapter maps its native ack code to one neutral st- `4` PLAYED -> `read` (media playback is not a distinct status)### Adapter+An interface implementation that provides a specific capability. In OpenWA, adapters are used for:+- **Database Adapter**: SQLite, PostgreSQL- **Storage Adapter**: Local, S3- **Cache**: Redis (optional β `CacheService` is Redis-only; with Redis disabled it no-ops and callers fall through to the database)- **Engine Adapter**: whatsapp-web.js (default), Baileys### API Key+Authentication token to access the OpenWA API. Sent via the `X-API-Key` header.### Auth State+WhatsApp Web session authentication data. On the whatsapp-web.js engine it is a Chrome profile (cookies, local/session storage) under `SESSION_DATA_PATH` β default `./data/sessions`, one `session-<name>` directory per session. On Baileys it is a set of credential JSON files under `BAILEYS_AUTH_DIR`, default `./data/baileys`. Losing it unlinks the WhatsApp account and requires a fresh QR scan.## B### Baileys+Node.js library for WhatsApp Web that uses WebSocket directly without a browser (no Chromium required). Available as a selectable engine in OpenWA via `ENGINE_TYPE=baileys`.### Broadcast+Sending the same message to multiple recipients. On WhatsApp, this differs from the native "Broadcast List" feature.### BullMQ+A Redis-based Node.js job queue library (`bullmq`, wired in through `@nestjs/bullmq`). It backs the two queues OpenWA runs:+- `webhook-queue`: webhook delivery, with retry and a dead-letter row on final failure- `ingress-queue`: inbound integration deliveries dispatched to plugins, with retry and a dead-letter row on final failure## C### Chat ID+Unique identifier for a WhatsApp chat:+- Individual: `[email protected]`- Group: `[email protected]`- Status: `status@broadcast`### Chrome/Chromium+Browser used by Puppeteer to run WhatsApp Web. OpenWA uses headless Chromium.### Compose+Docker Compose - a tool to define and run multi-container Docker applications.## D### Dashboard+Web interface to manage OpenWA without using the API directly. Built with React and Vite, using TanStack Query for data fetching and plain CSS for styling.### Dead Letter Queue (DLQ)+The durable record of deliveries abandoned after every retry. In OpenWA it is a **database table**, not a Redis queue: `webhook_delivery_failures` for outbound webhooks and `integration_delivery_failures` for plugin ingress. Used for debugging and manual redrive.### Docker+Containerization platform for packaging and deploying applications. OpenWA is distributed as a Docker image.## E### Engine+Component that handles communication with WhatsApp Web. OpenWA supports pluggable engines selected via the `ENGINE_TYPE` environment variable: `whatsapp-web.js` (default, Chromium/Puppeteer-based) or `baileys` (browser-free, WebSocket-based).### Event+A system-emitted occurrence, for example:+- `message.received`: New incoming message- `message.ack`: Message status changed- `session.status`: Session status changed@@ -77,211 +97,260 @@ A system-emitted occurrence, for example:## F### Factory Pattern+Design pattern used to create adapter instances based on configuration. Example: `EngineFactory.create()`, which returns the whatsapp-web.js or Baileys adapter for the configured `ENGINE_TYPE`.## G### Group ID+Unique identifier for a WhatsApp group. Format: `[email protected]`.### GHCR+GitHub Container Registry - registry for storing Docker images. The OpenWA image is available at `ghcr.io/rmyndharis/openwa` (and, mirrored per release, at `docker.io/rmyndharis/openwa`).## H### Headless+Browser mode that runs without a GUI. Puppeteer runs Chrome in headless mode.### Health Check+Endpoints to check system health: `/api/health` (basic status and running version), `/api/health/live` (liveness) and `/api/health/ready` (readiness β probes both databases, and reports 503 while the process is draining). All three are public and exempt from rate limiting. The `/api` prefix is applied globally with no exclusions, so the unprefixed paths do not exist β container and Kubernetes probes must use the prefixed form.### Hook+An extension point that allows plugins to intercept and modify processing flows.## I### In-Memory+Data stored in RAM. Fast but non-persistent β lost on restart. Independent of Redis, several in-process caches always run: the LIDβphone map, the Baileys session store's LRU maps, and the live-engine registry.## J### JID (Jabber ID)-WhatsApp's id format, inherited from XMPP; the user-facing "Chat ID" is a JID. The same entity can be addressed in more than one dialect: `<phone>@c.us` (whatsapp-web.js, and OpenWA's neutral form), `<phone>@s.whatsapp.net` (Baileys' raw form for the same user), `<id>@g.us` (a group), or `<lid>@lid` (a LID, a privacy id). OpenWA normalizes engine ids to a single neutral dialect at the engine boundary - see *System Architecture > WhatsApp Identity Contract*.++WhatsApp's id format, inherited from XMPP; the user-facing "Chat ID" is a JID. The same entity can be addressed in more than one dialect: `<phone>@c.us` (whatsapp-web.js, and OpenWA's neutral form), `<phone>@s.whatsapp.net` (Baileys' raw form for the same user), `<id>@g.us` (a group), or `<lid>@lid` (a LID, a privacy id). OpenWA normalizes engine ids to a single neutral dialect at the engine boundary - see _System Architecture > WhatsApp Identity Contract_.### Job Queue+Queueing system for asynchronous task processing. OpenWA registers exactly two queues β `webhook-queue` and `ingress-queue` β both optional (`QUEUE_ENABLED`). There is no scheduled or delayed sending: outbound messages are dispatched inline by the request that asks for them.## L### LID (Linked ID)-A WhatsApp **privacy identifier** (`<number>@lid`) that addresses a user without exposing their phone number - increasingly used in groups and communities. Its number is **not** a phone number; a separate `lid -> phone` mapping (supplied by WhatsApp via history sync / contacts) resolves it when known. OpenWA keeps an unresolved LID as-is rather than guessing a phone. See *System Architecture > WhatsApp Identity Contract*.++A WhatsApp **privacy identifier** (`<number>@lid`) that addresses a user without exposing their phone number - increasingly used in groups and communities. Its number is **not** a phone number; a separate `lid -> phone` mapping (supplied by WhatsApp via history sync / contacts) resolves it when known. OpenWA keeps an unresolved LID as-is rather than guessing a phone. See _System Architecture > WhatsApp Identity Contract_.### Linked Device+WhatsApp feature that allows up to 4 additional devices to be linked to one account without requiring an active phone connection.### Lucide+Icon library used in the dashboard. A fork of Feather Icons with more icons.## M### Message Queue-Not a component of OpenWA. Outbound sends are synchronous; the only queues are `webhook-queue` (outbound webhook delivery) and `ingress-queue` (inbound plugin events) β see *Job Queue*. Bulk sending paces itself with a per-message delay rather than a queue.++Not a component of OpenWA. Outbound sends are synchronous; the only queues are `webhook-queue` (outbound webhook delivery) and `ingress-queue` (inbound plugin events) β see _Job Queue_. Bulk sending paces itself with a per-message delay rather than a queue.### Middleware+Function executed before a request handler in NestJS. Used for logging, authentication, etc.### MinIO+Object storage server compatible with the S3 API. Can be used as a self-hosted alternative to S3.### Multi-session+Ability to run multiple WhatsApp sessions within a single OpenWA instance.## N### NestJS+Node.js framework for building server-side applications. The OpenWA backend is built with NestJS.### Node.js+JavaScript runtime used to run OpenWA. Recommended version: Node.js 22 LTS.## O### ORM (Object-Relational Mapping)+Library that maps objects in code to database tables. OpenWA uses TypeORM.### OpenWA+Open-source WhatsApp API gateway. This project.## P### Payload+Data sent in an HTTP request body or webhook delivery.### Plugin+Extension that can be added to OpenWA to add functionality without modifying the core codebase.### PostgreSQL+Relational database recommended for production deployments with multiple sessions.### Puppeteer+Node.js library for controlling Chrome/Chromium. Used by whatsapp-web.js.### Push Name+Display name shown in a user's WhatsApp profile.## Q### QR Code+Code that must be scanned in WhatsApp on a phone to connect a new session.### Queue+Queue for processing tasks sequentially and asynchronously.## R### Rate Limiting+Limiting request volume over time to prevent abuse and WhatsApp bans.### Redis+In-memory data store used for:+- Caching (`REDIS_CACHE_DB`)- Job queues (with BullMQ)- Rate-limit (throttler) counters### REST API+Architectural style for APIs used by OpenWA. Uses HTTP methods (GET, POST, PUT, DELETE).### Retry+Mechanism to retry failed operations, e.g., webhook delivery.## S### S3 (Simple Storage Service)+AWS object storage service. OpenWA supports S3-compatible storage for media files.### Session+An instance of a WhatsApp Web connection. One phone number = one session.### SQLite+Embedded database used as the default for minimal deployments.### Strategy Pattern+Design pattern that allows selecting an algorithm/implementation at runtime. Used for pluggable adapters.### Swagger+API documentation tool. OpenWA provides Swagger UI at `/api/docs`.## T### TanStack Query+Library for data fetching and caching in React. Previously known as React Query.### TypeORM+ORM for TypeScript/JavaScript that supports multiple databases.### TypeScript+Typed superset of JavaScript used for OpenWA development.## V### Vite+Build tool and dev server for frontend. Used for the dashboard.### Volume (Docker)+Persistent storage for Docker containers. OpenWA data is stored in volumes.## W### WAHA+WhatsApp HTTP API - a similar project that inspired OpenWA. OpenWA is built as an open-source alternative.### WAL (Write-Ahead Logging)+SQLite journaling mode that improves concurrency. Recommended for production.### Webhook+HTTP callback to send events to external systems when messages or other events occur.### WebSocket+Protocol for real-time bidirectional communication. Used for:+- Dashboard real-time updates- WhatsApp Web protocol (internal)### whatsapp-web.js+Default engine library used by OpenWA to interact with WhatsApp Web. Uses Puppeteer to control a headless Chromium browser. Selected via `ENGINE_TYPE=whatsapp-web.js` (or by omitting the env var).---## Abbreviations-| Abbr | Full Form |-|------|-----------|-| API | Application Programming Interface |-| CRUD | Create, Read, Update, Delete |-| DI | Dependency Injection |-| DLQ | Dead Letter Queue |-| DTO | Data Transfer Object |-| GHCR | GitHub Container Registry |-| HA | High Availability |-| HTTP | HyperText Transfer Protocol |-| JID | Jabber ID |-| JWT | JSON Web Token |-| LTS | Long Term Support |-| MVP | Minimum Viable Product |-| ORM | Object-Relational Mapping |-| QR | Quick Response |-| RAM | Random Access Memory |-| REST | Representational State Transfer |-| S3 | Simple Storage Service |-| SDK | Software Development Kit |-| SOP | Standard Operating Procedure |-| SQL | Structured Query Language |-| SSL | Secure Sockets Layer |-| TLS | Transport Layer Security |-| TTL | Time To Live |-| UI | User Interface |-| URL | Uniform Resource Locator |-| WAL | Write-Ahead Logging |-| WS | WebSocket |+| Abbr | Full Form |+| ---- | --------------------------------- |+| API | Application Programming Interface |+| CRUD | Create, Read, Update, Delete |+| DI | Dependency Injection |+| DLQ | Dead Letter Queue |+| DTO | Data Transfer Object |+| GHCR | GitHub Container Registry |+| HA | High Availability |+| HTTP | HyperText Transfer Protocol |+| JID | Jabber ID |+| JWT | JSON Web Token |+| LTS | Long Term Support |+| MVP | Minimum Viable Product |+| ORM | Object-Relational Mapping |+| QR | Quick Response |+| RAM | Random Access Memory |+| REST | Representational State Transfer |+| S3 | Simple Storage Service |+| SDK | Software Development Kit |+| SOP | Standard Operating Procedure |+| SQL | Structured Query Language |+| SSL | Secure Sockets Layer |+| TLS | Transport Layer Security |+| TTL | Time To Live |+| UI | User Interface |+| URL | Uniform Resource Locator |+| WAL | Write-Ahead Logging |+| WS | WebSocket |+---<div align="center">diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.mdindex e10986baa..329347804 100644--- a/docs/22-n8n-integration.md+++ b/docs/22-n8n-integration.md@@ -73,28 +73,28 @@ Start workflows when WhatsApp events occur.#### Supported Events-| Event | Description | Use Case |-| ----------------------- | ----------------------------------- | ------------------------- |-| `message.received` | New incoming message | Auto-reply, lead capture |-| `message.sent` | Message sent successfully | Delivery confirmation |-| `message.ack` | Delivery/read status advanced | Read receipts |-| `message.failed` | Outgoing message failed | Failure alerting |-| `message.revoked` | Message deleted for everyone | Deletion tracking |-| `message.reaction` | Reaction added / changed / removed | Reaction tracking |-| `message.edited` | Message body or caption edited | Content synchronization |-| `status.received` | Contact posted a Status update | Status archiving |-| `session.status` | Session status changed | Lifecycle tracking |-| `session.qr` | QR code generated | Reconnection alerts |-| `session.authenticated` | Session logged in (phone available) | Startup notifications |-| `session.disconnected` | Session lost connection | Alert monitoring |-| `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting |-| `session.restriction` | WhatsApp restricted the account, or lifted it | Pausing outreach while an account is limited |-| `presence.update` | A watched chat's online/typing state changed | Live agent hand-off, presence-aware routing |-| `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended | Missed-call follow-up, call logging |-| `group.join` | Participant(s) joined a group | Welcome messages |-| `group.leave` | Participant(s) left a group | Churn tracking |-| `group.update` | Group subject/description/settings changed | Group administration |-| `call.received` | Incoming call started ringing | Auto-reject + auto-reply bots |+| Event | Description | Use Case |+| ------------------------------------------------- | --------------------------------------------- | -------------------------------------------- |+| `message.received` | New incoming message | Auto-reply, lead capture |+| `message.sent` | Message sent successfully | Delivery confirmation |+| `message.ack` | Delivery/read status advanced | Read receipts |+| `message.failed` | Outgoing message failed | Failure alerting |+| `message.revoked` | Message deleted for everyone | Deletion tracking |+| `message.reaction` | Reaction added / changed / removed | Reaction tracking |+| `message.edited` | Message body or caption edited | Content synchronization |+| `status.received` | Contact posted a Status update | Status archiving |+| `session.status` | Session status changed | Lifecycle tracking |+| `session.qr` | QR code generated | Reconnection alerts |+| `session.authenticated` | Session logged in (phone available) | Startup notifications |+| `session.disconnected` | Session lost connection | Alert monitoring |+| `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting |+| `session.restriction` | WhatsApp restricted the account, or lifted it | Pausing outreach while an account is limited |+| `presence.update` | A watched chat's online/typing state changed | Live agent hand-off, presence-aware routing |+| `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended | Missed-call follow-up, call logging |+| `group.join` | Participant(s) joined a group | Welcome messages |+| `group.leave` | Participant(s) left a group | Churn tracking |+| `group.update` | Group subject/description/settings changed | Group administration |+| `call.received` | Incoming call started ringing | Auto-reject + auto-reply bots |#### How It Worksdiff --git a/docs/23-community-integrations.md b/docs/23-community-integrations.mdindex 9a6f03146..63615ecd0 100644--- a/docs/23-community-integrations.md+++ b/docs/23-community-integrations.md@@ -10,8 +10,8 @@ Third-party integrations and adapters built by the community on top of OpenWA's> They may lag behind OpenWA API changes. Verify compatibility and review the source before using> them in production.-| Integration | Platform | Source | Notes |-| --- | --- | --- | --- |+| Integration | Platform | Source | Notes |+| ------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- || **ioBroker.openwa** | [ioBroker](https://www.iobroker.net/) (home / IoT automation) | [ThorstenBoettler/ioBroker.openwa](https://github.com/ThorstenBoettler/ioBroker.openwa) Β· [npm](https://www.npmjs.com/package/iobroker.openwa) | Send text / image / video / audio / document messages to chats and groups through OpenWA's REST API, with Blockly blocks. Early stage. |Maintain an integration built on OpenWA and want it listed here? Open a PR adding a row (or an issue), including the repository link and a one-line description.diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 0d055b156..6ecca629c 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -20,13 +20,13 @@| **Per-key rate limiter** | β Implemented | `src/modules/mcp/mcp-rate-limit.ts` || **Result shaping (smart/json)** | β Implemented | `src/modules/mcp/tool-result.ts` |-| Capability | Status | Notes |-| --------------------------------- | -------------- | ----------------------------------------------------------------------- |-| **Read-only mode** | β Implemented | **Default read-only**; set `MCP_READONLY=false` to expose write tools |-| **OAuth 2.1 (public exposure)** | π Planned | Static API key is used today (suitable for self-hosted/internal) |-| **Agent-action audit provenance** | π Planned | Mark audited actions as agent-initiated |-| **Env-tunable rate limits** | β Implemented | `MCP_RATE_LIMIT_MAX` / `MCP_RATE_LIMIT_WINDOW_MS` |-| **Additional tool domains** | π Planned | templates / channels / catalog / status (labels/automation now ship) |+| Capability | Status | Notes |+| --------------------------------- | -------------- | --------------------------------------------------------------------- |+| **Read-only mode** | β Implemented | **Default read-only**; set `MCP_READONLY=false` to expose write tools |+| **OAuth 2.1 (public exposure)** | π Planned | Static API key is used today (suitable for self-hosted/internal) |+| **Agent-action audit provenance** | π Planned | Mark audited actions as agent-initiated |+| **Env-tunable rate limits** | β Implemented | `MCP_RATE_LIMIT_MAX` / `MCP_RATE_LIMIT_WINDOW_MS` |+| **Additional tool domains** | π Planned | templates / channels / catalog / status (labels/automation now ship) |---diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 7c07797da..e041253c7 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -2,7 +2,7 @@> **Status:** Shipped. The core substrate, operator provisioning (an ADMIN instance API and a dashboard> **Instances** tab), and the official ingress adapters are all in place; the public SDK reference is-> still to come (P4). This document describes the architecture and the design rationale β *why* it is+> still to come (P4). This document describes the architecture and the design rationale β _why_ it is> built this way β not a how-to or an API reference (see> [15 - Project Roadmap](./15-project-roadmap.md) for the phase table).@@ -27,7 +27,7 @@ public contract β Integration SDK v1** β because the contract, not any singl## 25.2 Design principle: one new primitive, everything else a clone-The overriding goal is to preserve the untrusted-worker safety invariants *by construction*. OpenWA+The overriding goal is to preserve the untrusted-worker safety invariants _by construction_. OpenWAplugins run in a capability-gated worker thread with no ambient host access (see[30 - Plugin Sandboxing](./30-plugin-sandboxing.md)). Every hostβworker message is a serializable POJOacross a `structuredClone` boundary; host-initiated calls fail open on a timeout and drain on a worker@@ -37,15 +37,15 @@ host-side.Rather than invent new machinery that would have to re-earn those properties, the Integration Fabric is**~90% a faithful clone of seams OpenWA already ships**:-| Concern | Cloned from |-| ------- | ----------- |-| Hostβworker dispatch with fail-open timeout + crash-drain | the existing hook bridge |-| Workerβhost capability calls | the existing capability router |-| Durable delivery with retry + dead-letter | the outbound webhook queue and DLQ |-| Identity mapping table (no foreign key, last-write-wins) | the LIDβphone mapping table |-| Inbound deduplication (insert-or-skip on a unique key) | the inbound-message dedup oracle |-| SSRF-guarded egress | `ctx.net.fetch` (reused verbatim) |-| Secret masking on read | the plugin config redaction utility |+| Concern | Cloned from |+| --------------------------------------------------------- | ----------------------------------- |+| Hostβworker dispatch with fail-open timeout + crash-drain | the existing hook bridge |+| Workerβhost capability calls | the existing capability router |+| Durable delivery with retry + dead-letter | the outbound webhook queue and DLQ |+| Identity mapping table (no foreign key, last-write-wins) | the LIDβphone mapping table |+| Inbound deduplication (insert-or-skip on a unique key) | the inbound-message dedup oracle |+| SSRF-guarded egress | `ctx.net.fetch` (reused verbatim) |+| Secret masking on read | the plugin config redaction utility |Exactly **one** genuinely new primitive exists: a hostβworker RPC that returns an **HTTP status + body**from a sandboxed worker β inbound webhook ingress. It is modelled line-for-line on the hook bridge so its@@ -115,7 +115,7 @@ Alongside this async pipeline, a route may additionally declare a `response` conhost-side to the message service, so persistence and the message hook chain are preserved. It is gatedby a `conversation:send` permission and the instance's session scope.- **Identity, dedup, and DLQ tables** β see Β§25.5.-- **Ingress queue** β a durable BullMQ queue that is a *sibling* of the outbound webhook queue (its own+- **Ingress queue** β a durable BullMQ queue that is a _sibling_ of the outbound webhook queue (its ownworker, not the reordering webhook worker), with exponential-backoff retries and a dead-letter row onthe final attempt.@@ -185,7 +185,7 @@ Four tables live on the data connection, each created by a hand-authored dual-disupported ingress body formats and fail verification/content handling rather than being re-serialized.- **Egress.** The only outbound path remains the existing SSRF-guarded `ctx.net.fetch`, scoped to themanifest's allowed hosts.-- **Re-entrancy.** A reply issued *inside* an ingress handler seeds the in-flight hook set, so an adapter's+- **Re-entrancy.** A reply issued _inside_ an ingress handler seeds the in-flight hook set, so an adapter'sown outbound message hook cannot echo-loop the reply back out to the external system.## 25.7 Scale and durability@@ -245,7 +245,7 @@ signed over `${id}.${timestamp}.${rawBody}`), so only `toleranceSec` (falling ba`encoding`, `prefix`, and `timestampHeader` are ignored, and theoperator pastes the provider's Svix secret (`v1,whsec_<base64>`) as the instance secret. It is therecommended scheme for Standard-Webhooks providers: because the `session-alive` preflight (Β§25.4) runs-*after* signature verification, an unauthenticated caller can no longer use that preflight as a liveness+_after_ signature verification, an unauthenticated caller can no longer use that preflight as a livenessoracle on a route that previously declared `scheme: "none"`. The existing `hmac-sha256`/`shared-secret`/`none` behavior is unchanged. For `hmac-sha256`, declaring `timestampHeader` always activates the replaywindow (Β§25.6) β declare it together with a `contentTemplate` that includes `{timestamp}` so the checkeddiff --git a/docs/26-global-search.md b/docs/26-global-search.mdindex 88f7e2b83..65a3ea84e 100644--- a/docs/26-global-search.md+++ b/docs/26-global-search.md@@ -26,8 +26,8 @@ Search is backed by an open `SearchProvider` contract, not a hardcoded query pat```tsinterface SearchProvider {- readonly id: string; // e.g. 'builtin-fts'- readonly label: string; // human label for dashboard/config+ readonly id: string; // e.g. 'builtin-fts'+ readonly label: string; // human label for dashboard/configsearch(query: SearchQuery): Promise<SearchResults>;health(): Promise<SearchHealth>; // provider liveness; not yet surfaced on any route}@@ -91,11 +91,11 @@ it into Postgres). Concretely:All search configuration lives in the environment (`.env` / Compose / dashboard Infrastructure form):-| Variable | Default | Meaning |-| --- | --- | --- |-| `SEARCH_ENABLED` | `true` (unset) | Set to `false` to remove the `/search` route and the entire search module β zero footprint, no DI wiring. The migration still runs (so the index is ready if you re-enable). |-| `SEARCH_PROVIDER` | `auto` | `auto` selects the built-in provider at runtime and lets an enabled plugin provider supersede it; `builtin-fts` pins the built-in explicitly; `none` leaves the registry empty β the module and the route stay mounted, but with no active provider `/api/search` answers `501`. Those three are the only accepted values β anything else (including a plugin id) fails boot. |-| `SEARCH_LIMIT_MAX` | `100` | Hard cap applied to the `limit` query parameter, so a caller cannot request an unbounded result set. |+| Variable | Default | Meaning |+| ------------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `SEARCH_ENABLED` | `true` (unset) | Set to `false` to remove the `/search` route and the entire search module β zero footprint, no DI wiring. The migration still runs (so the index is ready if you re-enable). |+| `SEARCH_PROVIDER` | `auto` | `auto` selects the built-in provider at runtime and lets an enabled plugin provider supersede it; `builtin-fts` pins the built-in explicitly; `none` leaves the registry empty β the module and the route stay mounted, but with no active provider `/api/search` answers `501`. Those three are the only accepted values β anything else (including a plugin id) fails boot. |+| `SEARCH_LIMIT_MAX` | `100` | Hard cap applied to the `limit` query parameter, so a caller cannot request an unbounded result set. |### The opt-out footprint notediff --git a/docs/27-plugin-search-providers.md b/docs/27-plugin-search-providers.mdindex 7ebb31c4d..6c4ec289b 100644--- a/docs/27-plugin-search-providers.md+++ b/docs/27-plugin-search-providers.md@@ -26,8 +26,14 @@ user-facing feature and the built-in DB-FTS default.The manifest must declare `search:provide`:```json-{ "id": "meili", "name": "Meilisearch", "version": "1.0.0", "type": "extension",- "main": "index.cjs", "permissions": ["search:provide"] }+{+ "id": "meili",+ "name": "Meilisearch",+ "version": "1.0.0",+ "type": "extension",+ "main": "index.cjs",+ "permissions": ["search:provide"]+}```Without it the host ignores the registration and logs one warning@@ -86,10 +92,10 @@ The core fires `message:persisted` for every live message (outbound on send, inbfor history backfill. Register a handler to keep your index in sync:```ts-ctx.registerHook('message:persisted', async (hookCtx) => {+ctx.registerHook('message:persisted', async hookCtx => {const { sessionId, message } = hookCtx.data;// message carries: id, waMessageId, sessionId, chatId, body, from, to, type, direction, timestamp, β¦- await myBackend.index(message); // fire-and-forget is fine; an error here doesn't break the send/receive+ await myBackend.index(message); // fire-and-forget is fine; an error here doesn't break the send/receive});```@@ -103,7 +109,7 @@ merged into the echo's row and then dropped. The core emits `message:persisted`(upsert it) followed by `message:deleted` for the dropped one β delete that document by its `id`:```ts-ctx.registerHook('message:deleted', async (hookCtx) => {+ctx.registerHook('message:deleted', async hookCtx => {const { message } = hookCtx.data;await myBackend.delete(message.id);});@@ -140,6 +146,7 @@ plugins/my-search/```**manifest.json:**+```json{"id": "my-search",@@ -151,21 +158,22 @@ plugins/my-search/```**index.js:**+```jsmodule.exports = class MySearchPlugin {async onEnable(ctx) {// 1. Index every persisted message (live traffic only β backfill separately at onEnable).- ctx.registerHook('message:persisted', async (hookCtx) => {+ ctx.registerHook('message:persisted', async hookCtx => {const { message } = hookCtx.data;await this._index(ctx, message);});// 2. Answer search queries.- ctx.registerSearchProvider(async (query) => {+ ctx.registerSearchProvider(async query => {const start = Date.now();const results = await this._search(ctx, query); // your backend's queryreturn {- hits: results.rows.map((r) => ({+ hits: results.rows.map(r => ({messageId: String(r.id),waMessageId: r.waMessageId ?? '',sessionId: r.sessionId,@@ -186,9 +194,15 @@ module.exports = class MySearchPlugin {}// Your backend-specific methods:- async _index(ctx, message) { /* upsert into your index */ }- async _search(ctx, query) { /* run your backend's query, honoring query.q + filters + limit/offset */ return { rows: [], total: 0 }; }- _highlight(body, term) { return body.replace(new RegExp(term, 'gi'), '<mark>$&</mark>'); }+ async _index(ctx, message) {+ /* upsert into your index */+ }+ async _search(ctx, query) {+ /* run your backend's query, honoring query.q + filters + limit/offset */ return { rows: [], total: 0 };+ }+ _highlight(body, term) {+ return body.replace(new RegExp(term, 'gi'), '<mark>$&</mark>');+ }// Optional: report backend health to the /search health check.async healthCheck() {diff --git a/docs/28-multitenancy.md b/docs/28-multitenancy.mdindex abc43ed62..8b79c8117 100644--- a/docs/28-multitenancy.md+++ b/docs/28-multitenancy.md@@ -25,13 +25,13 @@OpenWA today is **multi-session, not multi-tenant**. What already exists and is reused by this design:-| Primitive | Where | Reuse |-|---|---|---|-| Many WhatsApp sessions per deployment, engine-isolated | `session.service.ts` | Sessions become tenant-owned resources |+| Primitive | Where | Reuse |+| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |+| Many WhatsApp sessions per deployment, engine-isolated | `session.service.ts` | Sessions become tenant-owned resources || API keys with roles (`ADMIN/OPERATOR/VIEWER`) and an `allowedSessions` scope; list + stats already scope-filtered | `api-key.entity.ts:37`, `api-key.guard.ts:64-77`, `session.controller.ts:68-70` | Evolves into tenant-scoped keys; the enforcement pattern (guard-level session resolution) is exactly where tenant checks plug in |-| Per-session plugin activation and per-session config overrides | `sessionConfig` in the plugin loader | Per-tenant plugin policy on top |-| All business data keyed by `sessionId` | messages, audit_log, webhooks, templates | Adding `tenantId` alongside is mechanical |-| Per-request ALS actor stamping (audit attribution) | `request-context.ts` | Audit gains `tenantId` at the same point |+| Per-session plugin activation and per-session config overrides | `sessionConfig` in the plugin loader | Per-tenant plugin policy on top |+| All business data keyed by `sessionId` | messages, audit_log, webhooks, templates | Adding `tenantId` alongside is mechanical |+| Per-request ALS actor stamping (audit attribution) | `request-context.ts` | Audit gains `tenantId` at the same point |**The gaps** (what makes it not multi-tenant today): no tenant entity, no named users ormemberships, dashboard identity is the API key itself, all branding is global (engine device name,@@ -46,8 +46,8 @@ boundary.quotas, and a data partition. Identified by `tenantId` (uuid) + a stable `slug`.- **Membership** β a named **user**'s relationship to a tenant, with a **tenant role**(`owner`, `admin`, `operator`, `viewer`). One user may belong to many tenants.-- **Tenant role vs platform role** β today's global `ApiKeyRole` becomes the *platform* role; the- tenant role governs what a user/key may do *inside* one tenant. The full matrix is in 28.5.3.+- **Tenant role vs platform role** β today's global `ApiKeyRole` becomes the _platform_ role; the+ tenant role governs what a user/key may do _inside_ one tenant. The full matrix is in 28.5.3.Everything tenant-owned carries `tenantId`: sessions, API keys, users (via memberships), pluginactivations, webhook endpoints, templates, and every row derived from sessions (messages, audit,@@ -59,11 +59,11 @@ message tables is required).Chosen: **shared database, `tenantId` on every tenant-owned row, enforced at the service/guardboundary** β the same boundary that already enforces `allowedSessions` today.-| Option | Verdict | Why |-|---|---|---|-| Row-level (`tenantId` columns, shared schema) | **Chosen** | Matches the existing `sessionId` pattern, zero-infra migration, per-tenant backup/filtering still possible, and PostgreSQL RLS remains a later hardening option |-| Schema-per-tenant (Postgres) | Later option | Real isolation at the DB layer, but migrations Γ N tenants and cross-tenant platform tables get awkward; revisit if a customer contract demands it |-| Database-per-tenant | Rejected for now | Operational complexity (migrations, pooling, backup orchestration) buys little at this scale |+| Option | Verdict | Why |+| --------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Row-level (`tenantId` columns, shared schema) | **Chosen** | Matches the existing `sessionId` pattern, zero-infra migration, per-tenant backup/filtering still possible, and PostgreSQL RLS remains a later hardening option |+| Schema-per-tenant (Postgres) | Later option | Real isolation at the DB layer, but migrations Γ N tenants and cross-tenant platform tables get awkward; revisit if a customer contract demands it |+| Database-per-tenant | Rejected for now | Operational complexity (migrations, pooling, backup orchestration) buys little at this scale |Hard rule: **no query returns rows without a tenant predicate**. The guard resolves the tenantcontext once per request (from key/user + route session) and the service layer composes with it β@@ -97,17 +97,17 @@ shared API keys already outgrew "one strong secret is enough".### 28.5.3 Role matrix (target)-| Capability | Platform admin | Tenant owner | Tenant admin | Tenant operator | Tenant viewer |-|---|---|---|---|---|---|-| Provision/suspend tenants | β | β | β | β | β |-| Manage tenant members & roles | β | β | β | β | β |-| Manage tenant API keys | β | β | β | β | β |-| Create/delete sessions | β | β | β | β | β |-| Send messages, manage webhooks/templates | β | β | β | β | β |-| View sessions, messages, logs | β | β | β | β | β |-| Configure tenant branding | β | β | β | β | β |-| Manage own 2FA | every named user | | | | |-| Reset members' 2FA | β | β | β | β | β |+| Capability | Platform admin | Tenant owner | Tenant admin | Tenant operator | Tenant viewer |+| ---------------------------------------- | ---------------- | ------------ | ------------ | --------------- | ------------- |+| Provision/suspend tenants | β | β | β | β | β |+| Manage tenant members & roles | β | β | β | β | β |+| Manage tenant API keys | β | β | β | β | β |+| Create/delete sessions | β | β | β | β | β |+| Send messages, manage webhooks/templates | β | β | β | β | β |+| View sessions, messages, logs | β | β | β | β | β |+| Configure tenant branding | β | β | β | β | β |+| Manage own 2FA | every named user | | | | |+| Reset members' 2FA | β | β | β | β | β |### 28.5.4 SSO / SCIM (phase 3 markers)@@ -184,7 +184,7 @@ as today.(they become keys of the default tenant).2. Ship behind `MULTITENANCY_ENABLED=true` (default **off**): when off, the tenant layer is ano-op pass-through to the default tenant and behavior is byte-identical to today.-3. Dashboard gains user login as an *additional* method; API-key login stays supported+3. Dashboard gains user login as an _additional_ method; API-key login stays supportedindefinitely.## 28.14 Security model & test matrix@@ -200,12 +200,12 @@ as today.## 28.15 Phasing-| Phase | Contents | Sizing note |-|---|---|---|-| **P0 β Foundations** | Tenant entity + `tenantId` everywhere, default-tenant migration, guard chokepoint, tenant-scoped keys, cross-tenant test matrix, `MULTITENANCY_ENABLED` flag | The platform everything hangs off; largest single block |-| **P1 β Users & 2FA** | users/memberships, email+password login, TOTP enroll/challenge/backup codes, tenant roles matrix, dashboard login + tenant switcher | Independent of P0's data model but layered on it |-| **P2 β Branding, quotas, observability** | per-tenant branding (device name, dashboard, UA), tenant quotas + counters, audit `tenantId`, per-tenant backup/export | Mostly small, parallelizable pieces |-| **P3 β Enterprise extras** | OIDC/SSO, SCIM provisioning, schema-per-tenant evaluation, audit export, impersonation support flow | Only after P0βP2 prove out |+| Phase | Contents | Sizing note |+| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- |+| **P0 β Foundations** | Tenant entity + `tenantId` everywhere, default-tenant migration, guard chokepoint, tenant-scoped keys, cross-tenant test matrix, `MULTITENANCY_ENABLED` flag | The platform everything hangs off; largest single block |+| **P1 β Users & 2FA** | users/memberships, email+password login, TOTP enroll/challenge/backup codes, tenant roles matrix, dashboard login + tenant switcher | Independent of P0's data model but layered on it |+| **P2 β Branding, quotas, observability** | per-tenant branding (device name, dashboard, UA), tenant quotas + counters, audit `tenantId`, per-tenant backup/export | Mostly small, parallelizable pieces |+| **P3 β Enterprise extras** | OIDC/SSO, SCIM provisioning, schema-per-tenant evaluation, audit export, impersonation support flow | Only after P0βP2 prove out |## 28.16 Open questions@@ -214,4 +214,4 @@ as today.2. Should tenant slug be immutable once sessions exist (webhook URLs may embed it later)?3. Is per-message-type or per-recipient rate limiting part of tenant quotas, or left to theexisting anti-abuse layer?-4. Does 2FA enforcement also cover API-key *management* actions (create/revoke), not just login?+4. Does 2FA enforcement also cover API-key _management_ actions (create/revoke), not just login?diff --git a/docs/30-plugin-sandboxing.md b/docs/30-plugin-sandboxing.mdindex b38b7576f..8edb8b66f 100644--- a/docs/30-plugin-sandboxing.md+++ b/docs/30-plugin-sandboxing.md@@ -7,10 +7,10 @@ it does not β and what changes for plugin authors.## Trust tiers-| Tier | Examples | Runs | Capabilities |-|------|----------|------|--------------|-| **Built-in (trusted)** | the two engine adapters (whatsapp-web.js, baileys) | in-process | direct, full speed |-| **Untrusted** | anything in the plugins directory | in a `worker_thread` | only via the host-validated bridge |+| Tier | Examples | Runs | Capabilities |+| ---------------------- | -------------------------------------------------- | -------------------- | ---------------------------------- |+| **Built-in (trusted)** | the two engine adapters (whatsapp-web.js, baileys) | in-process | direct, full speed |+| **Untrusted** | anything in the plugins directory | in a `worker_thread` | only via the host-validated bridge |The loader routes by tier automatically: a plugin registered programmatically is built-in; one loadedfrom disk is untrusted and sandboxed.@@ -18,9 +18,9 @@ from disk is untrusted and sandboxed.## What the sandbox guarantees- **No host-object access.** The worker runs in its own V8 context. It receives no reference to the- loader, the engine, the database, `MessageService`, or any host singleton. Its only channel *to the- host* is a `MessagePort` β not its only channel out, see the limits below.-- **Capability mediation.** A plugin's only *sanctioned* path to WhatsApp / the database / the network+ loader, the engine, the database, `MessageService`, or any host singleton. Its only channel _to the+ host_ is a `MessagePort` β not its only channel out, see the limits below.+- **Capability mediation.** A plugin's only _sanctioned_ path to WhatsApp / the database / the networkis the bridged `ctx.*` surface β `ctx.messages.*`, `ctx.engine.*`, `ctx.storage.*`, `ctx.net.fetch`, and`ctx.conversations` / `ctx.handover` / `ctx.mappings` β which round-trip to the host. The host runseach call through the same permission + session-scope checks an in-process plugin gets@@ -57,8 +57,8 @@ from disk is untrusted and sandboxed.A worker still has access to Node built-ins β `require('fs')`, `process`, network sockets β and runsas the same uid as OpenWA. The sandbox therefore does **not**, by itself, stop a malicious pluginfrom reading files the OpenWA process can read or making outbound network connections. It protects-the *integrity* of the host (no host-object compromise, contained faults, mediated capabilities) β not-the *confidentiality* of the host filesystem against deliberate Node-builtin abuse.+the _integrity_ of the host (no host-object compromise, contained faults, mediated capabilities) β not+the _confidentiality_ of the host filesystem against deliberate Node-builtin abuse.For genuinely untrusted, third-party plugins, combine the sandbox with **OS-level containment**:@@ -106,10 +106,10 @@ Built-in plugins were unaffected and still run in-process.## Configuration-| Constant | Value | Purpose |-|----------|-------|---------|-| `SANDBOX_MAX_OLD_GEN_MB` (worker `maxOldGenerationSizeMb`) | 256 | per-plugin heap cap; OOM kills the worker, not the host |-| `SANDBOX_HOOK_TIMEOUT_MS` | 5000 ms | budget before a sandboxed hook handler is skipped |+| Constant | Value | Purpose |+| ---------------------------------------------------------- | ------- | ------------------------------------------------------- |+| `SANDBOX_MAX_OLD_GEN_MB` (worker `maxOldGenerationSizeMb`) | 256 | per-plugin heap cap; OOM kills the worker, not the host |+| `SANDBOX_HOOK_TIMEOUT_MS` | 5000 ms | budget before a sandboxed hook handler is skipped |Both are hardcoded constants in the plugin loader β **neither is an environment variable**, sochanging either requires a code change.diff --git a/docs/README.md b/docs/README.mdindex 936b4e275..e6773fa95 100644--- a/docs/README.md+++ b/docs/README.md@@ -30,47 +30,47 @@**Full Index (by number)**-| No | Document | Description |-| --- | ---------------------------------------------------------------- | ------------------------------------------------- |-| 01 | [Project Overview](./01-project-overview.md) | Vision, goals, scope, current status |-| 02 | [Requirements Specification](./02-requirements-specification.md) | Functional and non-functional requirements |-| 03 | [System Architecture](./03-system-architecture.md) | Architecture, modules, and runtime flows |-| 04 | [Security Design](./04-security-design.md) | Auth, rate limiting, and security controls |-| 05 | [Database Design](./05-database-design.md) | Entities and storage considerations |-| 06 | [API Specification](./06-api-specification.md) | REST API and WebSocket protocol |-| 07 | [API Collection](./07-api-collection.md) | Example requests and Postman import tips |-| 08 | [Development Guidelines](./08-development-guidelines.md) | Coding standards and workflow |-| 09 | [Testing Strategy](./09-testing-strategy.md) | Test types and tooling |-| 10 | [DevOps & Infrastructure](./10-devops-infrastructure.md) | Docker, deployment, and environment configuration |-| 11 | [Operational Runbooks](./11-operational-runbooks.md) | Incident, maintenance, and backup runbooks |-| 12 | [Troubleshooting FAQ](./12-troubleshooting-faq.md) | Common issues and fixes |-| 13 | [Horizontal Scaling](./13-horizontal-scaling.md) | Multi-node deployment guidance |-| 14 | [Migration Guide](./14-migration-guide.md) | Upgrade and data migration guidance |-| 15 | [Project Roadmap](./15-project-roadmap.md) | Near-term and long-term roadmap |-| 16 | [Risk Management](./16-risk-management.md) | Risks and mitigations |-| 17 | [Dashboard Design](./17-dashboard-design.md) | Dashboard UX overview |-| 18 | [SDK Design](./18-sdk-design.md) | SDK plans and conventions |-| 19 | [Plugin Architecture](./19-plugin-architecture.md) | Extensibility concepts |-| 20 | [Community Guidelines](./20-community-guidelines.md) | Contribution and governance |-| 21 | [Glossary](./21-glossary.md) | Terms and definitions |-| 22 | [n8n Integration](./22-n8n-integration.md) | n8n community nodes for OpenWA |-| 23 | [Community Integrations](./23-community-integrations.md) | Third-party adapters built on the OpenWA API |-| 24 | [MCP Integration](./24-mcp-integration.md) | Model Context Protocol tools and auth model |-| 25 | [Integration Fabric](./25-integration-fabric.md) | Inbound webhook substrate for plugin integrations |-| 26 | [Global Search](./26-global-search.md) | Cross-session message search and the provider model |-| 27 | [Plugin Search Providers](./27-plugin-search-providers.md) | Writing a search-provider plugin |-| 28 | [Multitenancy](./28-multitenancy.md) | Multi-tenant target design (draft proposal) |-| 29 | [Engine Capability Matrix](./29-engine-capability-matrix.md) | Per-engine capability support, gaps, and roadmap |-| 30 | [Plugin Sandboxing](./30-plugin-sandboxing.md) | Worker isolation, capabilities, and plugin limits |+| No | Document | Description |+| --- | ---------------------------------------------------------------- | --------------------------------------------------- |+| 01 | [Project Overview](./01-project-overview.md) | Vision, goals, scope, current status |+| 02 | [Requirements Specification](./02-requirements-specification.md) | Functional and non-functional requirements |+| 03 | [System Architecture](./03-system-architecture.md) | Architecture, modules, and runtime flows |+| 04 | [Security Design](./04-security-design.md) | Auth, rate limiting, and security controls |+| 05 | [Database Design](./05-database-design.md) | Entities and storage considerations |+| 06 | [API Specification](./06-api-specification.md) | REST API and WebSocket protocol |+| 07 | [API Collection](./07-api-collection.md) | Example requests and Postman import tips |+| 08 | [Development Guidelines](./08-development-guidelines.md) | Coding standards and workflow |+| 09 | [Testing Strategy](./09-testing-strategy.md) | Test types and tooling |+| 10 | [DevOps & Infrastructure](./10-devops-infrastructure.md) | Docker, deployment, and environment configuration |+| 11 | [Operational Runbooks](./11-operational-runbooks.md) | Incident, maintenance, and backup runbooks |+| 12 | [Troubleshooting FAQ](./12-troubleshooting-faq.md) | Common issues and fixes |+| 13 | [Horizontal Scaling](./13-horizontal-scaling.md) | Multi-node deployment guidance |+| 14 | [Migration Guide](./14-migration-guide.md) | Upgrade and data migration guidance |+| 15 | [Project Roadmap](./15-project-roadmap.md) | Near-term and long-term roadmap |+| 16 | [Risk Management](./16-risk-management.md) | Risks and mitigations |+| 17 | [Dashboard Design](./17-dashboard-design.md) | Dashboard UX overview |+| 18 | [SDK Design](./18-sdk-design.md) | SDK plans and conventions |+| 19 | [Plugin Architecture](./19-plugin-architecture.md) | Extensibility concepts |+| 20 | [Community Guidelines](./20-community-guidelines.md) | Contribution and governance |+| 21 | [Glossary](./21-glossary.md) | Terms and definitions |+| 22 | [n8n Integration](./22-n8n-integration.md) | n8n community nodes for OpenWA |+| 23 | [Community Integrations](./23-community-integrations.md) | Third-party adapters built on the OpenWA API |+| 24 | [MCP Integration](./24-mcp-integration.md) | Model Context Protocol tools and auth model |+| 25 | [Integration Fabric](./25-integration-fabric.md) | Inbound webhook substrate for plugin integrations |+| 26 | [Global Search](./26-global-search.md) | Cross-session message search and the provider model |+| 27 | [Plugin Search Providers](./27-plugin-search-providers.md) | Writing a search-provider plugin |+| 28 | [Multitenancy](./28-multitenancy.md) | Multi-tenant target design (draft proposal) |+| 29 | [Engine Capability Matrix](./29-engine-capability-matrix.md) | Per-engine capability support, gaps, and roadmap |+| 30 | [Plugin Sandboxing](./30-plugin-sandboxing.md) | Worker isolation, capabilities, and plugin limits |**Examples**-| Example | Description |-| ------- | ----------- |-| [Session Phone-Number Pairing](./examples/session-phone-number-pairing.md) | Link an existing WhatsApp account by phone number instead of scanning QR |-| [Chat History Limits](./examples/chat-history-limits.md) | Understand local message history vs bounded live WhatsApp history |-| [Webhook Signature Verification](./examples/webhook-signature-verification.md) | Verify signed OpenWA webhook deliveries in Node.js and Python |-| [n8n Appointment Booking Workflow](./examples/n8n-appointment-booking.md) | Build an appointment-booking flow with OpenWA and n8n |+| Example | Description |+| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |+| [Session Phone-Number Pairing](./examples/session-phone-number-pairing.md) | Link an existing WhatsApp account by phone number instead of scanning QR |+| [Chat History Limits](./examples/chat-history-limits.md) | Understand local message history vs bounded live WhatsApp history |+| [Webhook Signature Verification](./examples/webhook-signature-verification.md) | Verify signed OpenWA webhook deliveries in Node.js and Python |+| [n8n Appointment Booking Workflow](./examples/n8n-appointment-booking.md) | Build an appointment-booking flow with OpenWA and n8n |## Quick Start@@ -181,39 +181,39 @@ socket.on('message', msg => {## Features (Current)-| Feature | Status |-| ------------------------------- | ----------------------------- |-| REST API for WhatsApp | Ready |-| WebSocket Events (Socket.IO) | Ready |-| Multi-session Support | Ready |-| Web Dashboard | Ready |-| Docker Deployment | Ready |-| Webhooks with HMAC Signature | Ready |-| SQLite / PostgreSQL Storage | Ready |-| API Key Authentication & Roles | Ready |-| CIDR IP Whitelisting | Ready |-| Rate Limiting | Ready |-| Audit Logging | Ready |-| Groups / Contacts / Labels API | Ready |-| Channels / Status API | Experimental (engine-limited) |-| Catalog / Product API | Endpoints defined; `501` on both engines |-| Pluggable Engine (wwebjs / Baileys) | Ready (set `ENGINE_TYPE`) |-| Plugin Extension System | Ready |-| Queue-based Webhook Retries | Optional (QUEUE_ENABLED=true) |+| Feature | Status |+| ----------------------------------- | ---------------------------------------- |+| REST API for WhatsApp | Ready |+| WebSocket Events (Socket.IO) | Ready |+| Multi-session Support | Ready |+| Web Dashboard | Ready |+| Docker Deployment | Ready |+| Webhooks with HMAC Signature | Ready |+| SQLite / PostgreSQL Storage | Ready |+| API Key Authentication & Roles | Ready |+| CIDR IP Whitelisting | Ready |+| Rate Limiting | Ready |+| Audit Logging | Ready |+| Groups / Contacts / Labels API | Ready |+| Channels / Status API | Experimental (engine-limited) |+| Catalog / Product API | Endpoints defined; `501` on both engines |+| Pluggable Engine (wwebjs / Baileys) | Ready (set `ENGINE_TYPE`) |+| Plugin Extension System | Ready |+| Queue-based Webhook Retries | Optional (QUEUE_ENABLED=true) |## Tech Stack-| Layer | Technology |-| --------- | ----------------------------- |-| Runtime | Node.js 22 LTS |-| Framework | NestJS 11.x |-| Language | TypeScript 6.x |+| Layer | Technology |+| --------- | --------------------------------------------------------------- |+| Runtime | Node.js 22 LTS |+| Framework | NestJS 11.x |+| Language | TypeScript 6.x || WA Engine | Pluggable (`ENGINE_TYPE`): whatsapp-web.js (default) or Baileys |-| WebSocket | Socket.IO |-| Database | SQLite (default) / PostgreSQL |-| ORM | TypeORM |-| Container | Docker + Docker Compose |-| Dashboard | React + Vite + TanStack Query |+| WebSocket | Socket.IO |+| Database | SQLite (default) / PostgreSQL |+| ORM | TypeORM |+| Container | Docker + Docker Compose |+| Dashboard | React + Vite + TanStack Query |## Project Structurediff --git a/docs/examples/chat-history-limits.md b/docs/examples/chat-history-limits.mdindex a694e0ac4..22f4cd4f8 100644--- a/docs/examples/chat-history-limits.md+++ b/docs/examples/chat-history-limits.md@@ -31,7 +31,7 @@ The endpoint is intentionally bounded:## How Deep It Can ReachBy default the live history endpoint returns at most the **100 most recent** messages per request (the-`limit` clamp above). The `whatsapp-web.js` engine *can* load older messages on demand β internally it+`limit` clamp above). The `whatsapp-web.js` engine _can_ load older messages on demand β internally itdrives WhatsApp Web's "load earlier messages" mechanism β so reaching further back is bounded by**OpenWA's cap**, not by what WhatsApp Web is willing to expose.diff --git a/docs/examples/n8n-appointment-booking.md b/docs/examples/n8n-appointment-booking.mdindex f1be6fd6a..75a06a164 100644--- a/docs/examples/n8n-appointment-booking.md+++ b/docs/examples/n8n-appointment-booking.md@@ -34,9 +34,9 @@ The workflow is intentionally generic. The availability source can be Google CalUse the **OpenWA Trigger** node.-| Field | Value |-| ----- | ----- |-| Event | `message.received` |+| Field | Value |+| ------- | ----------------------------- |+| Event | `message.received` || Session | Your connected OpenWA session |The incoming message body is available at:@@ -63,13 +63,13 @@ Add a **Set** node to extract the values your booking system expects.Suggested fields:-| Field | Example value |-| ----- | ------------- |-| `chatId` | `{{$json.data.chatId}}` |-| `phone` | `{{$json.data.from}}` |-| `message` | `{{$json.data.body}}` |+| Field | Example value |+| --------------- | -------------------------------------------------- |+| `chatId` | `{{$json.data.chatId}}` |+| `phone` | `{{$json.data.from}}` |+| `message` | `{{$json.data.body}}` || `requestedDate` | Parsed date from the message or a default fallback |-| `service` | Parsed service name or workflow default |+| `service` | Parsed service name or workflow default |If the message does not contain enough information, send a clarification question instead of creating a booking.@@ -83,13 +83,13 @@ Thanks. What day and time would you prefer for the appointment?Use whichever node matches your scheduling source:-| Source | n8n node |-| ------ | -------- |-| Google Calendar | Google Calendar or HTTP Request |-| Cal.com | HTTP Request |-| Internal API | HTTP Request |-| Database | PostgreSQL / MySQL / SQLite node |-| Spreadsheet | Google Sheets |+| Source | n8n node |+| --------------- | -------------------------------- |+| Google Calendar | Google Calendar or HTTP Request |+| Cal.com | HTTP Request |+| Internal API | HTTP Request |+| Database | PostgreSQL / MySQL / SQLite node |+| Spreadsheet | Google Sheets |The availability step should return whether the requested slot is available and, if not, a small list of alternatives.@@ -97,12 +97,12 @@ The availability step should return whether the requested slot is available and,When the requested slot is available, create the booking in your scheduling source and send a confirmation with the **OpenWA: Send Text** node.-| Field | Value |-| ----- | ----- |-| Resource | Message |-| Operation | Send Text |-| Chat ID | `{{$json.chatId}}` |-| Text | Confirmation message |+| Field | Value |+| --------- | -------------------- |+| Resource | Message |+| Operation | Send Text |+| Chat ID | `{{$json.chatId}}` |+| Text | Confirmation message |Example confirmation text:diff --git a/docs/examples/session-phone-number-pairing.md b/docs/examples/session-phone-number-pairing.mdindex 1c79b0bbd..fff936492 100644--- a/docs/examples/session-phone-number-pairing.md+++ b/docs/examples/session-phone-number-pairing.md@@ -61,11 +61,11 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/pairing-code \Example values:-| Country | Example |-| ------- | ------- |-| Indonesia | `628123456789` |-| Spain | `34612345678` |-| United States | `14155552671` |+| Country | Example |+| ------------- | -------------- |+| Indonesia | `628123456789` |+| Spain | `34612345678` |+| United States | `14155552671` |## Responsediff --git a/docs/examples/webhook-signature-verification.md b/docs/examples/webhook-signature-verification.mdindex 91e39e39e..2212e0b30 100644--- a/docs/examples/webhook-signature-verification.md+++ b/docs/examples/webhook-signature-verification.md@@ -6,13 +6,13 @@ OpenWA signs webhook deliveries when a webhook is configured with a secret. ReceOpenWA sends these system headers with webhook deliveries:-| Header | Description |-| ------ | ----------- |-| `X-OpenWA-Signature` | HMAC-SHA256 signature, present only when the webhook has a secret |-| `X-OpenWA-Event` | Event name, for example `message.received` |-| `X-OpenWA-Idempotency-Key` | Stable key for duplicate detection |-| `X-OpenWA-Delivery-Id` | Unique identifier for this delivery (stable across retry attempts) |-| `X-OpenWA-Retry-Count` | Retry count for the current delivery |+| Header | Description |+| -------------------------- | ------------------------------------------------------------------ |+| `X-OpenWA-Signature` | HMAC-SHA256 signature, present only when the webhook has a secret |+| `X-OpenWA-Event` | Event name, for example `message.received` |+| `X-OpenWA-Idempotency-Key` | Stable key for duplicate detection |+| `X-OpenWA-Delivery-Id` | Unique identifier for this delivery (stable across retry attempts) |+| `X-OpenWA-Retry-Count` | Retry count for the current delivery |The signature format is:@@ -36,8 +36,7 @@ const WEBHOOK_SECRET = process.env.OPENWA_WEBHOOK_SECRET;function verifyOpenWASignature(rawBody, signature, secret) {if (!signature || !secret) return false;- const expected =- 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');+ const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');const signatureBuffer = Buffer.from(signature);const expectedBuffer = Buffer.from(expected);diff --git a/sdk/go/README.md b/sdk/go/README.mdindex 6055c9f22..5a9e27b84 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -64,17 +64,17 @@ func main() {## Configuration-| Option | Purpose |-| ------ | ------- |-| `WithTimeout(d)` | Per-request timeout (default 30s). |-| `WithHTTPClient(hc)` | Inject a preconfigured `*http.Client` (pool, jar, timeout). |-| `WithTransport(rt)` | Inject the base `http.RoundTripper` (proxy, TLS, test double). |-| `WithLogger(l)` | Inject a `Logger` (default: no-op). |-| `WithRetry(p)` | Enable automatic retries (off by default). |-| `WithMiddleware(mw...)` | Add transport middleware (tracing, metrics, auth). |-| `WithUserAgent(ua)` | Override the `User-Agent`. |-| `WithHeader(k, v)` | Add a default header on every request. |-| `WithInsecureHTTP()` | Suppress the plaintext-`http://` warning. |+| Option | Purpose |+| ----------------------- | -------------------------------------------------------------- |+| `WithTimeout(d)` | Per-request timeout (default 30s). |+| `WithHTTPClient(hc)` | Inject a preconfigured `*http.Client` (pool, jar, timeout). |+| `WithTransport(rt)` | Inject the base `http.RoundTripper` (proxy, TLS, test double). |+| `WithLogger(l)` | Inject a `Logger` (default: no-op). |+| `WithRetry(p)` | Enable automatic retries (off by default). |+| `WithMiddleware(mw...)` | Add transport middleware (tracing, metrics, auth). |+| `WithUserAgent(ua)` | Override the `User-Agent`. |+| `WithHeader(k, v)` | Add a default header on every request. |+| `WithInsecureHTTP()` | Suppress the plaintext-`http://` warning. |## Typed errors@@ -187,7 +187,7 @@ subdirectory rather than at the repository root:git tag sdk/go/v0.2.0 && git push origin sdk/go/v0.2.0```-A bare `v0.2.0` tag is the *app* version and does nothing for this module.+A bare `v0.2.0` tag is the _app_ version and does nothing for this module.Without a prefixed tag, `go get` resolves a pseudo-version(`v0.0.0-<date>-<commit>`) β usable, but callers cannot pin a release.diff --git a/sdk/java/README.md b/sdk/java/README.mdindex 158162ee5..179fbcc33 100644--- a/sdk/java/README.md+++ b/sdk/java/README.md@@ -91,16 +91,16 @@ try {}```-| Class | HTTP | Meaning |-| ---------------------------- | ---- | ---------------------------------------- |-| `OpenWAAuthError` | 401 | Missing or invalid API key |-| `OpenWAForbiddenError` | 403 | API key role insufficient |-| `OpenWANotFoundError` | 404 | Resource not found |-| `OpenWAConflictError` | 409 | Engine not ready |-| `OpenWARateLimitError` | 429 | Rate limited |-| `OpenWANotImplementedError` | 501 | Active engine does not support the call |-| `OpenWAApiError` | β | Any other non-2xx (carries `.status()`) |-| `OpenWATimeoutError` | β | Request exceeded the configured timeout |+| Class | HTTP | Meaning |+| --------------------------- | ---- | --------------------------------------- |+| `OpenWAAuthError` | 401 | Missing or invalid API key |+| `OpenWAForbiddenError` | 403 | API key role insufficient |+| `OpenWANotFoundError` | 404 | Resource not found |+| `OpenWAConflictError` | 409 | Engine not ready |+| `OpenWARateLimitError` | 429 | Rate limited |+| `OpenWANotImplementedError` | 501 | Active engine does not support the call |+| `OpenWAApiError` | β | Any other non-2xx (carries `.status()`) |+| `OpenWATimeoutError` | β | Request exceeded the configured timeout |All extend `OpenWAError` (a `RuntimeException`).