Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

docs: align the documentation set with the shipped implementation (#977)

Yudhi Armyndharisa408066d8c39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6cbdd4809..41d7231f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **The documentation set now matches the shipped implementation.** Every numbered document was
+ checked claim by claim against source, and the corrections concentrate where following the docs
+ could fail silently. Session auth was documented at `./data/.wwebjs_auth` when it lives under
+ `SESSION_DATA_PATH` (default `./data/sessions`), so every backup, server-transfer and rollback
+ procedure copied a directory that does not exist and still reported success; compose commands
+ addressed a service named `openwa` where the shipped file defines `openwa-api`; the upgrade runbook
+ used `docker compose pull` against a compose file that builds from source; health checks omitted
+ the global `api` prefix; and several referenced files and scripts were never part of the repository.
+ Documented settings that the configuration layer does not read (`WA_RECONNECT_INTERVAL`,
+ `STORAGE_S3_*`, `CACHE_TYPE`, `API_PREFIX` and others) are replaced by the real names. Endpoints
+ and tooling that do not exist — per-session export/import, a 1.x upgrade path, an MCP tool name —
+ are removed, the catalog endpoints are marked as answering 501 on both engines, and the glossary no
+ longer defines a message queue, message scheduling or a Redis-backed dead-letter queue, none of
+ which the gateway has. Two risk-register rows that claimed send-rate safeguards now describe the
+ controls that ship. Structurally, `docs/23-plugin-sandboxing.md` becomes `docs/30`, resolving a
+ duplicate prefix; the engine capability matrix joins the sequence as `docs/29`; a language-forked
+ second copy of the Docker guide is removed; and the index lists all thirty documents.
+
- **A source install without the GNU `patch` binary no longer silently ships an unpatched
whatsapp-web.js.** OpenWA backports the fix for the WhatsApp Web 2.3000.x message-id rename during
`npm install`; when the `patch` binary was missing — the default on Windows outside Git Bash — the
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index 166d8d052..3e8de32fd 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -236,7 +236,9 @@ connections**:
- **`main`** — always SQLite (`./data/main.sqlite`); owns the auth (`api_keys`) and audit
(`audit_logs`) entities. Fixed boot config, not pluggable.
- **`data`** — the pluggable user-data connection: `sqlite` (default) or `postgres`, selected by
- `DATABASE_TYPE`. Owns the session/webhook/message/template/engine entities.
+ `DATABASE_TYPE`. Owns the session/webhook/message/template/engine entities, plus the
+ integration-fabric (`plugin_instances`, `ingress_events`, `conversation_mappings`,
+ `integration_delivery_failures`) and status-store (`status_updates`) entities.
The engine is provided by `EngineModule` as the `EngineFactory` **class** (a normal injectable, not a
string token). Storage and cache are provided as the `StorageService` and `CacheService` classes by
@@ -295,7 +297,7 @@ sequenceDiagram
Note over Env: STORAGE_TYPE=s3
Env->>Config: Load + validateEnv
Config->>Svc: storage.type = 's3'
- Svc->>Svc: construct S3Client (forcePathStyle: true)
+ Svc->>Svc: construct S3Client (forcePathStyle only when S3_ENDPOINT is set)
App->>Svc: putFile / getFile (unaware of backend)
```
@@ -378,90 +380,70 @@ flowchart TB
### NestJS Module Organization
+Trimmed to the load-bearing directories — `src/modules/` holds 27 feature modules. Only `*.module.ts`
+is common to all of them; the rest of the shape varies. Most pair a `*.controller.ts` with a
+`*.service.ts`, but `events/` is a WebSocket gateway, `mcp/` an MCP server and `queue/` pure BullMQ
+wiring (none of the three has either); `docker/` and `status-store/` are service-only; `health/`,
+`infra/` and `settings/` are controller-only; and 8 modules own an `entities/` directory:
+
```
src/
├── main.ts # Application entry point
-├── app.module.ts # Root module
+├── app.module.ts # Root module (imports feature modules, both TypeORM connections)
+│
+├── common/ # Shared, non-feature code
+│ ├── cache/ # CacheService (ioredis)
+│ ├── storage/ # StorageService (local | s3)
+│ ├── errors/ interceptors/ media/ metrics/ middleware/
+│ ├── security/ services/ # services/ holds logger.service.ts
+│ └── throttler/ transformers/ utils/
│
-├── common/ # Shared utilities
-│ ├── decorators/
-│ ├── filters/
-│ ├── guards/
-│ ├── interceptors/
-│ ├── pipes/
-│ └── utils/
+├── config/ # configuration.ts, env.validation.ts, feature-flags.ts,
+│ # app-validation.ts, swagger.config.ts, … (no config.module.ts)
│
-├── config/ # Configuration
-│ ├── config.module.ts
-│ ├── config.service.ts
-│ └── configuration.ts
+├── core/ # Host-side extension machinery
+│ ├── plugins/ # Plugin loader + sandbox
+│ ├── hooks/
+│ └── agent-tools/
│
-├── modules/
-│ ├── session/ # Session management
-│ │ ├── session.module.ts
-│ │ ├── session.controller.ts
-│ │ ├── session.service.ts
-│ │ ├── session.repository.ts
-│ │ ├── dto/
-│ │ └── entities/
-│ │
-│ ├── message/ # Message handling
-│ │ ├── message.module.ts
-│ │ ├── message.controller.ts
-│ │ ├── message.service.ts
-│ │ └── dto/
-│ │
-│ ├── webhook/ # Webhook management
-│ │ ├── webhook.module.ts
-│ │ ├── webhook.controller.ts
-│ │ ├── webhook.service.ts
-│ │ └── dto/
-│ │
-│ ├── contact/ # Contact management
-│ │ ├── contact.module.ts
-│ │ ├── contact.controller.ts
-│ │ └── contact.service.ts
-│ │
-│ ├── group/ # Group management
-│ │ ├── group.module.ts
-│ │ ├── group.controller.ts
-│ │ └── group.service.ts
-│ │
-│ ├── auth/ # Authentication
-│ │ ├── auth.module.ts
-│ │ ├── auth.guard.ts
-│ │ └── api-key.strategy.ts
-│ │
-│ └── health/ # Health checks
-│ ├── health.module.ts
-│ └── health.controller.ts
+├── plugins/
+│ └── engines/ # Built-in whatsapp-web.js + baileys engine plugins
│
-├── engine/ # WhatsApp engine wrapper
+├── engine/ # WhatsApp engine abstraction
│ ├── engine.module.ts
-│ ├── engine.service.ts
│ ├── engine.factory.ts
-│ └── interfaces/
+│ ├── adapters/ # whatsapp-web-js.adapter.ts, baileys.adapter.ts, mappers, stores
+│ ├── identity/ # Neutral WhatsApp id helpers + lid-mapping store
+│ ├── interfaces/ # whatsapp-engine.interface.ts
+│ └── types/
│
-├── queue/ # Job queue
-│ ├── queue.module.ts
-│ ├── processors/
-│ └── jobs/
+├── modules/ # Feature modules
+│ ├── session/ # Session management (no separate repository class)
+│ ├── message/ webhook/ contact/ group/ template/ label/ profile/ catalog/
+│ ├── channel/ status/ status-store/ search/ stats/ call/
+│ ├── auth/ # API-key auth: auth.service.ts, guards/, decorators/, entities/
+│ ├── queue/ # BullMQ wiring + processors/
+│ ├── integration/ # Integration fabric (plugin instances, ingress, mappings)
+│ └── plugins/ mcp/ events/ infra/ docker/ settings/ metrics/ audit/ health/
│
-└── database/ # Database
- ├── database.module.ts
- ├── migrations/
- └── seeds/
+└── database/ # data-source.ts / data-source-main.ts
+ ├── migrations/ # 'data' connection
+ └── migrations-main/ # 'main' connection (auth + audit)
```
## 3.5 Core Components Design
### 3.5.1 Session Manager
+The diagram below is conceptual: `SessionManager` is the role played by `SessionService`
+(`src/modules/session/session.service.ts`), which injects the TypeORM `Repository<Session>` directly —
+there is no `SessionRepository` class in the codebase.
+
```mermaid
classDiagram
class SessionManager {
- -sessions: Map~string, Session~
- -repository: SessionRepository
+ -engines: Map~string, IWhatsAppEngine~
+ -sessionRepository: Repository~Session~
-engineFactory: EngineFactory
+createSession(config): Session
+getSession(id): Session
@@ -487,7 +469,7 @@ classDiagram
CREATED
INITIALIZING
QR_READY
- AUTHENTICATED
+ AUTHENTICATING
READY
DISCONNECTED
FAILED
@@ -658,28 +640,25 @@ flowchart TB
```mermaid
flowchart TB
subgraph Production["Production Environment"]
- LB[Load Balancer] --> I1[Instance 1]
- LB --> I2[Instance 2]
- LB --> I3[Instance N]
-
- I1 --> DB[(PostgreSQL)]
- I2 --> DB
- I3 --> DB
-
- I1 --> REDIS[(Redis)]
- I2 --> REDIS
- I3 --> REDIS
+ API[OpenWA API<br/>single instance]
+ VOL[(Session-data volume<br/>auth dirs)]
+
+ API --- VOL
+ API --> DB[(PostgreSQL)]
+ API --> REDIS[(Redis)]
end
-
- subgraph Storage["Shared Storage"]
+
+ subgraph Storage["External Storage"]
S3[S3/MinIO<br/>Media backup / migration]
end
-
- I1 --> S3
- I2 --> S3
- I3 --> S3
+
+ API --> S3
```
+> Multi-replica deployment behind a load balancer is a future design, not the shipped topology — the
+> live engines are held in-process, so one API instance owns a session-data volume. See the
+> single-instance note in §3.2 and [13 - Horizontal Scaling](13-horizontal-scaling.md).
+
## 3.8 API Architecture
### RESTful API Design
@@ -693,7 +672,7 @@ flowchart LR
W["/api/sessions/:sessionId/webhooks"]
C["/api/sessions/:sessionId/contacts"]
G["/api/sessions/:sessionId/groups"]
- H["/health"]
+ H["/api/health"]
end
subgraph Methods["HTTP Methods"]
@@ -763,31 +742,46 @@ flowchart TB
## 3.10 Error Handling Architecture
+Handlers throw NestJS's own HTTP exceptions; NestJS's built-in `BaseExceptionFilter` renders them.
+There is no custom filter and no custom exception base class — see
+[08 - Development Guidelines](./08-development-guidelines.md) for the domain errors in
+`src/common/errors/` and the status each maps to.
+
```mermaid
flowchart TB
E[Error Occurs] --> T{Error Type}
-
- T -->|Validation| V[ValidationException]
- T -->|Not Found| N[NotFoundException]
- T -->|Auth| A[UnauthorizedException]
- T -->|Business| B[BusinessException]
- T -->|System| S[InternalException]
-
- V --> F[Exception Filter]
+
+ T -->|Validation fails| V[BadRequestException 400]
+ T -->|Missing resource| N[NotFoundException 404]
+ T -->|Bad/absent key| A[UnauthorizedException 401]
+ T -->|Role or scope refused| FB[ForbiddenException 403]
+ T -->|Engine cannot do this| NI[EngineNotSupportedError → 501]
+ T -->|Engine not ready| C[EngineNotReadyError → 409]
+ T -->|Engine transport down| SU[EngineTransportError → 503]
+ T -->|Unhandled| S[InternalServerErrorException 500]
+
+ V --> F[NestJS BaseExceptionFilter]
N --> F
A --> F
- B --> F
+ FB --> F
+ NI --> F
+ C --> F
+ SU --> F
S --> F
-
- F --> R[Formatted Response]
- F --> L[Log Error]
-
- L -->|Critical| AL[Alert]
+
+ F --> R["{ statusCode, message, error }"]
+ S --> L[Log with stack]
```
## 3.11 Scalability Considerations
-### Horizontal Scaling Strategy
+> **Future design, not the shipped topology.** Live engines are held in an in-process `Map` in
+> `SessionService`, so a session can only be driven by the instance that started it — there is no
+> session registry, node claim, or affinity router in the codebase. OpenWA runs as one API instance
+> per session-data volume; the two sketches below are retained for planning. See the single-instance
+> note in §3.2 and [13 - Horizontal Scaling](13-horizontal-scaling.md).
+
+### Horizontal Scaling Strategy (sketch)
```mermaid
flowchart TB
@@ -814,7 +808,7 @@ flowchart TB
Stateful --> Shared
```
-### Session Affinity
+### Session Affinity (sketch)
```mermaid
flowchart LR
@@ -904,6 +898,9 @@ export interface EngineEventCallbacks {
onMessageAck?: (messageId: string, status: DeliveryStatus) => void;
onMessageRevoked?: (message: RevokedMessage) => void;
onMessageReaction?: (event: ReactionEvent) => void;
+ onMessageEdited?: (message: EditedMessage) => void;
+ onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update
+ onCall?: (event: IncomingCallEvent) => void; // incoming call ringing; rejectCall() while it rings
onHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatch
onDisconnected?: (reason: string) => void; // recoverable -> reconnect
onStateChanged?: (state: EngineStatus) => void;
@@ -920,13 +917,14 @@ export interface IWhatsAppEngine {
// Status / auth
getStatus(): EngineStatus;
+ probeLiveness?(): Promise<boolean>; // optional active round-trip against the live connection
getQRCode(): string | null; // synchronous
requestPairingCode(phoneNumber: string): Promise<string>;
getPhoneNumber(): string | null;
getPushName(): string | null;
// Messaging (selected)
- sendTextMessage(chatId: string, text: string): Promise<MessageResult>;
+ sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult>;
sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult>;
sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult>;
sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult>;
@@ -945,10 +943,15 @@ The factory resolves the engine through the **plugin loader**, not a hard-coded
configured engine (`engine.type`, default `'whatsapp-web.js'`) is read once in the constructor; the
built-in `whatsapp-web.js` and `baileys` plugins are registered and the configured one is enabled in
`onModuleInit()`. `create()` takes an **options object** (engine-neutral per-call config —
-`sessionId` / `proxyUrl` / `proxyType`), not a `type` argument. There is no `EngineType` union, no
-`switch`, and no `Unknown engine type` throw: if the plugin is unavailable it logs a warning and
-**falls back** to constructing a `WhatsAppWebJsAdapter` directly. (A typo in `ENGINE_TYPE` is rejected
-at boot by `validateEnv`, which whitelists `whatsapp-web.js` | `baileys`.)
+`sessionId` / `dbSessionId` / `proxyUrl` / `proxyType`), not a `type` argument. The two ids are
+distinct: `sessionId` is the session **name** (the on-disk auth-directory key), `dbSessionId` is the
+session **UUID** (`Session.id`), needed by FK-bound stores such as `baileys_stored_messages`. There is
+no `EngineType` union, no `switch`, and no `Unknown engine type` throw: if the plugin is unavailable it
+logs a warning and falls back to the legacy direct adapter — but that fallback can only build
+`whatsapp-web.js`. For any other configured engine (e.g. `ENGINE_TYPE=baileys` with its plugin
+missing) `createFallbackEngine` **throws** rather than silently running the wrong engine, so the
+session fails loudly at start. (A typo in `ENGINE_TYPE` is rejected at boot by `validateEnv`, which
+whitelists `whatsapp-web.js` | `baileys`.)
```typescript
// engine/engine.factory.ts
@@ -959,7 +962,10 @@ import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';
import { PluginLoaderService, PluginType, IEnginePlugin } from '../core/plugins';
export interface EngineCreateOptions {
+ /** Session NAME — the on-disk auth-directory key. */
sessionId: string;
+ /** Session UUID (Session.id) — the DB-row key for FK-bound stores (e.g. baileys_stored_messages). */
+ dbSessionId: string;
proxyUrl?: string;
proxyType?: 'http' | 'https' | 'socks4' | 'socks5';
}
@@ -989,14 +995,26 @@ export class EngineFactory implements OnModuleInit {
// registration, so the factory passes only engine-neutral per-call options here.
return enginePlugin.instance.createEngine({
sessionId: options.sessionId,
+ dbSessionId: options.dbSessionId,
proxyUrl: options.proxyUrl,
proxyType: options.proxyType,
}) as IWhatsAppEngine;
}
- // Plugin missing -> warn and fall back to the direct whatsapp-web.js adapter (no throw).
+ // Plugin missing -> warn, then fall back to the direct whatsapp-web.js adapter.
return this.createFallbackEngine(options);
}
+
+ private createFallbackEngine(options: EngineCreateOptions): IWhatsAppEngine {
+ // The legacy fallback can only construct whatsapp-web.js. Building it for a different configured
+ // engine would silently run the WRONG one — fail loudly instead.
+ if (this.engineType !== 'whatsapp-web.js') {
+ throw new Error(
+ `Engine '${this.engineType}' is unavailable and has no direct fallback; cannot start the session.`,
+ );
+ }
+ return new WhatsAppWebJsAdapter(/* ...sessionDataPath, puppeteer, proxy, lidMappingStore... */);
+ }
}
```
@@ -1243,7 +1261,7 @@ flowchart TB
|-----------|---------|---------|-------|
| **WhatsApp Engine** | whatsapp-web.js, Baileys (`ENGINE_TYPE`) | whatsapp-web.js | Baileys is browser-free |
| **Database** | SQLite, PostgreSQL (`DATABASE_TYPE`) | SQLite | PostgreSQL for large-scale production |
-| **Media Storage** | local, s3 (`STORAGE_TYPE`) | local | MinIO is the `s3` backend (`forcePathStyle`) |
+| **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
@@ -1251,13 +1269,17 @@ flowchart TB
Media storage is a **single service** (`src/common/storage/storage.service.ts`) that branches
internally on `storageType` — there is no `I*Adapter` interface, separate adapter classes, or a
`StorageFactory`. The two backends are `local` (the default; files under `./data/media`) and `s3`.
-The shipped producer/consumer is the storage export/import migration and backup flow. Incoming and
-outgoing message media is returned inline to REST/webhook consumers and is **not** automatically
-written through `StorageService`.
-**MinIO is not a separate type** — it is the `s3` backend; the S3 client is always created with
-`forcePathStyle: true`, which MinIO requires, and any S3-compatible endpoint works. The public method
-set is `putFile` / `getFile` / `listFiles` / `createExportStream` (export) / `importFromStream`
-(import), plus `getFileCount` and `getCurrentStorageType`.
+The main producer/consumer is the storage export/import migration and backup flow; the status store
+also writes status media through `putFile` (under `statuses/`) and sweeps orphans back out with
+`deleteFile`. Incoming and outgoing message media is returned inline to REST/webhook consumers and is
+**not** automatically written through `StorageService`.
+**MinIO is not a separate type** — it is the `s3` backend. The S3 client is created from credentials
+alone, so plain AWS S3 works with no endpoint (the SDK derives one from the region); `S3_ENDPOINT` is
+for S3-compatible stores (MinIO, R2, …), and setting it is also what enables `forcePathStyle: true`.
+The public method set is `putFile` / `getFile` / `deleteFile` / `listFiles` / `iterateFiles` /
+`createExportStream` (export) / `importFromStream` (import), plus `getFileCount`,
+`getCurrentStorageType` and `refreshS3Availability` (re-probes the bucket; the infra status endpoint
+calls it to report S3 reachability).
```typescript
// src/common/storage/storage.service.ts
@@ -1272,15 +1294,16 @@ export class StorageService {
this.localPath = this.configService.get<string>('storage.localPath') || './data/media';
if (this.storageType === 's3') {
- const endpoint = process.env.S3_ENDPOINT; // S3 / MinIO endpoint
+ 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 secretAccessKey = process.env.S3_SECRET_ACCESS_KEY;
- if (endpoint && accessKeyId && secretAccessKey) {
+ // Credentials alone are enough — AWS S3 derives its endpoint from the region.
+ if (accessKeyId && secretAccessKey) {
this.s3Client = new S3Client({
- endpoint,
+ ...(endpoint ? { endpoint } : {}),
region: process.env.S3_REGION || 'us-east-1',
credentials: { accessKeyId, secretAccessKey },
- forcePathStyle: true, // Required for MinIO; harmless for AWS S3
+ ...(endpoint ? { forcePathStyle: true } : {}), // path-style is a MinIO/R2 concern
});
// bucket auto-created if missing (HeadBucket -> CreateBucket)
}
@@ -1329,7 +1352,7 @@ Database wiring lives inline in `AppModule` (`src/app.module.ts`) as two named
// shape of the 'data' connection useFactory in src/app.module.ts
const dbType = configService.get<'sqlite' | 'postgres'>('dataDatabase.type', 'sqlite');
const baseConfig = {
- entities: [/* session, webhook, message, template, engine entities */],
+ entities: [/* session, webhook, message, template, engine, integration, status-store globs */],
migrations: [__dirname + '/database/migrations/*{.ts,.js}'],
logging: configService.get<boolean>('dataDatabase.logging', false),
};
@@ -1351,7 +1374,7 @@ if (dbType === 'postgres') {
// SQLite (default): migration-managed unless DATABASE_SYNCHRONIZE=true
const synchronize = configService.get<boolean>('dataDatabase.synchronize', false);
return {
- ...baseConfig, name: 'data', type: 'sqlite',
+ ...baseConfig, name: 'data', type: 'better-sqlite3' as const, // DATABASE_TYPE=sqlite -> this driver
database: configService.get('dataDatabase.database', './data/openwa.sqlite'),
synchronize,
migrationsRun: !synchronize,
@@ -1369,44 +1392,28 @@ return {
#### Migration Strategy
-```typescript
-// database/migrations/utils/database-aware-migration.ts
-
-/**
- * Helper for writing migrations compatible with SQLite and PostgreSQL
- */
-export abstract class DatabaseAwareMigration {
- protected isPostgres(queryRunner: QueryRunner): boolean {
- return queryRunner.connection.options.type === 'postgres';
- }
-
- protected isSqlite(queryRunner: QueryRunner): boolean {
- return queryRunner.connection.options.type === 'sqlite';
- }
-
- /**
- * Generate UUID default based on database type
- */
- protected getUuidDefault(queryRunner: QueryRunner): string {
- if (this.isPostgres(queryRunner)) {
- return 'gen_random_uuid()';
- }
- // SQLite: UUID must be generated at the application level
- return '';
- }
+There is **no** shared cross-dialect migration base class. Each migration is a plain
+`MigrationInterface` that branches inline on the connection's dialect, and the branch always tests for
+`'postgres'` (never for a SQLite name — the SQLite driver reports `better-sqlite3`, not `sqlite`).
+A Postgres-only migration simply returns early everywhere else:
- /**
- * Get timestamp type based on database
- */
- protected getTimestampType(queryRunner: QueryRunner): string {
- if (this.isPostgres(queryRunner)) {
- return 'TIMESTAMP WITH TIME ZONE';
- }
- return 'DATETIME';
+```typescript
+// src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts (shape)
+export class AddUuidDefaultsForPostgres1779235200000 implements MigrationInterface {
+ name = 'AddUuidDefaultsForPostgres1779235200000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // No-op on SQLite: TypeORM generates the UUID in the driver layer there, so no DB default
+ // is needed. Only Postgres expects the column to supply it.
+ if (queryRunner.dataSource.options.type !== 'postgres') return;
+ // ... ALTER TABLE ... ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar
}
}
```
+Migrations that must run on both dialects with different SQL take the same check as a branch, e.g.
+`const isPostgres = queryRunner.connection.options.type === 'postgres';`.
+
### 3.13.3 Cache Service
There is **no** cache-manager / `CacheModuleOptions` / `redisStore` setup and **no** in-memory cache.
@@ -1427,13 +1434,14 @@ export class CacheService implements OnModuleDestroy {
constructor(private readonly configService: ConfigService) {
// REDIS_ENABLED is the primary switch; cache.enabled is the legacy fallback.
this.enabled = process.env.REDIS_ENABLED === 'true' || configService.get<boolean>('cache.enabled', false);
- // Lazy connect: the first isAvailable() call dials Redis (bounded retries).
+ // Lazy connect: the first isAvailable() call dials Redis, then ioredis owns reconnection —
+ // it retries forever with capped backoff (times => Math.min(times * 500, 5000)).
}
async isAvailable(): Promise<boolean> {
- if (!this.enabled) return false; // disabled -> always "no cache"
- if (!this.redis) await this.tryConnect(); // bounded attempts
- return this.ping();
+ 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.
@@ -1475,7 +1483,7 @@ flowchart LR
E1[PostgreSQL Cluster]
E2[S3/MinIO]
E3[Redis Cluster]
- E4[Horizontal Scaling]
+ E4[Vertical Headroom]
end
```
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 5780d37bc..b2ebe9452 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -59,25 +59,38 @@ sequenceDiagram
### API Key Format
```
-Format: owa_<32-character-random-string>
-Example: owa_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
+Format: owa_k1_<64 hex chars> (32 random bytes, hex-encoded — 71 characters in total)
+Example: owa_k1_3f9c1d0a7b2e4c5680a1f2d3e4b5c6a7980b1c2d3e4f50617283940a1b2c3d4e
-Storage: SHA-256 hash only (never store plain key)
+Storage: SHA-256 hash only (never store plain key); `keyPrefix` keeps the first 12 characters
```
+Every key minted through the API-keys endpoints uses that format. The bootstrap seed key is the only
+exception: an explicit `API_MASTER_KEY` is taken verbatim, and `ALLOW_DEV_API_KEY=true` opts into the
+fixed `dev-admin-key`; with neither set, the seed key is generated in the format above.
+
### Permission Model
-| Permission | Description |
-| ----------------- | ---------------------- |
-| `*` | Full access (admin) |
-| `sessions:read` | View sessions |
-| `sessions:write` | Create/delete sessions |
-| `messages:send` | Send messages |
-| `messages:read` | Read message history |
-| `webhooks:manage` | CRUD webhooks |
-| `contacts:read` | View contacts |
-| `groups:read` | View groups |
-| `groups:write` | Manage groups |
+API keys carry **no permission strings**. Authorization is a role hierarchy on the key itself, plus
+two scoping dimensions enforced by `ApiKeyGuard`.
+
+| Role | Rank | Meaning |
+|------|------|---------|
+| `admin` | 3 | Satisfies every `@RequireRole` level, including API-key management |
+| `operator` | 2 | Satisfies `operator` and `viewer` routes — the default for a new key |
+| `viewer` | 1 | Satisfies `viewer` routes only |
+
+A route declares its minimum level with `@RequireRole(...)`; a key passes when its role ranks at or
+above that level (`AuthService.hasPermission`). A key below it is rejected with `403 Forbidden`.
+
+| Scope | Field | Effect |
+|-------|-------|--------|
+| Source IP | `allowedIps` | Empty/absent = unrestricted; non-empty = fail-closed IP whitelist (see §4.3) |
+| Sessions | `allowedSessions` | Empty/absent = every session; non-empty = a request carrying any other session id is rejected with `401` |
+
+The key-lifecycle routes (`/api/auth/api-keys`) are additionally fenced with `@RequireUnscopedKey()`:
+a session-scoped key is refused there whatever its role, so it cannot mint or widen credentials
+beyond its own confinement.
## 4.3 IP Whitelisting
@@ -92,26 +105,11 @@ flowchart TB
AUTH -->|Yes| WL{IP Whitelist Enabled?}
WL -->|No| ALLOW[Allow Request]
WL -->|Yes| CHECK{IP in Whitelist?}
- CHECK -->|No| R403[403 Forbidden]
+ CHECK -->|No| RIP[401 Unauthorized]
CHECK -->|Yes| ALLOW
ALLOW --> PROCESS[Process Request]
```
-### Configuration
-
-```typescript
-// API to manage IP whitelist
-interface IpWhitelistEntry {
- id: string;
- apiKeyId: string;
- ipAddress: string; // Single IP: "203.0.113.50"
- cidrRange?: string; // CIDR: "10.0.0.0/24"
- description?: string;
- active: boolean;
- createdAt: Date;
-}
-```
-
### Managing the whitelist
There is **no `/whitelist` sub-resource**. A key's allowed source IPs are the `allowedIps` field on the API key itself, set when you create or update the key via the API-keys endpoints (see §6.4.9 in the [API Specification](./06-api-specification.md)):
@@ -132,76 +130,20 @@ PUT /api/auth/api-keys/:id
### Implementation
-```typescript
-// IP Whitelist Guard
-@Injectable()
-export class IpWhitelistGuard implements CanActivate {
- constructor(private readonly ipWhitelistService: IpWhitelistService) {}
-
- async canActivate(context: ExecutionContext): Promise<boolean> {
- const request = context.switchToHttp().getRequest();
- const apiKeyId = request.apiKey?.id;
-
- if (!apiKeyId) {
- return true; // Let other guards handle missing API key
- }
-
- const clientIp = this.getClientIp(request);
- const whitelist = await this.ipWhitelistService.getByApiKey(apiKeyId);
-
- // If no whitelist entries, allow all IPs
- if (whitelist.length === 0) {
- return true;
- }
-
- // Check if IP matches any whitelist entry
- const isAllowed = whitelist.some(entry => this.ipMatches(clientIp, entry));
-
- if (!isAllowed) {
- throw new ForbiddenException({
- code: 'IP_NOT_WHITELISTED',
- message: `IP address ${clientIp} is not in the whitelist`,
- });
- }
-
- return true;
- }
-
- private getClientIp(request: Request): string {
- // Handle proxies (X-Forwarded-For, X-Real-IP)
- const forwarded = request.headers['x-forwarded-for'];
- if (forwarded) {
- return (forwarded as string).split(',')[0].trim();
- }
- return (request.headers['x-real-ip'] as string) || request.socket.remoteAddress || '';
- }
-
- private ipMatches(clientIp: string, entry: IpWhitelistEntry): boolean {
- if (!entry.active) return false;
-
- if (entry.cidrRange) {
- return this.ipInCidr(clientIp, entry.cidrRange);
- }
-
- return clientIp === entry.ipAddress;
- }
-
- private ipInCidr(ip: string, cidr: string): boolean {
- // IPv4-only example. For IPv6 support, use a library like ipaddr.js.
- const [range, bits] = cidr.split('/');
- const mask = ~(2 ** (32 - parseInt(bits)) - 1);
-
- const ipNum = this.ipToNumber(ip);
- const rangeNum = this.ipToNumber(range);
-
- return (ipNum & mask) === (rangeNum & mask);
- }
-
- private ipToNumber(ip: string): number {
- return ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet), 0) >>> 0;
- }
-}
-```
+There is no dedicated whitelist guard, service or table — no `IpWhitelistGuard`, no whitelist
+sub-resource, no per-entry `active` flag. Enforcement lives in two places:
+
+- **Client IP resolution** — `ApiKeyGuard` calls `resolveClientIp(request, TRUSTED_PROXIES)`
+ (`src/common/utils/ip.ts`). `X-Forwarded-For` is client-controllable, so it is honored **only**
+ when the request actually arrives from a configured trusted proxy; with no trusted proxies set the
+ header is ignored entirely and the direct socket address is used. That is what prevents a caller
+ from spoofing its way past the whitelist with a forged header (see §4.6 for `TRUSTED_PROXIES`).
+- **Matching** — `AuthService.validateApiKey` compares that IP against the key's `allowedIps` with
+ the shared `ipMatches` helper, which accepts an exact address or CIDR notation and returns `false`
+ on a malformed entry rather than coercing it into range. With a whitelist configured, an
+ undeterminable client IP throws `UnauthorizedException` (`401`) straight away, with no log line;
+ an IP outside the list writes a `logger.warn` with `action: 'ip_rejected'` first, then throws the
+ same `401`.
### Best Practices
@@ -215,7 +157,9 @@ export class IpWhitelistGuard implements CanActivate {
### IPv6 Support
-For IPv6, use a library that supports IPv6 parsing (e.g., `ipaddr.js`) when performing `ipInCidr`.
+CIDR matching is IPv4-only: an IPv6 range in `allowedIps` never matches. An exact IPv6 address still
+works, by literal comparison — IPv4-mapped forms (`::ffff:203.0.113.50`) are normalized to their bare
+IPv4 address first.
## 4.4 Data Encryption
@@ -256,39 +200,43 @@ flowchart TB
### Validation Examples
-| Field | Rules |
-| ------------- | ---------------------------------- |
-| `chatId` | Pattern: `^\d+@(c\.us\|g\.us)$` |
-| `phone` | Pattern: `^\d{10,15}$` |
-| `url` | Valid URL, HTTPS only for webhooks |
-| `text` | Max 4096 chars (`send-text`) |
-| `sessionName` | Alphanumeric + hyphen, 3-50 chars |
+| Field | Rules |
+|-------|-------|
+| `chatId` | Non-empty string — **no format pattern**; the engine resolves the id, so `@c.us`, `@g.us`, `@lid`, `@newsletter` and `status@broadcast` all pass |
+| `phoneNumber` (pairing code) | Pattern: `^[0-9]{6,15}$` — digits only, international format |
+| `url` | Valid URL (`require_tld: false`, so single-label hosts like `http://localhost:3000` pass); HTTPS is a recommendation, not enforced |
+| `text` | Max 4096 chars (`send-text`) |
+| `sessionName` | Alphanumeric + hyphen, 3-50 chars |
### DTO Validation
```typescript
-// Example DTO with validation
-import { IsString, IsUrl, Matches, MaxLength } from 'class-validator';
-
-export class SendTextDto {
+// src/modules/message/dto/send-message.dto.ts
+export class SendTextMessageDto {
@IsString()
- @Matches(/^\d+@(c\.us|g\.us)$/, {
- message: 'Invalid chatId format',
- })
+ @IsNotEmpty()
chatId: string;
@IsString()
- @MaxLength(4096)
+ @IsNotEmpty()
+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH) // 4096, shared with the agent-tool input schemas
text: string;
}
+// src/modules/webhook/dto/webhook.dto.ts
export class CreateWebhookDto {
- @IsUrl({ protocols: ['https'], require_protocol: true })
+ // require_tld:false allows hostnames without a dot (e.g. http://localhost:3000); the SSRF
+ // guard still decides whether the host may actually be delivered to.
+ @IsUrl({ require_tld: false })
url: string;
+ @IsOptional()
@IsArray()
- @IsIn(['message.received', 'message.sent', 'session.status'], { each: true })
- events: string[];
+ @ArrayMinSize(1)
+ // The full WEBHOOK_EVENTS catalog (message.*, status.received, session.*, group.*,
+ // call.received) plus '*' for subscribe-all.
+ @IsIn([...WEBHOOK_EVENTS, '*'], { each: true })
+ events?: string[];
}
```
@@ -349,28 +297,34 @@ The frame budget is sized ~6x above legitimate traffic: the dashboard emits ~8 s
### CORS Settings
```typescript
-// Secure CORS configuration
-const corsOptions = {
- origin: (origin, callback) => {
- const allowedOrigins = process.env.CORS_ORIGINS?.split(',') || [];
+// resolveCorsPolicy (src/config/bootstrap-security.ts): CORS_ORIGINS is a comma-separated
+// allowlist; unset defaults to the wildcard. In production a wildcard is REFUSED — the policy
+// collapses to same-origin only, with credentials off, so a misconfigured deployment cannot
+// reflect arbitrary origins with credentials.
+const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);
- // Allow requests with no origin (mobile apps, Postman)
+app.enableCors({
+ origin: (origin, callback) => {
+ // Allow requests with no origin (mobile apps, Postman, server-to-server)
if (!origin) return callback(null, true);
- if (allowedOrigins.includes(origin) || allowedOrigins.includes('*')) {
+ if (corsPolicy.allowAnyOrigin || corsPolicy.origins.includes(origin)) {
callback(null, true);
} else {
- callback(new Error('Not allowed by CORS'));
+ // Deny WITHOUT throwing — throwing surfaced as a 500 Internal Server Error (#250).
+ // Returning false simply omits the CORS headers, so the browser blocks the genuine
+ // cross-origin request itself while same-origin traffic keeps working.
+ callback(null, false);
}
},
- credentials: true,
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
- allowedHeaders: ['Content-Type', 'X-API-Key', 'X-Request-ID'],
+ credentials: corsPolicy.credentials, // false whenever the allowlist is a wildcard
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
+ allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'],
// Throttlers are named, so rate-limit headers carry a per-window suffix
// (see "Response on limit" above); there are no unsuffixed variants.
exposedHeaders: ['X-RateLimit-Limit-short', 'X-RateLimit-Remaining-short', '...'],
maxAge: 86400, // 24 hours
-};
+});
```
## 4.8 Webhook Security
@@ -426,47 +380,56 @@ media shedding, so it is small. The HMAC signature is computed over the exact sh
## 4.9 Security Headers
-### Recommended Headers
+### Helmet Configuration
+
+The shipped configuration lives in `src/main.ts` — that file is the source of truth:
```typescript
-// Helmet configuration
-app.use(
- helmet({
- contentSecurityPolicy: {
- directives: {
- defaultSrc: ["'self'"],
- styleSrc: ["'self'", "'unsafe-inline'"],
- scriptSrc: ["'self'"],
- imgSrc: ["'self'", 'data:', 'https:'],
- },
+app.use(helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ // The bundled dashboard pulls webfonts from Google Fonts.
+ styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
+ // Per-response nonce; the served dashboard document carries the same value.
+ scriptSrc: ["'self'", (_req, res) => `'nonce-${res.locals.cspNonce}'`],
+ // blob: for the outgoing attachment preview, data: for chat media rendered inline.
+ imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
+ mediaSrc: ["'self'", 'data:', 'blob:', 'https:'],
+ connectSrc: ["'self'"],
+ fontSrc: ["'self'", 'https://fonts.gstatic.com'],
+ objectSrc: ["'none'"],
+ // On in production, unless CSP_UPGRADE_INSECURE_REQUESTS opts an HTTP-only
+ // private-network deployment out (#611).
+ upgradeInsecureRequests: isUpgradeInsecureRequestsEnabled(...) ? [] : null,
},
- hsts: {
- maxAge: 31536000,
- includeSubDomains: true,
- },
- noSniff: true,
- referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
- }),
-);
+ },
+ hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
+ noSniff: true,
+ referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
+ crossOriginResourcePolicy: { policy: 'cross-origin' }, // API usage
+}));
```
### Security Headers Checklist
-| Header | Value | Purpose |
-| --------------------------- | ------------------ | --------------------- |
-| `Strict-Transport-Security` | `max-age=31536000` | Force HTTPS |
-| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
-| `X-Frame-Options` | `DENY` | Prevent clickjacking |
-| `X-XSS-Protection` | `1; mode=block` | XSS filter |
-| `Referrer-Policy` | `strict-origin` | Control referrer |
+| Header | Value | Purpose |
+|--------|-------|---------|
+| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | Force HTTPS |
+| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
+| `X-Frame-Options` | `SAMEORIGIN` | Prevent clickjacking (helmet's default; not overridden) |
+| `X-XSS-Protection` | `0` | Helmet 8 deliberately disables the legacy auditor — the CSP is the protection |
+| `Referrer-Policy` | `strict-origin-when-cross-origin` | Control referrer |
## 4.10 Audit Logging
### What Gets Logged
> **Reality check:** persisted audit coverage currently includes API-key create/update/revoke/delete
-> (updates carry before/after authorization state), rejected authentication, session lifecycle, and
-> integration-instance creation, secret rotation, deletion, and scope-binding bridge failures. Enum
+> (updates carry before/after authorization state), rejected authentication, session lifecycle,
+> integration-instance creation, secret rotation, deletion, and scope-binding bridge failures, the
+> infra operations (config save, restart request, data export/import, storage export/import),
+> WebSocket rate-limit violations (sampled — see §4.6), and Bull Board queue mutations. Enum
> members for API-key use, connection transitions, message sends, and webhook lifecycle are explicitly
> registered as intentionally unemitted; application logs cover those operational events until dedicated
> audit callsites are added. There is no global audit interceptor.
@@ -495,7 +458,7 @@ flowchart TB
"severity": "info",
"apiKeyId": "uuid",
"sessionId": "sess_123",
- "ip": "192.168.1.1",
+ "ipAddress": "192.168.1.1",
"method": "POST",
"path": "/api/sessions/sess_123/start",
"statusCode": 201,
@@ -505,11 +468,11 @@ flowchart TB
}
```
-`action` is an `AuditAction` enum value (snake_case); `severity` is `info` / `warn` / `error`. There is no `requestId` or `responseTime` field, and no global request-logging interceptor — entries are written explicitly by the code paths that emit them.
+`action` is an `AuditAction` enum value (snake_case); `severity` is `info` / `warn` / `error`. There is no `requestId` or `responseTime` **column**, but the active request id is merged into the `metadata` object of every row written inside a request scope, so an entry still correlates with the application log lines for that request. There is no global request-logging interceptor — entries are written explicitly by the code paths that emit them.
### Security Alerts
-> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The only related runtime behavior today is a `logger.warn` when an IP-restricted key is used from a disallowed IP. Forward the audit log / application log to your SIEM to build these alerts.
+> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The signals do get recorded — rejected authentication and WebSocket rate-limit violations write persisted audit rows (the latter sampled), and an IP-restricted key used from a disallowed IP also emits a `logger.warn` — but nothing acts on them. Forward the audit log / application log to your SIEM to build these alerts.
| Event | Severity | Intended action (roadmap) |
| -------------------- | -------- | ------------------------- |
@@ -566,11 +529,11 @@ flowchart TB
### Environment Variables Security
```bash
-# ❌ BAD: Secrets in code or docker-compose.yml
-DATABASE_URL=postgresql://user:password123@localhost:5432/db
+# ❌ BAD: Secrets hard-coded in a committed file (docker-compose.yml, Dockerfile, source)
+DATABASE_PASSWORD=password123
# ✅ GOOD: Use .env file (not committed)
-DATABASE_URL=${DATABASE_URL}
+DATABASE_PASSWORD=${DATABASE_PASSWORD}
# ✅ BETTER: Use Docker secrets or vault
docker secret create db_password ./secret.txt
@@ -581,32 +544,26 @@ docker secret create db_password ./secret.txt
> **Caveat:** the `*_FILE` convention shown below requires a secret-file reader in the app (see "Reading Secrets" below), which is **not currently implemented** — OpenWA reads secrets straight from environment variables. Until that helper exists, pass secrets as plain env vars (e.g. an `.env` file with restricted permissions) rather than `_FILE` paths.
```yaml
-# docker-compose.prod.yml
-version: '3.8'
-
+# Illustrative overlay — not the docker-compose.yml shipped in this repo
services:
app:
image: openwa:latest
secrets:
- db_password
- - encryption_key
- api_master_key
environment:
- DATABASE_PASSWORD_FILE=/run/secrets/db_password
- - ENCRYPTION_KEY_FILE=/run/secrets/encryption_key
secrets:
db_password:
external: true
- encryption_key:
- external: true
api_master_key:
external: true
```
### Reading Secrets in Application
-> **Not implemented as shown.** OpenWA does **not** read `<NAME>_FILE` Docker-secret files — there is no `getSecret()` helper today. Secrets come straight from `process.env`, layered at boot as `process.env` → `.env` → `data/.env.generated` (`override:false`, so a real environment value wins). The function below is a suggested pattern to add if you want Docker-secret `_FILE` support; as-is, `DATABASE_PASSWORD_FILE` / `ENCRYPTION_KEY_FILE` are not consulted.
+> **Not implemented as shown.** OpenWA does **not** read `<NAME>_FILE` Docker-secret files — there is no `getSecret()` helper today. Secrets come straight from `process.env`, layered at boot as `process.env` → `.env` → `data/.env.generated` (`override:false`, so a real environment value wins). The function below is a suggested pattern to add if you want Docker-secret `_FILE` support; as-is, `DATABASE_PASSWORD_FILE` is not consulted.
```typescript
// config/secrets.ts
@@ -629,8 +586,8 @@ export function getSecret(name: string): string {
}
// Usage
-const encryptionKey = getSecret('ENCRYPTION_KEY');
const dbPassword = getSecret('DATABASE_PASSWORD');
+const masterKey = getSecret('API_MASTER_KEY');
```
### Key Rotation Procedure
@@ -687,29 +644,40 @@ npm audit --json > audit-report.json
### GitHub Dependabot Configuration
```yaml
-# .github/dependabot.yml
+# .github/dependabot.yml — the root npm ecosystem (the file also covers /dashboard,
+# github-actions and docker)
version: 2
updates:
- - package-ecosystem: 'npm'
- directory: '/'
+ - package-ecosystem: npm
+ directory: /
schedule:
- interval: 'weekly'
- day: 'monday'
- open-pull-requests-limit: 10
+ interval: weekly
+ day: monday
+ open-pull-requests-limit: 5
groups:
- development-dependencies:
- dependency-type: 'development'
- production-dependencies:
- dependency-type: 'production'
+ minor-and-patch:
+ update-types: [minor, patch]
+ major:
+ update-types: [major]
+ labels:
+ - dependencies
ignore:
- # Major version updates require manual review
- - dependency-name: '*'
- update-types: ['version-update:semver-major']
+ # TypeScript 7 is the native port: typescript-eslint and ts-jest cannot load it (#727/#729).
+ - dependency-name: "typescript"
+ versions: [">=7.0.0"]
+ # better-sqlite3 v13: every released TypeORM caps its peer at ^12, and the linux-arm64
+ # prebuild needs glibc 2.38 (the node:22-slim base has 2.36).
+ - dependency-name: "better-sqlite3"
+ versions: [">=13.0.0"]
```
+Majors are **not** ignored — they arrive as their own grouped PR, separate from the minor/patch
+group. The only ignores are the two pinned incompatibilities above, each with its lift condition
+documented inline.
+
### Security Scanning in CI
-> **Aspirational template — not in the repo.** There is no `security.yml`, no Snyk, and no CodeQL workflow today. The actual dependency check is an inline step in `ci.yml` (`npm audit --audit-level=critical`, run on push/PR — not on a schedule). The workflow below is a recommended setup to add if you want scheduled scanning and SAST.
+> **Aspirational template — not in the repo.** There is no `security.yml`, no Snyk, and no CodeQL workflow today. The actual dependency check is a dedicated `audit` job ("Security audit") in `ci.yml`, running `npm audit --audit-level=high` on push/PR — not on a schedule. It is deliberately its own job rather than a step inside Lint: an advisory published against an unrelated dependency would otherwise abort the job before ESLint, the type-check and the drift gates ever ran. The threshold is `high` rather than `critical` because the `overrides` in `package.json` clear the root tree's existing HIGH advisories, so it now fences regressions. The workflow below is a recommended setup to add if you want scheduled scanning and SAST.
```yaml
# .github/workflows/security.yml
@@ -854,7 +822,7 @@ contacts:
security_lead:
name: 'Security Lead'
+ email: '[email protected]' # see SECURITY.md — GitHub Security Advisories preferred
escalation:
- level: 1
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index ade8146bb..74e30a70e 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -29,7 +29,7 @@ OpenWA supports two database backends that can be selected at deployment time:
> - No horizontal scaling support
> - Ideal for: personal bots, small businesses with 1-3 WhatsApp numbers
>
-> For configuration, see [03 - System Architecture: Pluggable Adapters](./03-system-architecture.md#312-pluggable-adapters)
+> For configuration, see [03 - System Architecture: Pluggable Adapters](./03-system-architecture.md#313-pluggable-adapters)
### Dual-Database Architecture
@@ -40,21 +40,32 @@ OpenWA v0.2+ implements a **dual-database architecture** that separates boot con
│ OpenWA Application │
├─────────────────────────────┬───────────────────────────────────┤
│ Main DB (SQLite) │ Data DB (Pluggable) │
-│ Always ./data/main.db │ SQLite or PostgreSQL (config) │
+│ Default ./data/main.sqlite │ SQLite or PostgreSQL (config) │
├─────────────────────────────┼───────────────────────────────────┤
│ • api_keys │ • sessions │
│ • audit_logs │ • webhooks │
│ │ • messages │
│ │ • message_batches │
│ │ • templates │
-│ │ • (engine: baileys_stored_messages, lid_mappings) │
+│ │ • status_updates │
+│ │ • webhook_delivery_failures │
+│ │ • plugin_instances │
+│ │ • ingress_events │
+│ │ • conversation_mappings │
+│ │ • integration_delivery_failures │
+│ │ • baileys_stored_messages (engine)│
+│ │ • lid_mappings (engine) │
└─────────────────────────────┴───────────────────────────────────┘
```
-| Component | Database | Location | Purpose |
-| ----------- | -------------------- | -------------------- | ------------------------------------------ |
-| **Main DB** | SQLite (always) | `./data/main.sqlite` | Boot-critical config, API keys, audit logs |
-| **Data DB** | SQLite or PostgreSQL | Configurable | User data, sessions, messages, webhooks |
+| Component | Database | Location | Purpose |
+| ----------- | -------------------- | ------------------------------ | ------------------------------------------ |
+| **Main DB** | SQLite (always) | `./data/main.sqlite` (default) | Boot-critical config, API keys, audit logs |
+| **Data DB** | SQLite or PostgreSQL | Configurable | User data, sessions, messages, webhooks |
+
+The main DB is unconditionally SQLite, but its *path* is not fixed: `MAIN_DATABASE_NAME` overrides the
+`./data/main.sqlite` default, and is honoured by both the runtime connection factory
+(`src/config/configuration.ts`) and the CLI DataSource (`src/database/data-source-main.ts`).
> [!IMPORTANT]
> **Why Dual-Database?**
@@ -65,21 +76,14 @@ OpenWA v0.2+ implements a **dual-database architecture** that separates boot con
> - Audit logs must persist even if Data DB fails
> - Enables switching Data DB type without losing authentication
-#### Pre-Bootstrap PostgreSQL Orchestration
+#### Built-in PostgreSQL Orchestration
-When using PostgreSQL Built-in mode, OpenWA automatically:
+When using PostgreSQL Built-in mode (`POSTGRES_BUILTIN=true`), `DockerService.onModuleInit()` runs a bootstrap orchestration that starts the managed `postgres` container (alongside `redis` / `minio` when their own `REDIS_BUILTIN` / `MINIO_BUILTIN` flags are set). This happens **during** Nest module initialization, not before it — there is no pre-bootstrap step in `main.ts`.
-1. Starts PostgreSQL container **before** NestJS bootstrap
-2. Waits for health check (max 60 seconds)
-3. Proceeds with application initialization
+Because the container can therefore still be coming up when the `data` connection first dials it, that connection is configured with `retryAttempts: 10` and `retryDelay: 3000` (`src/app.module.ts`), giving the database roughly 30 seconds to become reachable.
-```typescript
-// main.ts - Pre-bootstrap flow
-if (process.env.POSTGRES_BUILTIN === 'true') {
- await preBootstrapPostgres(); // Start & wait for healthy
-}
-const app = await NestFactory.create(AppModule); // Then bootstrap
-```
+> [!NOTE]
+> If the Docker API is unreachable, orchestration logs a warning and is skipped — no container is started, and the `data` connection then fails its retries against whatever `DATABASE_HOST` points at.
#### PostgreSQL Schema Selection
@@ -203,6 +207,8 @@ erDiagram
uuid session_id FK
varchar wa_message_id
varchar chat_id
+ varchar chat_name
+ varchar author
varchar from
varchar to
text body
@@ -306,23 +312,25 @@ stateDiagram-v2
**Config Schema:**
+`config` is an opaque JSON blob; the keys the session service actually reads are:
+
```json
{
- "autoReconnect": true,
"maxReconnectAttempts": 5,
- "puppeteer": {
- "headless": true,
- "args": ["--no-sandbox"]
- },
- "proxy": {
- "host": "proxy.example.com",
- "port": 8080,
- "username": "user",
- "password": "pass"
- }
+ "reconnectBaseDelay": 5000,
+ "autoRejectCalls": false
}
```
+| Key | Default | Effect |
+| ---------------------- | ---------- | -------------------------------------------------------------------------- |
+| `maxReconnectAttempts` | unlimited | Reconnect attempt cap, clamped to 0–20 (`0` disables reconnect entirely) |
+| `reconnectBaseDelay` | `5000` ms | Base delay of the reconnect backoff, clamped to 1000–300000 ms |
+| `autoRejectCalls` | `false` | Auto-reject an incoming call as soon as it rings |
+
+> [!NOTE]
+> Proxy settings are **not** read from `config` — they live in the dedicated `proxy_url` / `proxy_type` columns shown in the DDL above. Puppeteer options are global engine configuration from the environment (`engine.puppeteer.*`), not per-session. Anything else placed in `config` is stored but ignored.
+
---
### 5.3.2 webhooks
@@ -357,6 +365,7 @@ CREATE TABLE webhooks (
"message.revoked",
"message.reaction",
"message.edited",
+ "status.received",
"session.status",
"session.qr",
"session.authenticated",
@@ -381,6 +390,8 @@ CREATE TABLE messages (
session_id UUID NOT NULL,
wa_message_id VARCHAR, -- nullable; transient outgoing rows have none yet
chat_id VARCHAR NOT NULL,
+ chat_name VARCHAR, -- nullable; contact pushName / group name when known
+ author VARCHAR, -- nullable; participant JID for a group message ("from" is the group)
"from" VARCHAR NOT NULL,
"to" VARCHAR NOT NULL,
body TEXT,
@@ -393,10 +404,12 @@ CREATE TABLE messages (
);
-- Indexes (declared on the entity)
-CREATE INDEX idx_messages_session_id ON messages(session_id);
+-- There is deliberately NO standalone session_id index: the composites below lead with
+-- session_id, so they already serve session-only lookups (see DropRedundantMessagesSessionIdIndex).
CREATE INDEX idx_messages_session_created ON messages(session_id, created_at);
CREATE INDEX idx_messages_chat_id ON messages(chat_id);
CREATE INDEX idx_messages_status ON messages(status);
+CREATE INDEX "IDX_messages_createdAt" ON messages(created_at); -- created_at-only stats aggregates
-- Inbound dedup (issue #464): one row per (session_id, wa_message_id).
-- NULL wa_message_id rows are exempt (SQL treats NULLs as distinct).
@@ -482,11 +495,17 @@ CREATE INDEX "IDX_audit_logs_createdAt" ON audit_logs(created_at);
`api_key_updated`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`), session
lifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`,
`session_deleted`, `session_qr_generated`, `session_connected`, `session_disconnected`), messages
-(`message_sent`, `message_failed`), and webhooks (`webhook_created`, `webhook_deleted`,
-`webhook_triggered`, `webhook_failed`).
+(`message_sent`, `message_failed`), webhooks (`webhook_created`, `webhook_deleted`,
+`webhook_triggered`, `webhook_failed`), rate-limit enforcement (`rate_limit_exceeded`, sampled to at
+most one row per subject+kind per minute), the queue dashboard (`queue_board_mutated`), integration
+plugin instances (`integration_instance_created`, `integration_instance_updated`,
+`integration_instance_secret_regenerated`, `integration_instance_deleted`,
+`integration_instance_redriven`), and ADMIN-only infrastructure operations (`infra_config_saved`,
+`infra_restart_requested`, `infra_data_exported`, `infra_data_imported`, `infra_storage_exported`,
+`infra_storage_imported`).
> [!NOTE]
-> Audit-log retention is automatic: see [§5.7 Data Retention](#57-data-retention). Other event types (session logs, webhook delivery logs, API access logs) are surfaced via structured application logging, not dedicated database tables.
+> Audit-log retention is automatic: see [§5.7 Data Retention](#57-data-retention). Other event types (session logs, API access logs) are surfaced via structured application logging, not dedicated database tables. The one exception is a webhook delivery that exhausts every retry — that lands in the `webhook_delivery_failures` table (§5.3.8), not just the log stream.
### 5.3.7 message_batches
@@ -495,7 +514,7 @@ Tracks bulk/batch message jobs. A single table holds the job state plus its mess
```sql
CREATE TABLE message_batches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
- batch_id VARCHAR NOT NULL UNIQUE,
+ batch_id VARCHAR NOT NULL,
session_id VARCHAR NOT NULL,
status VARCHAR NOT NULL DEFAULT 'pending', -- pending | processing | completed | cancelled | failed
messages JSONB NOT NULL, -- [{ chatId, type, content, variables? }]
@@ -506,10 +525,14 @@ CREATE TABLE message_batches (
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
started_at TIMESTAMP WITH TIME ZONE,
- completed_at TIMESTAMP WITH TIME ZONE
+ completed_at TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "UQ_message_batches_session_id_batch_id" UNIQUE (session_id, batch_id)
);
```
+> [!NOTE]
+> Batch-id uniqueness is **scoped to the session**, not global — one session cannot deny a batch id to another, so the same `batch_id` may exist under different sessions.
+
**Batch Status Values:**
| Status | Description |
@@ -527,9 +550,17 @@ CREATE TABLE message_batches (
The data connection also owns:
- **`templates`** — reusable message templates (`src/modules/template/entities/template.entity.ts`), with a unique constraint on `(sessionId, name)` — one template name per session.
+- **`status_updates`** — inbound status/story broadcasts with a 24-hour TTL (`src/modules/status-store/entities/status-update.entity.ts`); unique on `(sessionId, waStatusId)`. Attached media is stored via `StorageService`, not in the row.
+- **`webhook_delivery_failures`** — durable record of a webhook delivery that exhausted all retries (`src/modules/webhook/entities/webhook-delivery-failure.entity.ts`), surfaced via the ADMIN `GET /webhooks/delivery-failures`.
+- **`plugin_instances`** — one configured instance of an adapter plugin, keyed `${pluginId}:${instanceId}` (`src/modules/integration/entities/plugin-instance.entity.ts`); holds the host-minted ingress HMAC secret, masked on API reads.
+- **`ingress_events`** — persist-before-ack durable row and inbound dedup oracle, unique on `(pluginId, instanceId, providerDeliveryId)` (`src/modules/integration/entities/ingress-event.entity.ts`). The full payload is retired to `NULL` once dispatch is settled, leaving a slim dedup marker.
+- **`conversation_mappings`** — bidirectional WA-chat ↔ provider-conversation mapping plus handover state (`src/modules/integration/entities/conversation-mapping.entity.ts`).
+- **`integration_delivery_failures`** — DLQ-of-record for both inbound (ingress) and outbound (provider egress) delivery failures (`src/modules/integration/entities/integration-delivery-failure.entity.ts`).
- **`baileys_stored_messages`** — Baileys engine message store — the serialized WAMessage proto (`src/engine/adapters/baileys-stored-message.entity.ts`); present only when the Baileys engine is used. (Credentials live on the filesystem, not here.)
- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).
+Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint.
+
> [!NOTE]
> **Tables that do *not* exist.** Earlier drafts referenced `contacts`, `session_logs`, `webhook_logs`, `api_key_logs`, `webhook_idempotency`, and `ip_whitelist`. None of these are implemented. Contacts are read live from the engine; auditing is the single `audit_logs` table; webhook idempotency is not a persisted table; and per-key IP restrictions are stored inline on `api_keys.allowed_ips` (a `simple-array`), not in a separate `ip_whitelist` table.
@@ -548,6 +579,8 @@ These indexes are the ones declared on the entities (see §5.3); the rows below
| List messages by session (paged) | `(session_id, created_at)` composite | Very High |
| Look up message by chat | `chat_id` | High |
| Ack/dedup a message | `UQ_messages_sessionId_waMessageId` (UNIQUE) | Very High |
+| Message stats over a date range | `IDX_messages_createdAt` | Medium |
+| Find a session's webhooks | `IDX_webhooks_sessionId` | Very High |
| Authenticate API key | `IDX_api_keys_keyHash` (UNIQUE, main DB) | Very High |
| Filter audit logs | `IDX_audit_logs_action` / `_apiKeyId` / `_sessionId` | Medium |
@@ -557,6 +590,13 @@ These indexes are the ones declared on the entities (see §5.3); the rows below
-- messages: paged listing per session + ack-driven status update / inbound dedup
CREATE INDEX idx_messages_session_created ON messages(session_id, created_at);
CREATE UNIQUE INDEX "UQ_messages_sessionId_waMessageId" ON messages(session_id, wa_message_id);
+CREATE INDEX "IDX_messages_createdAt" ON messages(created_at);
+
+-- webhooks: the dispatch path filters by session on every emitted event
+CREATE INDEX "IDX_webhooks_sessionId" ON webhooks(session_id);
+
+-- message_batches: batch ids are unique per session, not globally
+CREATE UNIQUE INDEX "UQ_message_batches_session_id_batch_id" ON message_batches(session_id, batch_id);
-- audit_logs (main DB): filter by action / key / session, ordered by time
CREATE INDEX "IDX_audit_logs_action" ON audit_logs(action);
@@ -638,8 +678,8 @@ flowchart LR
end
subgraph FS["Engine Auth (not in sessions table)"]
- FSAUTH[whatsapp-web.js: filesystem]
- DBAUTH[Baileys: engine tables]
+ FSAUTH[whatsapp-web.js: filesystem LocalAuth]
+ BAUTH[Baileys: filesystem useMultiFileAuthState]
end
Memory -->|Sync| Persistent
@@ -652,10 +692,13 @@ OpenWA runs **two separate TypeORM connections**, each with its own migrations d
| Connection | DataSource | Migrations dir | Owns |
| ---------- | ----------------------- | --------------------------- | ---------------------------------------------------------------------- |
-| **main** | `data-source-main.ts` | `src/database/migrations-main/` | `api_keys`, `audit_logs` — always SQLite (`./data/main.sqlite`) |
-| **data** | `data-source.ts` | `src/database/migrations/` | `sessions`, `webhooks`, `messages`, `message_batches`, `templates`, engine tables — SQLite **or** PostgreSQL |
+| **main** | `data-source-main.ts` | `src/database/migrations-main/` | `api_keys`, `audit_logs` — always SQLite (`./data/main.sqlite` by default) |
+| **data** | `data-source.ts` | `src/database/migrations/` | `sessions`, `webhooks`, `messages`, `message_batches`, `templates`, `status_updates`, `webhook_delivery_failures`, the integration tables (`plugin_instances`, `ingress_events`, `conversation_mappings`, `integration_delivery_failures`), engine tables — SQLite **or** PostgreSQL |
-Migrations are hand-authored (TypeORM `synchronize` is off for both connections in production) and are idempotent (`IF NOT EXISTS`) so they are safe to adopt on a database originally created by `synchronize`.
+Migrations are hand-authored and idempotent (`IF NOT EXISTS`) so they are safe to adopt on a database originally created by `synchronize`. The two connections differ in how schema is managed:
+
+- **data** — `synchronize` defaults **off**, so this connection is migration-managed by default. On PostgreSQL `migrationsRun` is hardcoded on, and `DATABASE_SYNCHRONIZE=true` is rejected outright at boot validation (it would drop the migration-created `body_ts` tsvector column that `/search` depends on). On SQLite there is no such rejection and `migrationsRun` is the inverse of `synchronize` — so an opted-in `DATABASE_SYNCHRONIZE=true` switches the data connection to entity-synchronized schema and turns its migrations **off**.
+- **main** — `synchronize` defaults **on** (zero-config first boot) regardless of `NODE_ENV`; set `MAIN_DATABASE_SYNCHRONIZE=false` to manage `api_keys` / `audit_logs` via `migrations-main/` instead. Never both at once — `migrationsRun` on this connection is the inverse of `synchronize`.
### Migration Files
@@ -665,6 +708,7 @@ src/database/migrations-main/ # main connection (auth + audit, SQLite)
src/database/migrations/ # data connection (pluggable)
├── 1770108659848-AddMessageStatus.ts
+├── 1770200000000-NormalizeSynchronizeUuidColumns.ts
├── 1779235200000-AddUuidDefaultsForPostgres.ts # Postgres-only: gen_random_uuid() id DEFAULTs
├── 1779840000000-AddTemplates.ts
├── 1779900100000-AddMessageSessionWaIndex.ts
@@ -672,7 +716,21 @@ src/database/migrations/ # data connection (pluggable)
├── 1781100000000-AddTemplateNameUnique.ts
├── 1781200000000-AddLidMappings.ts
├── 1781300000000-AddMessagesWaMessageIdUnique.ts # UNIQUE(sessionId, waMessageId) inbound dedup (#464)
-└── 1781500000000-AddWebhookFilters.ts
+├── 1781500000000-AddWebhookFilters.ts
+├── 1781600000000-DropRedundantMessagesSessionIdIndex.ts
+├── 1781700000000-AddWebhookDeliveryFailures.ts
+├── 1781800000000-ScopeBatchIdUniqueToSession.ts
+├── 1781900000000-AddIntegrationFabric.ts
+├── 1782000000000-AddMessageChatName.ts
+├── 1782100000000-WidenIngressDedupKey.ts
+├── 1782200000000-AddWebhooksSessionIdIndex.ts
+├── 1782300000000-AddIntegrationUuidDefaults.ts
+├── 1782400000000-AddMessagesFts.ts # FTS5 (SQLite) / body_ts tsvector + GIN (Postgres)
+├── 1784822470680-CreateStatusUpdates.ts
+├── 1784908800000-AddMessageAuthor.ts
+├── 1785112230000-AddIngressEventDispatchState.ts
+├── 1785123853000-AddMessagesCreatedAtIndex.ts
+└── 1785600000000-SlimIngressEventPayload.ts
```
> [!NOTE]
@@ -707,13 +765,17 @@ export class AddMessagesWaMessageIdUnique1781300000000 implements MigrationInter
### Retention Policies
-Only **`audit_logs`** has an automated retention job. Everything else is kept indefinitely (sessions, webhooks, message history, batches) and is removed only by user action (e.g. deleting a session) or operational backup/restore — there is no message or log auto-purge.
+Five tables have an automated *time-based* retention job, across four services: **`audit_logs`**, **`status_updates`**, **`webhook_delivery_failures`**, **`ingress_events`** and **`integration_delivery_failures`**. Separately, **`baileys_stored_messages`** is capped per session rather than by age — each write keeps the newest `BAILEYS_MESSAGE_STORE_LIMIT` rows (default 5000) for that session and deletes the rest. Everything else is kept indefinitely (sessions, webhooks, batches, templates, conversation mappings, plugin instances) and is removed only by user action (e.g. deleting a session) or operational backup/restore — the `messages` history table in particular has no auto-purge and grows without bound.
-| Data Type | Default Retention | Configurable |
-| ------------------- | ----------------- | ------------------------------------- |
-| Sessions / Webhooks | Indefinite | No |
-| Messages / Batches | Indefinite | No (delete a session to drop its data) |
-| Audit logs | 90 days | Yes — `AUDIT_RETENTION_DAYS` (≤ 0 disables) |
+| Data Type | Default Retention | Configurable |
+| ----------------------------- | ----------------- | ------------------------------------- |
+| Sessions / Webhooks | Indefinite | No |
+| Messages / Batches | Indefinite | No (delete a session to drop its data) |
+| Status updates | 24 hours | No (fixed, matches WhatsApp's own story expiry) |
+| Audit logs | 90 days | Yes — `AUDIT_RETENTION_DAYS` (≤ 0 disables) |
+| Webhook delivery failures | 90 days | Yes — `WEBHOOK_FAILURE_RETENTION_DAYS` (≤ 0 disables) |
+| Ingress events (dedup rows) | 7 days | Yes — `INGRESS_DEDUP_RETENTION_DAYS` (≤ 0 does **not** disable) |
+| Integration delivery failures | 90 days | Yes — `INGRESS_RETENTION_DAYS` (≤ 0 disables this prune only) |
### Audit-Log Cleanup Job
@@ -740,6 +802,22 @@ async cleanup(olderThanDays = 30): Promise<number> {
}
```
+### Sibling Prune Jobs
+
+The other three interval-based prunes are the same shape — one prune at startup, then a 24-hour `setInterval`, `unref`'d, never a `@Cron`:
+
+- **`webhook_delivery_failures`** — `WebhookService.onModuleInit()` (`src/modules/webhook/webhook.service.ts`), window `WEBHOOK_FAILURE_RETENTION_DAYS` (default 90; ≤ 0 disables the prune and logs that it is off).
+- **`ingress_events`** and **`integration_delivery_failures`** — `IntegrationRetentionService` (`src/modules/integration/integration-retention.service.ts`) prunes both in one timer on two independent windows. `INGRESS_DEDUP_RETENTION_DAYS` (default 7) bounds the dedup rows; a non-positive value does **not** disable it — an unpruned dedup table grows without bound for no functional gain, so the service warns and falls back to the 7-day default. `INGRESS_RETENTION_DAYS` (default 90) bounds the DLQ rows, where long retention can be a deliberate operator choice, so ≤ 0 disables that prune (and only that prune).
+
+### Status-Update TTL Sweep
+
+`StatusStoreService` (`src/modules/status-store/status-store.service.ts`) stamps every ingested status row with `expiresAt = postedAt + 24h` and runs two recurring sweeps, both started in `onModuleInit` and both `unref`'d so they never hold the process open:
+
+- **TTL purge** — once at startup, then every 15 minutes; deletes rows past their `expiresAt`.
+- **Orphaned-media sweep** — hourly by default (`STATUS_ORPHAN_SWEEP_INTERVAL_MS`); deletes status media files no row references, after a grace window (`STATUS_ORPHAN_GRACE_MS`, default 1 hour) so a file mid-ingest is never reaped.
+
+The 24-hour TTL itself is a fixed constant (`STATUS_TTL_MS`) and is not configurable.
+
## 5.8 Backup Strategy
> [!NOTE]
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index ec8ae9722..64c5d49a2 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1504,7 +1504,7 @@ List all contacts for a session, returned as an in-memory paginated window.
]
```
-**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session
#### GET /api/sessions/:sessionId/contacts/check/:number
@@ -1531,9 +1531,9 @@ Check whether a phone number exists on WhatsApp and return its canonical WhatsAp
`whatsappId` is the canonical native chat id, or `null` when the number is not on WhatsApp; `exists` is `whatsappId !== null`.
-> Route-order caveat: the literal `check/` segment disambiguates this route from `GET /:contactId`. A contact whose id is literally `check` would be shadowed by this handler.
+> Route-order caveat: this route is two path segments (`check/:number`), so it never collides with the single-segment `GET /:contactId` — a contact id of literally `check` resolves to `GET /:contactId`.
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key
#### GET /api/sessions/:sessionId/contacts/:contactId
@@ -1562,7 +1562,7 @@ Get a single contact by its WhatsApp id.
}
```
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Contact <id> not found` (engine returned null), or session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Contact <id> not found` (engine returned null)
#### GET /api/sessions/:sessionId/contacts/:contactId/profile-picture
@@ -1587,7 +1587,42 @@ Get the profile picture URL for a contact (best-effort).
> The path segment is `profile-picture` (hyphenated), not `profile-pic`.
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key
+
+#### GET /api/sessions/:sessionId/contacts/profile-pictures
+
+Batch-resolve profile picture URLs for many contacts in one request (a chat sidebar would otherwise fire a burst of single fetches and exhaust the per-IP throttle).
+
+**Auth:** API key
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID. |
+
+**Query parameters**
+
+| Name | Type | Required | Description |
+| --- | --- | --- | --- |
+| ids | string | Yes | Comma-separated contact ids. Blank entries are dropped; only the **first 50** ids are looked up, the rest are ignored (they simply do not appear in the response). |
+
+**Response** `200`
+
+```json
+{
+ "pictures": {
+ "[email protected]": "https://pps.whatsapp.net/v/...",
+ }
+}
+```
+
+`pictures` is keyed by the requested id. A per-id failure — or a lookup that exceeds the 8 s per-id deadline — yields `null` for that id rather than failing the batch. An omitted or empty `ids` returns `{ "pictures": {} }`.
+
+> Route-order caveat: `profile-pictures` is declared **before** `GET /:contactId`, so the literal segment wins — a contact whose id is literally `profile-pictures` cannot be fetched through the single-contact route.
+
+**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session
#### GET /api/sessions/:sessionId/contacts/:contactId/phone
@@ -1610,7 +1645,7 @@ Resolve a contact id (e.g. an `@lid`) to a phone number (MSISDN digits), best-ef
`phone` is `null` when the engine cannot map the id (e.g. an `@lid` the account has never seen).
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key
#### POST /api/sessions/:sessionId/contacts/:contactId/block
@@ -1635,7 +1670,7 @@ This route is annotated `@HttpCode(200)`, so it returns `200` rather than the PO
{ "success": true, "message": "Contact blocked" }
```
-**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR
#### DELETE /api/sessions/:sessionId/contacts/:contactId/block
@@ -1660,7 +1695,7 @@ No `@HttpCode` override is present, so this DELETE returns the NestJS default `2
{ "success": true, "message": "Contact unblocked" }
```
-**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session not found
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` key role below OPERATOR
### 6.4.4 Groups
@@ -1687,15 +1722,13 @@ List all groups for a session, with pagination.
**Response** `200`
-Raw array (no envelope). The service calls `engine.getGroups()` then paginates to bound the window.
+Raw array (no envelope). The service calls `engine.getGroups()`, projects each entry down to `id`/`name`/`linkedParentJID`, then paginates to bound the window. Anything else the engine's group object may carry is dropped by that projection — use `GET /groups/:groupId` (participants, settings, owner) when you need more than the identity.
```json
[
{
"name": "Project Team",
- "participantsCount": 12,
- "isAdmin": true,
"linkedParentJID": null
}
]
@@ -1837,12 +1870,21 @@ Add participants to a group.
**Response** `200`
-Status is forced to `200` via `@HttpCode(HttpStatus.OK)` (overriding the POST default). The body is a fixed acknowledgement after the void engine call.
+Status is forced to `200` via `@HttpCode(HttpStatus.OK)` (overriding the POST default). `results` carries the engine's per-participant outcome — a partial refusal does **not** fail the batch, so check `results[].success` rather than the envelope's `success`.
```json
-{ "success": true, "message": "Participants added" }
+{
+ "success": true,
+ "message": "Participants added",
+ "results": [
+ { "id": "[email protected]", "success": true, "status": 200 },
+ { "id": "[email protected]", "success": false, "status": 403, "message": "invite-only" }
+ ]
+}
```
+Each entry is a `ParticipantOperationResult`: `id` (the participant the outcome belongs to), `success` (true only when the engine confirmed the change for that participant), and the optional engine-reported `status`/`message` (e.g. `200` ok, `403` invite-only/not-admin, `404` not registered, `409` already a member). Engines that only confirm the batch as a whole report one success entry per requested participant.
+
**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
#### DELETE /api/sessions/:sessionId/groups/:groupId/participants
@@ -1870,10 +1912,14 @@ Remove participants from a group. Note: this DELETE carries a JSON request body.
**Response** `200`
-No `@HttpCode`, so NestJS uses the DELETE default of `200`.
+No `@HttpCode`, so NestJS uses the DELETE default of `200`. `results` carries the per-participant outcome (see the add route above).
```json
-{ "success": true, "message": "Participants removed" }
+{
+ "success": true,
+ "message": "Participants removed",
+ "results": [{ "id": "[email protected]", "success": true, "status": 200 }]
+}
```
**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
@@ -1901,10 +1947,14 @@ Promote participants to group admin.
{ "participants": ["[email protected]"] }
```
-**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`). `results` carries the per-participant outcome (see the add route above).
```json
-{ "success": true, "message": "Participants promoted to admin" }
+{
+ "success": true,
+ "message": "Participants promoted to admin",
+ "results": [{ "id": "[email protected]", "success": true, "status": 200 }]
+}
```
**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
@@ -1932,10 +1982,14 @@ Demote participants from group admin.
{ "participants": ["[email protected]"] }
```
-**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`)
+**Response** `200` (forced via `@HttpCode(HttpStatus.OK)`). `results` carries the per-participant outcome (see the add route above).
```json
-{ "success": true, "message": "Participants demoted from admin" }
+{
+ "success": true,
+ "message": "Participants demoted from admin",
+ "results": [{ "id": "[email protected]", "success": true, "status": 200 }]
+}
```
**Errors:** `400` validation / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role
@@ -2357,9 +2411,9 @@ Get business catalog info for the session's WhatsApp Business account.
}
```
-**Not implemented on any engine.** whatsapp-web.js returns `null` unconditionally (it has no native Catalog API and the adapter stubs without calling the client); Baileys raises `501`. The shape below documents the contract, not a response you can obtain today. The response is the raw `engine.getCatalog()` return — no envelope.
+**Not implemented on any engine.** Both adapters throw `EngineNotSupportedError` (`501`) — whatsapp-web.js has no native Catalog API (the former null-returning stub was removed), and Baileys leaves it unwired. The shape above documents the contract, not a response you can obtain today. The whatsapp-web.js adapter calls its readiness guard *before* refusing, so a session that exists but is not `READY` (initializing, waiting on a QR, reconnecting) gets `409` instead of `501`; Baileys refuses unconditionally.
-**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `409` session present but not READY (whatsapp-web.js only) · `501` not implemented on either engine
#### GET /api/sessions/:sessionId/catalog/products
@@ -2404,7 +2458,9 @@ Validated against `ProductQueryDto` via the global ValidationPipe; any unknown q
}
```
-**Errors:** `400` invalid `page`/`limit` or unknown query key · `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+**Not implemented on any engine.** Both adapters throw `EngineNotSupportedError` (`501`), so the shape above documents the contract, not a response you can obtain today. Query validation still runs first, so a bad `page`/`limit` is a `400`. On whatsapp-web.js the readiness guard runs before the refusal, so a session that exists but is not `READY` gets `409` instead of `501`; Baileys refuses unconditionally.
+
+**Errors:** `400` invalid `page`/`limit` or unknown query key · `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `409` session present but not READY (whatsapp-web.js only) · `501` not implemented on either engine
#### GET /api/sessions/:sessionId/catalog/products/:productId
@@ -2436,9 +2492,9 @@ Get a specific catalog product by id.
}
```
-An unknown `productId` returns `200` with body `null` — it is **not** a `404`. Only a missing/disconnected session yields `404`.
+**Not implemented on any engine.** Both adapters throw `EngineNotSupportedError` (`501`), so the shape above documents the contract, not a response you can obtain today. On whatsapp-web.js the readiness guard runs before the refusal, so a session that exists but is not `READY` gets `409` instead of `501`; Baileys refuses unconditionally.
-**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `500` engine error
+**Errors:** `401` missing/invalid API key · `404` `Session <sessionId> not found or not connected` · `409` session present but not READY (whatsapp-web.js only) · `501` not implemented on either engine
#### POST /api/sessions/:sessionId/messages/send-product
@@ -2468,7 +2524,7 @@ Send a product message (catalog product card) to a chat. Note: this route lives
}
```
-**Response** `501` — always (not implemented)
+**Response** `501` (not implemented on either engine)
```json
{
@@ -2480,8 +2536,10 @@ Send a product message (catalog product card) to a chat. Note: this route lives
No engine implements this. whatsapp-web.js and Baileys both raise `EngineNotSupportedError`, so the
route cannot return a success body on any deployment; it is documented here because it is mounted.
+On whatsapp-web.js the readiness guard runs before the refusal, so a session that exists but is not
+`READY` gets `409` instead of `501`; Baileys refuses unconditionally.
-**Errors:** `400` missing `chatId`/`productId`, wrong types, or any field not on the DTO · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `500` engine error
+**Errors:** `400` missing `chatId`/`productId`, wrong types, or any field not on the DTO · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `409` session present but not READY (whatsapp-web.js only) · `500` engine error
#### POST /api/sessions/:sessionId/messages/send-catalog
@@ -2509,7 +2567,7 @@ Send the business catalog link to a chat. Note: this route lives under the `/mes
}
```
-**Response** `501` — always (not implemented)
+**Response** `501` (not implemented on either engine)
```json
{
@@ -2521,8 +2579,10 @@ Send the business catalog link to a chat. Note: this route lives under the `/mes
No engine implements this. whatsapp-web.js and Baileys both raise `EngineNotSupportedError`, so the
route cannot return a success body on any deployment; it is documented here because it is mounted.
+On whatsapp-web.js the readiness guard runs before the refusal, so a session that exists but is not
+`READY` gets `409` instead of `501`; Baileys refuses unconditionally.
-**Errors:** `400` missing/invalid `chatId` or any non-DTO field · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `500` engine error
+**Errors:** `400` missing/invalid `chatId` or any non-DTO field · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected` · `409` session present but not READY (whatsapp-web.js only) · `500` engine error
#### GET /api/sessions/:sessionId/channels
@@ -2604,7 +2664,7 @@ Get recent messages from a channel/newsletter.
| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
-| `limit` | number | No | engine default (Swagger notes 50) | Max messages to return. Taken as a raw query string and run through `parseInt(limit, 10)` when present, else `undefined` is passed to the engine. There is **no** DTO/ValidationPipe on this value — a non-numeric `limit` becomes `NaN` and is forwarded to the engine. |
+| `limit` | number | No | engine default (Swagger notes 50) | Max messages to return. Taken as a raw query string and run through `parseInt(limit, 10)` when present. There is **no** DTO/ValidationPipe on this value, but a non-numeric `limit` (e.g. `?limit=abc`) parses to `NaN` and falls back to `undefined`, i.e. the engine default — it is never forwarded as `NaN`. |
**Response** `200`
@@ -2690,6 +2750,8 @@ Note: this is the one route in the module that returns a literal `{ success: tru
Labels are a WhatsApp Business feature: every label route lives under a session and reads/writes the chat-label assignments exposed by the engine. Status routes manage the session's status feed (stories) — reading visible statuses and posting/deleting your own. Read routes require a base API key; all writes require `OPERATOR`.
+**Label reads are whatsapp-web.js only.** `GET /labels`, `GET /labels/:labelId` and `GET /labels/chat/:chatId` throw `501` on the Baileys engine, which exposes no label query (the library only has the association *writes*). Adding/removing a chat label works on both engines.
+
**Reads are store-backed, not engine-direct.** `GET /status` and `GET /status/:contactId` no longer call the engine — they read from an OpenWA-side store that ingests inbound status/story broadcasts as they arrive (plus a best-effort backfill of currently-active stories on session connect), with a 24h TTL matching WhatsApp's own story expiry. This makes reads **identical on both engines**: `whatsapp-web.js` (which had a native `getBroadcasts()`/`getBroadcastById()` path) and Baileys (which never had one — `fetchStatus` only returns the *about* text, not stories, so the raw engine methods still throw `501` if called directly, they're just no longer on the read path) now return the same shape from the same source. A status older than 24h, or received before the store existed, will not appear.
#### GET /api/sessions/:sessionId/labels
@@ -2715,7 +2777,7 @@ List all labels defined for the session (WhatsApp Business accounts only).
Bare array — raw return of `engine.getLabels()`; no envelope.
-**Errors:** `400` session is not started (no live engine), or the account is not a WhatsApp Business account · `401` missing/invalid API key
+**Errors:** `400` session is not started (no live engine), or the account is not a WhatsApp Business account · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only)
#### GET /api/sessions/:sessionId/labels/:labelId
@@ -2738,7 +2800,7 @@ Get a single label by its ID.
The engine resolves `Label | null`; a `null` is mapped to `404` in the service, so a `200` always carries a label.
-**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Label <labelId> not found`
+**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Label <labelId> not found` · `501` the Baileys engine does not implement label reads (whatsapp-web.js only)
#### GET /api/sessions/:sessionId/labels/chat/:chatId
@@ -2763,7 +2825,7 @@ List the labels currently assigned to a specific chat.
Bare array — raw return of `engine.getChatLabels(chatId)`.
-**Errors:** `400` session is not started · `401` missing/invalid API key
+**Errors:** `400` session is not started · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only)
#### POST /api/sessions/:sessionId/labels/chat/:chatId
@@ -2929,10 +2991,10 @@ Post a text status (story) to the session's status feed. The recipients allow-li
| Field | Type | Required | Constraints | Description |
| --- | --- | --- | --- | --- |
-| text | string | yes | — | Status text body |
-| recipients | string[] | yes | 1–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status. **Honored on Baileys only** (passed as `statusJidList`); whatsapp-web.js ignores the allow-list and broadcasts to the account's status-privacy audience. Empty array → `400` |
+| text | string | yes | `@MaxLength(4096)` | Status text body |
+| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status. **Honored on Baileys only** (passed as `statusJidList`), where it is required in practice — Baileys posts to exactly this allow-list, so omitting it reaches nobody. whatsapp-web.js ignores it and broadcasts to the account's status-privacy audience; omit it there |
| backgroundColor | string | no | 6-digit hex color matching `^#[0-9A-Fa-f]{6}$` | e.g. `#25D366`; bad value → `backgroundColor must be a hex color (e.g., #25D366)` |
-| font | integer | no | integer `0`–`5` | Font index |
+| font | integer | no | `@IsIn([0, 1, 2, 6, 7, 8, 9, 10])` — `3`–`5` are rejected with `400` | WhatsApp status font index: `0` (default), `1`, `2`, `6` (bold), `7`, `8`, `9`, `10`. whatsapp-web.js honors only `0`–`7` and clamps anything above back to the default |
```json
{ "text": "Hello from OpenWA!", "recipients": ["[email protected]"], "backgroundColor": "#25D366", "font": 2 }
@@ -2954,7 +3016,7 @@ Returns the engine `StatusResult` directly (no wrapper). POST default status is
**Sender-side caveat:** the posting account's own phone may display a "waiting for this status update" notice in its status feed; this is cosmetic — recipients view the status normally.
-**Errors:** `400` validation failure (unknown body field, missing/empty `recipients`, a JID not matching `@c.us`/`@lid`, or more than 256 recipients, bad `backgroundColor`/`font`), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+**Errors:** `400` validation failure (unknown body field, a JID not matching `@c.us`/`@lid`, more than 256 recipients, `text` over 4096 chars, bad `backgroundColor`/`font`) · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
#### POST /api/sessions/:sessionId/status/send-image
@@ -2972,14 +3034,14 @@ Post an image status (story) from a URL or base64 payload. The recipients allow-
| Field | Type | Required | Constraints | Description |
| --- | --- | --- | --- | --- |
-| image | object (`MediaInput`) | yes | validated nested object (an empty `{}` passes — there is no `@IsNotEmpty`) | Media source wrapper |
-| image.url | string | no | — | Media source URL |
-| image.base64 | string | no | — | Base64-encoded media data |
+| image | object (`StatusMediaInput`) | yes | validated nested object; one of `url`/`base64` must be present — an empty `{}` is rejected with `400` | Media source wrapper |
+| image.url | string | no | must be a non-empty string whenever `base64` is absent **or** `url` is present at all — `"url": ""` is rejected with `400` even when a valid `base64` is supplied | Media source URL |
+| image.base64 | string | no | must be a non-empty string whenever `url` is absent **or** `base64` is present at all — `"base64": ""` is rejected with `400` even when a valid `url` is supplied | Base64-encoded media data |
| image.mimetype | string | no | — | Media MIME type; if omitted the service defaults to `image/jpeg` |
-| recipients | string[] | yes | 1–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status (`statusJidList`). Empty array → `400` |
-| caption | string | no | — | Optional caption |
+| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status (`statusJidList`). Required in practice on Baileys (it posts to exactly this allow-list); ignored by whatsapp-web.js — omit it there |
+| caption | string | no | `@MaxLength(1024)` | Optional caption |
-The service resolves the media as `image.url || image.base64 || ''` and applies mimetype `image.mimetype ?? 'image/jpeg'`.
+The service resolves the media as `image.base64 || image.url || ''` — `base64` wins when both are supplied — and applies mimetype `image.mimetype ?? 'image/jpeg'`.
```json
{ "image": { "url": "https://example.com/photo.jpg", "mimetype": "image/png" }, "recipients": ["[email protected]"], "caption": "My status" }
@@ -2999,7 +3061,7 @@ Returns the engine `StatusResult` directly. POST default status is `201`.
**Recipient JIDs:** `@c.us` (regular phone) recipients are reliable. `@lid` (privacy-id) recipients are best-effort and unverified — prefer `@c.us` where the phone number is known. **Sender-side caveat:** the posting account's own phone may show a "waiting for this status update" notice; recipients view it normally.
-**Errors:** `400` validation failure (unknown body field, missing/empty `recipients`, a JID not matching `@c.us`/`@lid`, or more than 256 recipients), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars) · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
#### POST /api/sessions/:sessionId/status/send-video
@@ -3017,14 +3079,14 @@ Post a video status (story) from a URL or base64 payload. The recipients allow-l
| Field | Type | Required | Constraints | Description |
| --- | --- | --- | --- | --- |
-| video | object (`MediaInput`) | yes | validated nested object (an empty `{}` passes) | Media source wrapper |
-| video.url | string | no | — | Media source URL |
-| video.base64 | string | no | — | Base64-encoded media data |
+| video | object (`StatusMediaInput`) | yes | validated nested object; one of `url`/`base64` must be present — an empty `{}` is rejected with `400` | Media source wrapper |
+| video.url | string | no | must be a non-empty string whenever `base64` is absent **or** `url` is present at all — `"url": ""` is rejected with `400` even when a valid `base64` is supplied | Media source URL |
+| video.base64 | string | no | must be a non-empty string whenever `url` is absent **or** `base64` is present at all — `"base64": ""` is rejected with `400` even when a valid `url` is supplied | Base64-encoded media data |
| video.mimetype | string | no | — | Media MIME type; if omitted the service defaults to `video/mp4` |
-| recipients | string[] | yes | 1–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status (`statusJidList`). Empty array → `400` |
-| caption | string | no | — | Optional caption |
+| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs of the contacts permitted to view the status (`statusJidList`). Required in practice on Baileys (it posts to exactly this allow-list); ignored by whatsapp-web.js — omit it there |
+| caption | string | no | `@MaxLength(1024)` | Optional caption |
-The service resolves the media as `video.url || video.base64 || ''` and applies mimetype `video.mimetype ?? 'video/mp4'`.
+The service resolves the media as `video.base64 || video.url || ''` — `base64` wins when both are supplied — and applies mimetype `video.mimetype ?? 'video/mp4'`.
```json
{ "video": { "url": "https://example.com/clip.mp4", "mimetype": "video/quicktime" }, "recipients": ["[email protected]"], "caption": "Watch this" }
@@ -3044,7 +3106,7 @@ Returns the engine `StatusResult` directly. POST default status is `201`.
**Recipient JIDs:** `@c.us` (regular phone) recipients are reliable. `@lid` (privacy-id) recipients are best-effort and unverified — prefer `@c.us` where the phone number is known. **Sender-side caveat:** the posting account's own phone may show a "waiting for this status update" notice; recipients view it normally.
-**Errors:** `400` validation failure (unknown body field, missing/empty `recipients`, a JID not matching `@c.us`/`@lid`, or more than 256 recipients), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars) · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
#### DELETE /api/sessions/:sessionId/status/:statusId
@@ -3071,7 +3133,7 @@ The service returns `void`; the controller returns a fixed success object. DELET
### 6.4.8 Webhooks (management)
-Webhooks are configured per session and managed under `/api/sessions/:sessionId/webhooks` (handled by `WebhookController`). A separate cross-session list endpoint lives at `/api/webhooks` (handled by `WebhooksListController`). Every route requires an API key with **OPERATOR** role or higher.
+Webhooks are configured per session and managed under `/api/sessions/:sessionId/webhooks` (handled by `WebhookController`). Two cross-session endpoints live on `WebhooksListController`: `GET /api/webhooks` (list, **OPERATOR**) and `GET /api/webhooks/delivery-failures` (dead-letter log, **ADMIN**). Every other route requires an API key with **OPERATOR** role or higher.
Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.
@@ -3180,6 +3242,44 @@ Bare array, ordered by `createdAt` descending, bounded by `limit`/`offset`. If t
**Errors:** `401` missing/invalid API key · `403` insufficient role
+#### GET /api/webhooks/delivery-failures
+
+List webhook deliveries that exhausted every retry, most recent first. This is the dead-letter trail referenced by §6.6 — a receiver outage longer than the retry window, an over-budget payload, or a blocked (SSRF-guarded) URL lands here instead of vanishing.
+
+**Auth:** API key (ADMIN) · **Scope:** results are confined to the calling key's `allowedSessions`, so a session-restricted ADMIN key cannot read another session's rows via `sessionId`
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `sessionId` | string | No | — | Narrow to one session. A value outside the key's `allowedSessions` returns `[]` (no cross-session existence oracle). |
+| `limit` | integer (1-1000) | No | `1000` | Max records to return; oversized/non-finite values are clamped/fallback to the default window. |
+| `offset` | integer | No | `0` | Records to skip for paging; negative/non-finite values resolve to `0`. |
+
+**Response** `200`
+
+```json
+[
+ {
+ "id": "8c0b1f2e-3d4a-5b6c-7d8e-9f0a1b2c3d4e",
+ "webhookId": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "sessionId": "my-session",
+ "event": "message.received",
+ "url": "https://your-server.com/webhook",
+ "idempotencyKey": "msg_my-session_3EB0..._f1e2d3c4-b5a6-7890-1234-567890abcdef",
+ "deliveryId": "dlv_0f8c1a2b-3c4d-5e6f-7a8b-9c0d1e2f3a4b",
+ "attempts": 4,
+ "lastStatusCode": 502,
+ "lastError": "Request failed with status code 502",
+ "createdAt": "2026-06-25T11:59:00.000Z"
+ }
+]
+```
+
+Bare array of `WebhookDeliveryFailure` rows, ordered by `createdAt` descending. `lastStatusCode` is `null` when the failure was a network/timeout/SSRF error rather than a non-2xx response; `idempotencyKey`/`deliveryId` let you correlate the lost event with your own receiver logs.
+
+**Errors:** `401` missing/invalid API key · `403` key role below ADMIN
+
#### POST /api/sessions/:sessionId/webhooks
Create a webhook for the session.
@@ -3263,7 +3363,7 @@ Update a webhook. Partial — only fields present in the body are changed.
| Field | Type | Required | Constraints | Description |
| --- | --- | --- | --- | --- |
| url | string | no | `@IsOptional`, `@IsUrl({ require_tld: false })`; re-runs the SSRF guard when provided → `400` if blocked. | New URL. |
-| events | string[] | no | `@IsOptional`, `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Same allowed set as create (incl. `*` and reserved `group.*`). |
+| events | string[] | no | `@IsOptional`, `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Same allowed set as create (incl. `*`). |
| secret | string | no | `@IsOptional`, `@IsString`, `@MaxLength(255)` | **Write-only.** An empty string is normalized to `null`, which disables HMAC. |
| headers | Record<string,string> | no | `@IsOptional`, `@IsHeaderMap()` (same constraints as create) | **Write-only.** Replaces existing headers wholesale when provided. |
| filters | WebhookFilters \| null | no | `@IsOptional`, `@IsValidWebhookFilters()` | Set to `null` to clear filters. |
@@ -3344,7 +3444,7 @@ No content (empty body; explicit `@HttpCode(204)`).
### 6.4.9 API Keys
-API keys are managed under `/api/auth/api-keys`. All management routes (create/list/get/update/delete/revoke) require an **ADMIN** key. The plaintext key string is returned **only once**, at creation. Validation of the caller's own key lives at `POST /api/auth/validate` and accepts any valid key.
+API keys are managed under `/api/auth/api-keys`. All management routes (create/list/get/update/delete/revoke) require an **ADMIN** key **with no session scope**: the controller is fenced with `@RequireUnscopedKey`, so a key whose `allowedSessions` is non-empty is rejected with `403` whatever its role — otherwise a confined admin key could mint an unrestricted one. The guard evaluates the role requirement *before* that fence, so a scoped VIEWER/OPERATOR key is refused with `Insufficient permissions. Required: admin`; only a scoped ADMIN key reaches the fence and sees `Session-scoped API keys are not permitted on this route`. Both are `403`. The plaintext key string is returned **only once**, at creation. Validation of the caller's own key lives at `POST /api/auth/validate` (a separate controller, not fenced) and accepts any valid key.
#### GET /api/auth/api-keys
@@ -3374,7 +3474,7 @@ Bare JSON array (no envelope), ordered by `createdAt` DESC. Null array/date fiel
]
```
-**Errors:** `401` missing/invalid `X-API-Key` · `403` key role below ADMIN
+**Errors:** `401` missing/invalid `X-API-Key` · `403` key role below ADMIN, or the key is session-scoped
#### GET /api/auth/api-keys/:id
@@ -3406,7 +3506,7 @@ Get a single API key's details by id. No plaintext key.
}
```
-**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` `"API key with id '<id>' not found"`
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped · `404` `"API key with id '<id>' not found"`
#### POST /api/auth/api-keys
@@ -3454,7 +3554,7 @@ Same shape as the read DTO **plus** an `apiKey` field carrying the full plaintex
}
```
-**Errors:** `400` validation (bad `name` length, invalid `role` enum, non-IPv4 `allowedIps` entry, bad `expiresAt`, or any non-whitelisted body field) · `401` missing/invalid key · `403` key role below ADMIN
+**Errors:** `400` validation (bad `name` length, invalid `role` enum, non-IPv4 `allowedIps` entry, bad `expiresAt`, or any non-whitelisted body field) · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped
#### PUT /api/auth/api-keys/:id
@@ -3505,7 +3605,7 @@ Returns the updated key (no plaintext).
}
```
-**Errors:** `400` validation (incl. `forbidNonWhitelisted` for unknown fields such as `isActive`) · `401` missing/invalid key · `403` key role below ADMIN · `404` not found · `409` change would remove the last usable admin key
+**Errors:** `400` validation (incl. `forbidNonWhitelisted` for unknown fields such as `isActive`) · `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped · `404` not found · `409` change would remove the last usable admin key
#### POST /api/auth/api-keys/:id/revoke
@@ -3535,7 +3635,7 @@ Sets `isActive` to `false` and returns the key with explicit HTTP `200`. After r
}
```
-**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` not found · `409` target is the last usable admin key
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped · `404` not found · `409` target is the last usable admin key
#### DELETE /api/auth/api-keys/:id
@@ -3553,7 +3653,7 @@ Permanently delete an API key (hard delete). Also drops any un-flushed usage acc
`@HttpCode(204)` — no response body.
-**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` `"API key with id '<id>' not found"` · `409` target is the last usable admin key
+**Errors:** `401` missing/invalid key · `403` key role below ADMIN, or the key is session-scoped · `404` `"API key with id '<id>' not found"` · `409` target is the last usable admin key
#### POST /api/auth/validate
@@ -3573,9 +3673,9 @@ The key is read from the `X-API-Key` header, not the body; send an empty body. T
> Implemented by `AuthValidateController` (`@Controller('auth')`), sharing the same `/api/auth` base.
-### 6.4.10 System (Health, Metrics, Stats, Settings)
+### 6.4.10 System (Health, Metrics, Stats, Settings, Audit)
-System endpoints expose operational status, Prometheus metrics, aggregate statistics, and runtime settings. Health and metrics use non-standard auth (public / Bearer token); stats and settings use the API key, with several routes gated to `ADMIN`.
+System endpoints expose operational status, Prometheus metrics, aggregate statistics, runtime settings, and the audit log. Health and metrics use non-standard auth (public / Bearer token); stats, settings and audit use the API key, with several routes gated to `ADMIN`.
#### GET /api/health
@@ -3689,7 +3789,7 @@ Get overall cross-session aggregate statistics (sessions by status + message tot
"sessions": {
"active": 2,
"total": 3,
- "byStatus": { "READY": 2, "DISCONNECTED": 1 }
+ "byStatus": { "ready": 2, "disconnected": 1 }
},
"messages": {
"sent": 1280,
@@ -3700,7 +3800,7 @@ Get overall cross-session aggregate statistics (sessions by status + message tot
}
```
-Notes: raw handler return (no envelope). `sessions.byStatus` is keyed by `SessionStatus` enum values with per-status counts; `sessions.active` counts only `READY`. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `failed` is the `FAILED`-status COUNT; `today.*` are the same counts since local midnight. Side effect: caches the `sessions` block via `CacheService`.
+Notes: raw handler return (no envelope). `sessions.byStatus` is keyed by the stored `SessionStatus` values — lowercase, per §6.4.1 — with per-status counts; `sessions.active` counts only `ready`. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `failed` is the `FAILED`-status COUNT; `today.*` are the same counts since local midnight. Side effect: caches the `sessions` block via `CacheService`.
**Errors:** `401` — missing/invalid `X-API-Key` · `403` — key role below `ADMIN`.
@@ -3742,7 +3842,7 @@ Notes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket strin
Get statistics for a single session: identity, message counts, top chats, and 24 h hourly activity.
-**Auth:** API key — any valid key (VIEWER and up); there is no `@RequireRole`. Note: the handler does NOT verify the key is scoped to this session, so any authenticated key can read any session's stats.
+**Auth:** API key — any valid key (VIEWER and up); there is no `@RequireRole`. Scope still applies: the global guard feeds the `:sessionId` route param to the key's `allowedSessions`, so a session-scoped key asking for a session outside its list gets `401 "API key not authorized for this session"`. Only an unscoped key can read any session's stats.
**Path parameters**
@@ -3768,13 +3868,13 @@ Get statistics for a single session: identity, message counts, top chats, and 24
Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `today` is the total message count since local midnight; `failed` is the `FAILED`-status count. `topChats` is the top 10 by count DESC, with `lastActive` = `MAX(createdAt)` as a DB-native datetime string. `hourlyActivity` always has 24 entries (hour `0..23`), missing hours zero-filled, computed over the last 24 h.
-**Errors:** `401` — missing/invalid API key · `404` — session not found (`Session not found`).
+**Errors:** `401` — missing/invalid API key, or the key is not scoped to this session · `404` — session not found (`Session not found`).
#### GET /api/settings
Get application settings (environment-derived; `general`/`api`/`notifications` groups).
-**Auth:** API key (ADMIN). Settings expose server configuration, so a VIEWER or session-scoped key is rejected with `403`.
+**Auth:** API key (ADMIN). Settings expose server configuration, so a key below `ADMIN` is rejected with `403`. The route carries no session dimension and is not fenced with `@RequireUnscopedKey`, so a session-scoped ADMIN key is accepted.
**Response** `200`
@@ -3824,11 +3924,59 @@ Notes: the handler unconditionally throws `NotImplementedException`. Even an ADM
**Errors:** `401` — missing/invalid key · `403` — key lacks `ADMIN` · `501` — always (not implemented).
+#### GET /api/audit
+
+List audit-log entries, newest first. Every API-key lifecycle change, session/message/webhook event and ADMIN infra operation lands here.
+
+**Auth:** API key (ADMIN) · **Scope:** rows are confined to the calling key's `allowedSessions` — the `sessionId` query may only narrow within that list, never widen it
+
+**Query parameters**
+
+| Name | Type | Required | Default | Description |
+| --- | --- | --- | --- | --- |
+| `action` | string | No | — | Filter by `AuditAction` (e.g. `api_key_created`, `session_started`, `message_sent`, `webhook_failed`, `infra_data_imported`). |
+| `severity` | `'info' \| 'warn' \| 'error'` | No | — | Filter by `AuditSeverity`. |
+| `sessionId` | string | No | — | Narrow to one session. A value outside the key's `allowedSessions` returns `{ "data": [], "total": 0 }`. |
+| `apiKeyId` | string | No | — | Filter by the acting key's id. |
+| `limit` | integer | No | `50` | Page size, clamped to a maximum of `200`. |
+| `offset` | integer | No | `0` | Rows to skip; a negative value resolves to `0`. |
+
+**Response** `200`
+
+```json
+{
+ "data": [
+ {
+ "id": "6b3f…",
+ "action": "session_started",
+ "severity": "info",
+ "apiKeyId": "1c2d…",
+ "apiKeyName": "dashboard",
+ "sessionId": "9f1c…",
+ "sessionName": "support-line",
+ "ipAddress": "203.0.113.7",
+ "userAgent": "curl/8.4.0",
+ "method": "POST",
+ "path": "/api/sessions/9f1c…/start",
+ "statusCode": 200,
+ "metadata": null,
+ "errorMessage": null,
+ "createdAt": "2026-06-25T11:42:07.000Z"
+ }
+ ],
+ "total": 1
+}
+```
+
+Unlike the other list routes this one is **not** a bare array: `data` is the page and `total` the unpaginated match count. Nullable columns (`apiKeyId`, `sessionId`, `metadata`, `errorMessage`, …) are `null` when the event has no such dimension.
+
+**Errors:** `401` missing/invalid API key · `403` key role below ADMIN
+
### 6.4.11 Administration (Infrastructure, Plugins, MCP)
Admin-facing operations: infrastructure status & config, the data/storage migration tooling, plugin lifecycle, and the optional MCP transport. Almost every route is **API key (ADMIN)**; the two exceptions are the public `GET /api/infra/health` and the `POST /mcp` JSON-RPC endpoint (see end of section).
-> Note on the infra/MCP request bodies: the `PUT /api/infra/config`, `POST /api/infra/restart`, `POST /api/infra/import-data`, `POST /api/infra/storage/import` bodies and the entire `POST /mcp` envelope are **plain TS interfaces, not class-validator DTOs** — the global `whitelist`/`forbidNonWhitelisted` ValidationPipe does **not** run on them. Unknown fields pass through silently and no type/constraint checks happen, except the few field-level guards noted per endpoint. Plugin DTOs (`InstallFromUrlDto`, `PluginConfigDto`, `PluginSessionsDto`) *are* class-validated and reject unknown fields with `400`.
+> Note on the infra/MCP request bodies: the `POST /api/infra/import-data` body and the entire `POST /mcp` envelope (mounted as a raw Express handler, outside the Nest pipe chain) are **plain TS interfaces, not class-validator DTOs** — the global `whitelist`/`forbidNonWhitelisted` ValidationPipe does **not** run on them. Unknown fields pass through silently and no type/constraint checks happen, except the few field-level guards noted per endpoint. The other infra bodies — `SaveConfigDto` (`PUT /api/infra/config`), `RestartDto` (`POST /api/infra/restart`), `ImportStorageDto` (`POST /api/infra/storage/import`) — and the plugin DTOs (`InstallFromUrlDto`, `PluginConfigDto`, `PluginSessionsDto`) *are* class-validated and reject unknown fields with `400`.
---
@@ -3856,23 +4004,27 @@ Aggregate infrastructure status (database, Redis, queue, storage, engine).
```json
{
- "database": { "connected": true, "type": "sqlite", "host": "" },
- "redis": { "enabled": false, "connected": false, "host": "localhost", "port": 6379 },
+ "database": { "connected": true, "type": "sqlite", "host": "", "builtIn": false },
+ "redis": { "enabled": false, "connected": false, "host": "localhost", "port": 6379, "builtIn": false },
"queue": {
"enabled": false,
"webhooks": { "pending": 0, "completed": 0, "failed": 0 }
},
- "storage": { "type": "local", "path": "./data/media" },
+ "storage": { "type": "local", "path": "./data/media", "builtIn": false },
"engine": {
"type": "whatsapp-web.js",
"headless": true,
"sessionDataPath": "./data/sessions",
- "browserArgs": "--no-sandbox --disable-gpu"
+ "browserArgs": "--no-sandbox --disable-gpu",
+ "webVersion": "2.3000.1040641150-alpha",
+ "webVersionSource": "auto"
}
}
```
-The `queue.webhooks` counters are live BullMQ job counts (`pending` = waiting + active + delayed; plus `completed`/`failed`), degrading to zeros when the queue is disabled or Redis is unreachable. `redis.connected` is a live probe. `storage` only ever returns `type`+`path` here (no `bucket`).
+The `queue.webhooks` counters are live BullMQ job counts (`pending` = waiting + active + delayed; plus `completed`/`failed`), degrading to zeros when the queue is disabled or Redis is unreachable. `redis.connected` is a live probe.
+
+`builtIn` (on `database`/`redis`/`storage`) reports whether OpenWA's own bundled container is actually running *and* backing this service, detected live from the labelled container; when Docker is unreachable it falls back to the saved `*_BUILTIN` intent from `data/.env.generated`. In S3 mode `storage` additionally carries `bucket` (when one is configured) and `s3Available` (a throttled re-probe); in local mode neither key is present. `engine.webVersion`/`engine.webVersionSource` (`pinned` / `auto` / `native`) appear only on `whatsapp-web.js`; `webVersion` is `null` until the auto-resolve first succeeds.
**Errors:** `401` missing/invalid key · `403` key role < ADMIN
@@ -3932,7 +4084,7 @@ Read the saved infrastructure config from `data/.env.generated` (used to hydrate
{
"database": {
"type": "sqlite", "builtIn": false, "host": "", "port": "",
- "username": "", "database": "", "poolSize": 10,
+ "username": "", "database": "", "schema": "public", "poolSize": 10,
"sslEnabled": false, "sslRejectUnauthorized": true, "passwordSet": false
},
"redis": { "enabled": false, "builtIn": false, "host": "", "port": "", "passwordSet": false },
@@ -3948,7 +4100,7 @@ Read the saved infrastructure config from `data/.env.generated` (used to hydrate
}
```
-When `data/.env.generated` does not exist, empty-string/default values are returned (`poolSize=10`, `sslRejectUnauthorized=true`, `engine.type='whatsapp-web.js'`, `headless=true`).
+When `data/.env.generated` does not exist, empty-string/default values are returned (`schema='public'`, `poolSize=10`, `sslRejectUnauthorized=true`, `engine.type='whatsapp-web.js'`, `headless=true`).
**Errors:** `401` · `403`
@@ -3968,6 +4120,7 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)
| `database.type` | `'sqlite' \| 'postgres'` | If `database` is present | enum | `sqlite` drops stale postgres keys; `postgres` writes connection keys |
| `database.builtIn` | boolean | No | — | When `true`+postgres, forces the bundled `postgres` container creds + pushes `postgres` Docker profile |
| `database.host` / `.port` / `.username` / `.database` | string | No | `port` is a string | External postgres connection (defaults `localhost`/`5432`/`postgres`/`openwa`) |
+| `database.schema` | string | No | — | Postgres schema, saved as `POSTGRES_SCHEMA`; an empty value writes `public` (also forced to `public` when switching to the built-in DB) |
| `database.password` | string | No | secret | Empty/omitted keeps the existing stored secret |
| `database.poolSize` | number | No | — | Default 10 |
| `database.sslEnabled` | boolean | No | — | Default false |
@@ -4046,10 +4199,12 @@ Request a graceful server restart, optionally orchestrating Docker profiles (add
#### GET /api/infra/export-data
-Export every row from the Data DB (sessions, webhooks, messages, batches, templates, Baileys stored messages) as JSON for migration. Read-only, but runs raw `SELECT *` on the `data` DataSource.
+Export every row of the 13 migration tables from the Data DB as JSON. Read-only, but runs raw `SELECT *` on the `data` DataSource.
**Auth:** API key (ADMIN)
+The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `webhooks`, `messages`, `messageBatches`, `templates`, `baileysStoredMessages`, `lidMappings`, `pluginInstances`, `conversationMappings`, `ingressEvents`, `webhookDeliveryFailures`, `integrationDeliveryFailures`, `statusUpdates`.
+
**Response** `200`
```json
@@ -4057,18 +4212,28 @@ Export every row from the Data DB (sessions, webhooks, messages, batches, templa
"exportedAt": "2026-06-25T12:00:00.000Z",
"dataDbType": "sqlite",
"tables": {
- "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "sessions": [ { "id": "s1", "name": "main", "status": "ready", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
"webhooks": [],
"messages": [],
"messageBatches": [],
"templates": [],
- "baileysStoredMessages": []
+ "baileysStoredMessages": [],
+ "lidMappings": [],
+ "pluginInstances": [],
+ "conversationMappings": [],
+ "ingressEvents": [],
+ "webhookDeliveryFailures": [],
+ "integrationDeliveryFailures": [],
+ "statusUpdates": []
},
- "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0 }
+ "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0, "lidMappings": 0, "pluginInstances": 0, "conversationMappings": 0, "ingressEvents": 0, "webhookDeliveryFailures": 0, "integrationDeliveryFailures": 0, "statusUpdates": 0 },
+ "skippedTables": []
}
```
-Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows include `secret` in cleartext.** `messages`/`messageBatches`/`templates`/`baileysStoredMessages` default to `[]` if their table is missing; `sessions`/`webhooks` are not try-wrapped, so a hard DB error there yields `500`.
+Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows include `secret` in cleartext**, and `pluginInstances` rows carry integration secrets — treat the payload as a credential dump. On Postgres the generated `body_ts` FTS column is stripped from `messages` so archives stay dialect-neutral.
+
+`sessions`/`webhooks` are queried directly, so a hard DB error there yields `500`. The other 11 are queried tolerantly: a *genuinely missing* table (an older DB that has not run the migration) exports as `[]` and its name is listed in `skippedTables`; any other error (lock, I/O, timeout) fails the export rather than reporting the table as empty. Check `skippedTables` before restoring — a skipped table is "not migrated yet", not "exported empty".
**Errors:** `401` · `403` · `500` DB error
@@ -4078,26 +4243,31 @@ Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns
Replace all Data DB rows with the supplied export. **Destructive and transactional (all-or-nothing).**
+> **The replace covers all 13 migration tables, not just the ones you send.** Inside the transaction every table in the migration set is emptied first and only then re-populated from the payload, so a table you omit ends up **empty**, not untouched. Always restore a payload produced by `GET /api/infra/export-data` of the same or a newer build — a hand-built body carrying only a subset silently wipes the rest.
+
**Auth:** API key (ADMIN)
-**Request body** — inline `{ tables: Partial<MigrationTables> }` (plain interface, not class-validated)
+**Request body** — inline `{ tables: Partial<MigrationTables>; force?: boolean; stopOrphans?: boolean }` (plain interface, not class-validated)
| Field | Type | Required | Description |
| --- | --- | --- | --- |
-| `tables` | object | Yes | Container of per-table row arrays. Accessing `data.tables` directly means a missing/null value throws `500` |
-| `tables.sessions` | `SessionRow[]` | No | Inserted first; skipped if absent/empty |
+| `tables` | object | Yes | Container of per-table row arrays, keyed exactly as the export's `tables`. Accessing `data.tables` directly means a missing/null value throws `500` |
+| `tables.sessions` | `SessionRow[]` | No | Inserted first; a row whose `name` is not a safe directory name is skipped with a warning (which then rolls the whole restore back) |
| `tables.webhooks` | `WebhookRow[]` | No | Includes `secret` |
-| `tables.messages` | `MessageRow[]` | No | — |
| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |
-| `tables.templates` | `TemplateRow[]` | No | — |
-| `tables.baileysStoredMessages` | `BaileysStoredMessageRow[]` | No | — |
+| `tables.*` (the remaining 10) | `Row[]` | No | Same keys as the export; an omitted table restores **zero** rows into an emptied table |
+| `stopOrphans` | boolean | No | Stop the running engines for sessions the backup does not contain, inside this request and before the replace (best-effort, time-bounded per engine). Preferred over `force` |
+| `force` | boolean | No | Legacy escape hatch: proceed despite orphaned engines and leave them running until a process restart (`restartRequired: true`) |
```json
{
"tables": {
- "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
- "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": []
- }
+ "sessions": [ { "id": "s1", "name": "main", "status": "ready", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": [],
+ "lidMappings": [], "pluginInstances": [], "conversationMappings": [], "ingressEvents": [],
+ "webhookDeliveryFailures": [], "integrationDeliveryFailures": [], "statusUpdates": []
+ },
+ "stopOrphans": true
}
```
@@ -4106,14 +4276,23 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
```json
{
"imported": true,
- "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0 },
- "warnings": []
+ "counts": { "sessions": 1, "webhooks": 0, "messages": 0, "messageBatches": 0, "templates": 0, "baileysStoredMessages": 0, "lidMappings": 0, "pluginInstances": 0, "conversationMappings": 0, "ingressEvents": 0, "webhookDeliveryFailures": 0, "integrationDeliveryFailures": 0, "statusUpdates": 0 },
+ "warnings": [],
+ "notices": [],
+ "restartRequired": false,
+ "orphanedEngines": [],
+ "stoppedOrphanEngines": [],
+ "failedOrphanEngines": []
}
```
-Inside a transaction it DELETEs all rows from webhooks/messages/message_batches/templates/baileys_stored_messages/sessions, then re-inserts. If **any** row insert fails, `warnings` is non-empty, the transaction is **rolled back**, and `imported:false` is returned (counts reflect rows inserted before the failure). JSON object/array fields are auto-stringified before insert.
+`warnings` are per-row import failures — they force a **rollback** and `imported:false`. `notices` are non-fatal operator messages (orphan-engine reconciliation detail) and never roll anything back. `restartRequired` is `true` when engines were left pointing at sessions the restore removed (`force`) or when an orphan teardown failed. `orphanedEngines` lists the session ids with a live engine the restored data no longer contains; `stoppedOrphanEngines`/`failedOrphanEngines` report how `stopOrphans` went.
+
+**Orphan-engine pre-flight.** Before the transaction opens, any running engine whose session id is absent from `tables.sessions` is an orphan (the replace would delete its DB row, leaving an unstoppable engine writing into freshly restored tables). Default behaviour is to refuse with `409` listing those ids; `stopOrphans: true` stops them in-request and proceeds; `force: true` proceeds and leaves them running until restart.
+
+Inside the transaction every migration table is emptied. `webhooks` and `sessions` are DELETEd directly, so a missing table there fails the restore; the other 11 go through a tolerant helper where a *genuinely missing* table is skipped. Any other DELETE failure propagates to the rollback. Rows are then re-inserted, sessions first. JSON object/array fields are auto-stringified before insert, and the Postgres-form `$N` placeholders are rewritten for SQLite. Two guards return `imported:false` after a rollback: any `warnings`, and a payload that restores **zero** rows in total (a wrong/empty backup would otherwise commit a silent wipe — the response then carries `Backup contained no rows to restore; refused to replace existing data. Check the file.`). On commit the lid→phone mirror is reloaded from the restored rows.
-**Errors:** `401` · `403` · `500` `tables` missing/null or unrecoverable DB error
+**Errors:** `401` · `403` · `409` live engines exist for sessions the backup does not contain (retry with `stopOrphans` or `force`) · `500` `tables` missing/null or unrecoverable DB error
---
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 36017f98f..7c5c383a6 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -2,7 +2,7 @@
## 07.1 Overview
-This collection gives a runnable cURL for every OpenWA REST endpoint. The examples assume two environment variables — set them once and reuse them:
+This collection gives a runnable cURL for the primary OpenWA REST endpoints; the complete route list lives in `openapi.json` at the repository root. The Swagger UI at `/api/docs` serves the same schema, but it defaults off under `NODE_ENV=production` — set `ENABLE_SWAGGER=true` to serve it there. The examples assume two environment variables — set them once and reuse them:
```bash
export BASE=http://localhost:2785
@@ -13,7 +13,7 @@ export API_KEY=owa_k1_your-api-key-here
### Authentication
-Every request carries the key in the `X-API-Key` header — REST auth is **header-only**, an `?apiKey=` query value is not accepted. Routes that mutate state need an `operator` key; API-key and settings management need an `admin` key; read-only routes accept any valid key. The metrics endpoint uses `Authorization: Bearer $METRICS_TOKEN` instead.
+Every request carries the key in the `X-API-Key` header — REST auth is **header-only**, an `?apiKey=` query value is not accepted. Routes that mutate state need an `operator` key; API-key and settings management need an `admin` key. Most read-only routes accept any valid key, but template and webhook reads need `operator`, plugin reads and infra reads need `admin` (except `GET /api/infra/health`, which is public), and the cross-session stats reads — `/api/stats/overview` and `/api/stats/messages` — need `admin` while per-session stats accept any role. Each section states its own requirement. The metrics endpoint uses `Authorization: Bearer $METRICS_TOKEN` instead.
```bash
# the auth header that prefixes nearly every call below
@@ -32,6 +32,12 @@ Sessions · Messages · Webhooks · Groups · Contacts · Chats · Labels · Cha
All examples assume `BASE` and `API_KEY` are exported (see 07.1). Paths are prefixed with `/api`.
+The `:sessionId` path segment is always the session **UUID** returned by `POST /api/sessions` — never the session name. Session routes (07.3) use `:id` for that same UUID; everywhere else `:id` is a different resource's id — a template, webhook, API key or plugin — and never a session. Export the session UUID once alongside the other variables:
+
+```bash
+export SESSION_ID=8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a
+```
+
### 07.3 Sessions
All routes are under `$BASE/api/sessions` and require `X-API-Key: $API_KEY` (some require an OPERATOR-role key). Reads come first, then writes.
@@ -56,7 +62,7 @@ curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" \
#### GET /api/sessions/:id/qr
-Get the QR code (PNG data URL) for authentication.
+Get the QR code (PNG data URL) for authentication (OPERATOR).
```bash
curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/qr" \
@@ -212,7 +218,7 @@ All routes are under `/api/sessions/:sessionId/messages`. Reads accept any API k
Get persisted message history from the local DB (paginated, filterable).
```bash
-curl "$BASE/api/sessions/my-session/[email protected]&limit=20&offset=0" \
+curl "$BASE/api/sessions/$SESSION_ID/[email protected]&limit=20&offset=0" \
-H "X-API-Key: $API_KEY"
```
@@ -221,7 +227,7 @@ curl "$BASE/api/sessions/my-session/[email protected]&limit=20&o
Fetch chat history live from WhatsApp, bypassing the DB.
```bash
-curl "$BASE/api/sessions/my-session/messages/[email protected]/history?limit=100&deep=true" \
+curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/history?limit=100&deep=true" \
-H "X-API-Key: $API_KEY"
```
@@ -230,7 +236,7 @@ curl "$BASE/api/sessions/my-session/messages/[email protected]/history?limit=100
Get reactions for a message, grouped by emoji.
```bash
-curl "$BASE/api/sessions/my-session/messages/[email protected]/[email protected]_3EB0ABCD/reactions" \
+curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/[email protected]_3EB0ABCD/reactions" \
-H "X-API-Key: $API_KEY"
```
@@ -239,7 +245,7 @@ curl "$BASE/api/sessions/my-session/messages/[email protected]/true_628123456789
Get the status and progress of a bulk batch.
```bash
-curl "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4" \
+curl "$BASE/api/sessions/$SESSION_ID/messages/batch/batch_a1b2c3d4" \
-H "X-API-Key: $API_KEY"
```
@@ -248,7 +254,7 @@ curl "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4" \
Send a plain text message.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-text" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-text" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }'
@@ -259,7 +265,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-text" \
Render a stored template (`{{vars}}` substituted) and send it as text.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-template" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-template" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "templateName": "order-confirmation", "vars": { "customer": "Alice", "orderId": "1234" } }'
@@ -270,7 +276,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-template" \
Send an image by URL or base64 with an optional caption.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-image" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-image" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "url": "https://example.com/image.jpg", "caption": "Check out this image!" }'
@@ -281,7 +287,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-image" \
Send a video by URL or base64 with an optional caption.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-video" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-video" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "url": "https://example.com/clip.mp4", "caption": "video" }'
@@ -292,7 +298,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-video" \
Send an audio message by URL or base64. Add `"ptt": true` to send a real WhatsApp voice note (mic bubble + waveform); the server defaults the mimetype to `audio/ogg; codecs=opus` when `ptt` is set without one.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-audio" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-audio" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "url": "https://example.com/voice.ogg", "mimetype": "audio/ogg", "ptt": true }'
@@ -303,7 +309,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-audio" \
Send a document/file by URL or base64.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-document" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-document" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "url": "https://example.com/report.pdf", "filename": "report.pdf", "mimetype": "application/pdf" }'
@@ -314,7 +320,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-document" \
Send a location pin.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-location" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-location" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "latitude": -6.2088, "longitude": 106.8456, "description": "Jakarta", "address": "Central Jakarta" }'
@@ -325,7 +331,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-location" \
Send a contact card (vCard).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-contact" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-contact" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "contactName": "John Doe", "contactNumber": "628987654321" }'
@@ -336,7 +342,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-contact" \
Send a sticker by URL or base64 (typically webp).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-sticker" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-sticker" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "url": "https://example.com/sticker.webp", "mimetype": "image/webp" }'
@@ -347,7 +353,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-sticker" \
Send a native WhatsApp poll (2–12 options; single choice unless `allowMultipleAnswers` is true).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-poll" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-poll" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "name": "Where should we meet?", "options": ["Park", "Beach", "Downtown"] }'
@@ -358,7 +364,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-poll" \
Reply to a message, quoting a prior one.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/reply" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/reply" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "quotedMessageId": "[email protected]_3EB0ABCD", "text": "Replying to you" }'
@@ -369,7 +375,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/reply" \
Forward a message from one chat to another.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/forward" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/forward" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "fromChatId": "[email protected]", "toChatId": "[email protected]", "messageId": "[email protected]_3EB0XYZ" }'
@@ -380,7 +386,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/forward" \
Add a reaction (send an empty `emoji` to remove it).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/react" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/react" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "emoji": "👍" }'
@@ -391,7 +397,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/react" \
Delete a message (for everyone by default).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/delete" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/delete" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "forEveryone": true }'
@@ -399,10 +405,10 @@ curl -X POST "$BASE/api/sessions/my-session/messages/delete" \
#### POST /api/sessions/:sessionId/messages/send-bulk
-Send to multiple recipients as an async batch (max 100 messages; duplicate `chatId`s are collapsed — first occurrence wins).
+Send to multiple recipients as an async batch (max 100 messages; exact duplicate entries — same `chatId`, `type`, `content` and `variables` — are collapsed, first occurrence wins).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-bulk" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-bulk" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
@@ -419,7 +425,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-bulk" \
Cancel a running bulk batch (no body).
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4/cancel" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/batch/batch_a1b2c3d4/cancel" \
-H "X-API-Key: $API_KEY"
```
@@ -430,7 +436,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/batch/batch_a1b2c3d4/cancel
List contacts for a session (paginated window).
```bash
-curl -X GET "$BASE/api/sessions/main/contacts?limit=100&offset=0" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts?limit=100&offset=0" \
-H "X-API-Key: $API_KEY"
```
@@ -439,7 +445,7 @@ curl -X GET "$BASE/api/sessions/main/contacts?limit=100&offset=0" \
Check whether a phone number is on WhatsApp.
```bash
-curl -X GET "$BASE/api/sessions/main/contacts/check/628123456789" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/check/628123456789" \
-H "X-API-Key: $API_KEY"
```
@@ -448,7 +454,7 @@ curl -X GET "$BASE/api/sessions/main/contacts/check/628123456789" \
Get a single contact by its WhatsApp id.
```bash
-curl -X GET "$BASE/api/sessions/main/contacts/[email protected]" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]" \
-H "X-API-Key: $API_KEY"
```
@@ -457,7 +463,7 @@ curl -X GET "$BASE/api/sessions/main/contacts/[email protected]" \
Get a contact's profile picture URL.
```bash
-curl -X GET "$BASE/api/sessions/main/contacts/[email protected]/profile-picture" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]/profile-picture" \
-H "X-API-Key: $API_KEY"
```
@@ -466,7 +472,7 @@ curl -X GET "$BASE/api/sessions/main/contacts/[email protected]/profile-picture
Resolve a contact id (e.g. an @lid) to a phone number.
```bash
-curl -X GET "$BASE/api/sessions/main/contacts/12345678901234@lid/phone" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/12345678901234@lid/phone" \
-H "X-API-Key: $API_KEY"
```
@@ -475,7 +481,7 @@ curl -X GET "$BASE/api/sessions/main/contacts/12345678901234@lid/phone" \
Block a contact (requires an OPERATOR key). Send an empty body.
```bash
-curl -X POST "$BASE/api/sessions/main/contacts/[email protected]/block" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]/block" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{}'
@@ -486,7 +492,7 @@ curl -X POST "$BASE/api/sessions/main/contacts/[email protected]/block" \
Unblock a contact (requires an OPERATOR key).
```bash
-curl -X DELETE "$BASE/api/sessions/main/contacts/[email protected]/block" \
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]/block" \
-H "X-API-Key: $API_KEY"
```
@@ -497,7 +503,7 @@ curl -X DELETE "$BASE/api/sessions/main/contacts/[email protected]/block" \
List all groups for a session (paginated).
```bash
-curl -X GET "$BASE/api/sessions/my-session/groups?limit=1000&offset=0" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/groups?limit=1000&offset=0" \
-H "X-API-Key: $API_KEY"
```
@@ -506,7 +512,7 @@ curl -X GET "$BASE/api/sessions/my-session/groups?limit=1000&offset=0" \
Get detailed group info including participants.
```bash
-curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/groups/[email protected]" \
-H "X-API-Key: $API_KEY"
```
@@ -515,7 +521,7 @@ curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]" \
Get the group invite code and full invite link.
```bash
-curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]/invite-code" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/invite-code" \
-H "X-API-Key: $API_KEY"
```
@@ -524,7 +530,7 @@ curl -X GET "$BASE/api/sessions/my-session/groups/[email protected]/invite
Create a new group with an initial set of participants (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "Project Team", "participants": ["[email protected]", "[email protected]"] }'
@@ -535,7 +541,7 @@ curl -X POST "$BASE/api/sessions/my-session/groups" \
Add participants to a group (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/participants" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "participants": ["[email protected]"] }'
@@ -546,7 +552,7 @@ curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/parti
Remove participants from a group (OPERATOR). This DELETE takes a JSON body.
```bash
-curl -X DELETE "$BASE/api/sessions/my-session/groups/[email protected]/participants" \
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/participants" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "participants": ["[email protected]"] }'
@@ -557,7 +563,7 @@ curl -X DELETE "$BASE/api/sessions/my-session/groups/[email protected]/par
Promote participants to group admin (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants/promote" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/participants/promote" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "participants": ["[email protected]"] }'
@@ -568,7 +574,7 @@ curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/parti
Demote participants from group admin (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/participants/demote" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/participants/demote" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "participants": ["[email protected]"] }'
@@ -579,7 +585,7 @@ curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/parti
Change the group name/subject (OPERATOR).
```bash
-curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/subject" \
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/subject" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "subject": "New Team Name" }'
@@ -590,7 +596,7 @@ curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/subjec
Change the group description; an empty string clears it (OPERATOR).
```bash
-curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/description" \
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/description" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "description": "Internal coordination group." }'
@@ -601,7 +607,7 @@ curl -X PUT "$BASE/api/sessions/my-session/groups/[email protected]/descri
Leave a group (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/leave" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/leave" \
-H "X-API-Key: $API_KEY"
```
@@ -610,7 +616,7 @@ curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/leave
Revoke the current invite code and generate a new one (OPERATOR).
```bash
-curl -X POST "$BASE/api/sessions/my-session/groups/[email protected]/invite-code/revoke" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/invite-code/revoke" \
-H "X-API-Key: $API_KEY"
```
@@ -677,39 +683,41 @@ curl -X DELETE "$BASE/api/sessions/$SESSION_ID/templates/$TEMPLATE_ID" \
### 07.8 Catalog & Channels
+The five catalog routes are registered but **no engine implements them**: both whatsapp-web.js and Baileys raise `EngineNotSupportedError`, so each of them returns `501 Not Implemented` once the session is READY. On whatsapp-web.js the readiness check runs first, so a session that exists but is not yet READY returns `409` instead; Baileys raises the unsupported error unconditionally. They are listed for route completeness only. The channel routes that follow are a separate group with real engine support — the per-engine gaps are listed in `docs/29-engine-capability-matrix.md`.
+
#### GET /api/sessions/:sessionId/catalog
-Get business catalog info for the session.
+Get business catalog info for the session. Returns `501` on both engines.
```bash
-curl -X GET "$BASE/api/sessions/my-session/catalog" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog" \
-H "X-API-Key: $API_KEY"
```
#### GET /api/sessions/:sessionId/catalog/products
-List catalog products with pagination.
+List catalog products with pagination. Returns `501` on both engines.
```bash
-curl -X GET "$BASE/api/sessions/my-session/catalog/products?page=1&limit=20" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products?page=1&limit=20" \
-H "X-API-Key: $API_KEY"
```
#### GET /api/sessions/:sessionId/catalog/products/:productId
-Get a specific catalog product by id (unknown id returns 200 with `null`).
+Get a specific catalog product by id. Returns `501` on both engines, whatever the id.
```bash
-curl -X GET "$BASE/api/sessions/my-session/catalog/products/PROD_12345" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products/PROD_12345" \
-H "X-API-Key: $API_KEY"
```
#### POST /api/sessions/:sessionId/messages/send-product
-Send a product card to a chat (OPERATOR key required).
+Send a product card to a chat (OPERATOR key required). Returns `501` on both engines.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-product" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-product" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "productId": "PROD_12345", "body": "Check out this item!" }'
@@ -717,10 +725,10 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-product" \
#### POST /api/sessions/:sessionId/messages/send-catalog
-Send the business catalog link to a chat (OPERATOR key required).
+Send the business catalog link to a chat (OPERATOR key required). Returns `501` on both engines.
```bash
-curl -X POST "$BASE/api/sessions/my-session/messages/send-catalog" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-catalog" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "chatId": "[email protected]", "body": "Browse our full catalog here" }'
@@ -731,7 +739,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-catalog" \
List subscribed channels/newsletters.
```bash
-curl -X GET "$BASE/api/sessions/my-session/channels" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/channels" \
-H "X-API-Key: $API_KEY"
```
@@ -740,7 +748,7 @@ curl -X GET "$BASE/api/sessions/my-session/channels" \
Get a single channel by id.
```bash
-curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/channels/120363000000000000@newsletter" \
-H "X-API-Key: $API_KEY"
```
@@ -749,7 +757,7 @@ curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newslette
Get recent messages from a channel.
```bash
-curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter/messages?limit=50" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/channels/120363000000000000@newsletter/messages?limit=50" \
-H "X-API-Key: $API_KEY"
```
@@ -758,7 +766,7 @@ curl -X GET "$BASE/api/sessions/my-session/channels/120363000000000000@newslette
Subscribe to a channel by invite code (OPERATOR key required).
```bash
-curl -X POST "$BASE/api/sessions/my-session/channels/subscribe" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/channels/subscribe" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "inviteCode": "ABC123xyz" }'
@@ -769,7 +777,7 @@ curl -X POST "$BASE/api/sessions/my-session/channels/subscribe" \
Unsubscribe from a channel (OPERATOR key required).
```bash
-curl -X DELETE "$BASE/api/sessions/my-session/channels/120363000000000000@newsletter" \
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/channels/120363000000000000@newsletter" \
-H "X-API-Key: $API_KEY"
```
@@ -858,7 +866,7 @@ All routes require an API key with OPERATOR role or higher. `secret` and `header
List all webhooks for a session (newest first).
```bash
-curl -X GET "$BASE/api/sessions/my-session/webhooks" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/webhooks" \
-H "X-API-Key: $API_KEY"
```
@@ -867,7 +875,7 @@ curl -X GET "$BASE/api/sessions/my-session/webhooks" \
Get a single webhook by ID, scoped to the session.
```bash
-curl -X GET "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+curl -X GET "$BASE/api/sessions/$SESSION_ID/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
-H "X-API-Key: $API_KEY"
```
@@ -885,7 +893,7 @@ curl -X GET "$BASE/api/webhooks?limit=100&offset=0" \
Create a webhook for the session.
```bash
-curl -X POST "$BASE/api/sessions/my-session/webhooks" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/webhooks" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
@@ -908,7 +916,7 @@ curl -X POST "$BASE/api/sessions/my-session/webhooks" \
Update a webhook (partial; only provided fields change).
```bash
-curl -X PUT "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
@@ -924,7 +932,7 @@ curl -X PUT "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-5678
Send a synthetic test payload to the webhook URL and report the result (no request body).
```bash
-curl -X POST "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef/test" \
+curl -X POST "$BASE/api/sessions/$SESSION_ID/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef/test" \
-H "X-API-Key: $API_KEY"
```
@@ -933,7 +941,7 @@ curl -X POST "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567
Delete a webhook (returns `204` no content).
```bash
-curl -X DELETE "$BASE/api/sessions/my-session/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/webhooks/f1e2d3c4-b5a6-7890-1234-567890abcdef" \
-H "X-API-Key: $API_KEY"
```
@@ -1074,7 +1082,7 @@ curl "$BASE/api/stats/messages?period=7d" \
#### GET /api/stats/sessions/:sessionId
-Per-session stats. Any valid API key (not session-scoped).
+Per-session stats. Any role; a session-restricted key can only read stats for its allowed sessions.
```bash
curl "$BASE/api/stats/sessions/9f1c2d3e-…" \
@@ -1327,10 +1335,10 @@ curl -X PUT "$BASE/api/plugins/chat-flow/config" \
#### PUT /api/plugins/:id/config/:sessionId
-Set (or clear with `{}`) a per-session plugin config override.
+Set (or clear with `{}`) a per-session plugin config override. The override is stored under the session UUID and resolved against the UUID carried by each event, so an id that is not a live session's UUID never takes effect.
```bash
-curl -X PUT "$BASE/api/plugins/chat-flow/config/session-1" \
+curl -X PUT "$BASE/api/plugins/chat-flow/config/$SESSION_ID" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{ "config": { "replyDelayMs": 3000 } }'
@@ -1369,7 +1377,7 @@ curl -X DELETE "$BASE/api/plugins/chat-flow" \
#### POST /mcp
-MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer`; auth is enforced per tool call. See doc 24 for the tool catalog.
+MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer`; auth is enforced per tool call. The server is **read-only by default** — write tools such as `MessageSendText` are only mounted when `MCP_READONLY=false`. See doc 24 for the tool catalog.
```bash
# Initialize handshake
@@ -1384,11 +1392,11 @@ curl -X POST "$BASE/mcp" \
-H "Content-Type: application/json" \
-d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }'
-# Call a tool (arguments must match the tool's zod inputSchema)
+# Call a tool (arguments must match the tool's zod inputSchema; requires MCP_READONLY=false)
curl -X POST "$BASE/mcp" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
- -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "session_send_text", "arguments": { "sessionId": "default", "to": "6281234567890", "text": "Hello from MCP" } } }'
+ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "MessageSendText", "arguments": { "sessionId": "'"$SESSION_ID"'", "chatId": "[email protected]", "text": "Hello from MCP" } } }'
```
### 07.14 Real-time (WebSocket)
@@ -1400,15 +1408,15 @@ npm install socket.io-client
```
```js
-// realtime.mjs — run: BASE_WS=ws://localhost:2785 API_KEY=... SESSION_ID=main node realtime.mjs
+// realtime.mjs — run: BASE_WS=ws://localhost:2785 API_KEY=... SESSION_ID=<session-uuid> node realtime.mjs
import { io } from 'socket.io-client';
const BASE_WS = process.env.BASE_WS || 'ws://localhost:2785';
const API_KEY = process.env.API_KEY;
-const SESSION_ID = process.env.SESSION_ID || 'main';
+const SESSION_ID = process.env.SESSION_ID; // the session UUID, or '*' (unrestricted keys only)
const socket = io(`${BASE_WS}/events`, {
- auth: { apiKey: API_KEY }, // or transport.headers / ?apiKey=
+ auth: { apiKey: API_KEY }, // or the x-api-key header
});
socket.on('connect', () => {
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.md
index afa0675f2..572c6dc05 100644
--- a/docs/08-development-guidelines.md
+++ b/docs/08-development-guidelines.md
@@ -16,7 +16,7 @@ openwa/
│ └── plugins/ # Built-in engine and extension plugins
├── test/ # E2E smoke tests and mocks
├── dashboard/ # React/Vite dashboard
-├── sdk/ # JavaScript and Python SDK scaffolds
+├── sdk/ # Client SDKs: go, java, javascript, php, python
├── docs/ # Documentation
├── scripts/ # Utility scripts
├── .github/workflows/ # CI and release workflows
@@ -35,36 +35,37 @@ openwa/
### TypeScript Configuration
```json
-// tsconfig.json
+// tsconfig.json (abridged — see the file for the commented rationale)
{
"compilerOptions": {
- "module": "commonjs",
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "target": "ES2023",
+ "rootDir": ".",
+ "outDir": "./dist",
+ "types": ["node", "jest"],
"declaration": true,
- "removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
- "allowSyntheticDefaultImports": true,
- "target": "ES2022",
- "sourceMap": true,
- "outDir": "./dist",
- "baseUrl": "./",
- "incremental": true,
- "skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": true,
"strictBindCallApply": true,
- "forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
- "paths": {
- "@/*": ["src/*"],
- "@common/*": ["src/common/*"],
- "@modules/*": ["src/modules/*"],
- "@config/*": ["src/config/*"]
- }
- }
+ "strictPropertyInitialization": false,
+ "strictFunctionTypes": false,
+ "useUnknownInCatchVariables": false
+ },
+ "include": ["src", "test"],
+ "exclude": ["node_modules", "dist", "dashboard"]
}
```
+There are **no path aliases** — no `baseUrl`, no `paths`. Import with relative paths
+(`../common/services/logger.service`), not `@/…`. Under TypeScript 6 the strict family defaults on,
+so the three `false` entries above are deliberate opt-outs pending their own migrations
+(`strictPropertyInitialization` alone flags around 260 TypeORM entity properties). `types` must be
+listed explicitly because TypeScript 6 no longer auto-includes every `@types` package.
+
### ESLint Configuration
The backend uses ESLint flat config in `eslint.config.mjs` with type-aware TypeScript rules,
@@ -210,7 +211,7 @@ import { Example } from './entities/example.entity';
@Injectable()
export class ExampleService {
- private readonly logger = new Logger(ExampleService.name);
+ private readonly logger = createLogger('ExampleService');
constructor(private readonly repository: ExampleRepository) {}
@@ -524,70 +525,37 @@ export class SessionController {
## 8.7 Error Handling
-### Custom Exception Classes
+There is **no custom exception base class and no global exception filter**. Handlers throw NestJS's
+built-in HTTP exceptions and NestJS's own `BaseExceptionFilter` renders them, so responses carry the
+framework default shape `{ statusCode, message, error }`.
```typescript
-// common/exceptions/business.exception.ts
-export class BusinessException extends HttpException {
- constructor(
- public readonly code: string,
- message: string,
- statusCode: HttpStatus = HttpStatus.BAD_REQUEST,
- public readonly details?: Record<string, any>,
- ) {
- super({ code, message, details }, statusCode);
- }
-}
-
-// Usage
-throw new BusinessException(
- 'SESSION_NOT_READY',
- 'Session is not ready to send messages',
- HttpStatus.BAD_REQUEST,
- { sessionId, currentStatus: session.status }
-);
+throw new BadRequestException('Session is not started');
+throw new NotFoundException(`Contact ${contactId} not found`);
```
-### Global Exception Filter
-
-```typescript
-// common/filters/http-exception.filter.ts
-@Catch()
-export class AllExceptionsFilter implements ExceptionFilter {
- private readonly logger = new Logger(AllExceptionsFilter.name);
+### Domain errors extend a built-in exception
- catch(exception: unknown, host: ArgumentsHost): void {
- const ctx = host.switchToHttp();
- const response = ctx.getResponse<Response>();
- const request = ctx.getRequest<Request>();
+Where a failure mode recurs across engines, `src/common/errors/` defines a named error that extends
+the NestJS exception carrying the right status, so throwing it from an adapter maps to the intended
+HTTP code with no filter involved:
- const status = exception instanceof HttpException
- ? exception.getStatus()
- : HttpStatus.INTERNAL_SERVER_ERROR;
+| 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 |
- const errorResponse = this.formatError(exception, request);
+Add a new one only when the condition is engine-agnostic and recurs; a one-off stays an inline
+`throw new BadRequestException(...)`.
- this.logger.error(
- `${request.method} ${request.url} - ${status}`,
- exception instanceof Error ? exception.stack : undefined,
- );
-
- response.status(status).json(errorResponse);
- }
-
- private formatError(exception: unknown, request: Request) {
- const status = exception instanceof HttpException
- ? exception.getStatus()
- : HttpStatus.INTERNAL_SERVER_ERROR;
- // Return NestJS default error shape: { statusCode, message, error }
- return {
- statusCode: status,
- message: this.getErrorMessage(exception),
- error: this.getErrorCode(exception),
- };
- }
-}
-```
+> Do not introduce a response envelope. A `ResponseInterceptor`/`HttpExceptionFilter` pair that
+> wrapped every payload in `{ success, data, meta }` was written once, never registered, and has
+> since been deleted — `dashboard/src/services/api.ts` reads the raw payload.
---
@@ -799,13 +767,14 @@ ENABLE_SWAGGER=false
```typescript
// Use Logger from NestJS
-import { Logger, Inject, Scope } from '@nestjs/common';
+import { Inject, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
+import { createLogger } from '../common/services/logger.service';
@Injectable({ scope: Scope.REQUEST })
export class MyService {
- private readonly logger = new Logger(MyService.name);
+ private readonly logger = createLogger('MyService');
constructor(@Inject(REQUEST) private readonly request: Request) {}
@@ -894,17 +863,21 @@ npm test -- session.service.spec.ts
# Run tests with verbose output
npm test -- --verbose
-# Check for TypeScript errors
-npm run build -- --noEmit
+# Check for TypeScript errors without emitting (the Nest CLI has no --noEmit; call tsc directly).
+# Use the root tsconfig, not tsconfig.build.json — it is the only one that also type-checks the
+# colocated *.spec.ts files, which is what CI gates on.
+npx tsc --noEmit -p tsconfig.json
# Lint with auto-fix
npm run lint -- --fix
-# Debug database queries (TypeORM)
-# Add to .env: DEBUG=typeorm:query
+# Debug database queries (TypeORM) — add to .env:
+# DATABASE_LOGGING=true
+# (there is no DEBUG=typeorm:query switch; both connections read DATABASE_LOGGING)
-# View Docker logs
-docker compose logs -f app
+# View Docker logs (service is `openwa-api` in docker-compose.yml, `openwa` in
+# docker-compose.dev.yml — there is no service named `app`)
+docker compose logs -f openwa-api
```
## 8.10 Performance Best Practices
@@ -981,7 +954,7 @@ const results = await Promise.all(
// Bound teardown so one stuck browser/socket cannot block shutdown.
@Injectable()
export class EngineTeardownService {
- private readonly logger = new Logger(EngineTeardownService.name);
+ private readonly logger = createLogger('EngineTeardownService');
async destroyWithTimeout(sessionId: string, engine: IWhatsAppEngine): Promise<void> {
const timeout = new Promise<never>((_, reject) => {
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 32cdb32bc..84ef4b179 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -39,20 +39,28 @@ npm --prefix dashboard run test:unit
| `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 build && npm run smoke` | Test and package-smoke the JavaScript SDK |
+| `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 && go vet ./... && go test -race ./...` | Vet and race-test the Go SDK |
+| `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
@@ -118,15 +126,19 @@ E2E smoke tests live in `test/` and use `test/jest-e2e.json`.
```text
test/
+├── __mocks__/
+├── fixtures/
├── app.e2e-spec.ts
├── baileys-engine.e2e-spec.ts
├── ingress-instance-throttle.e2e-spec.ts
├── integration-fabric.e2e-spec.ts
├── integration-instance.e2e-spec.ts
├── mcp-auth.e2e-spec.ts
+├── queue-on.e2e-spec.ts
├── search.e2e-spec.ts
├── serve-static.e2e-spec.ts
├── session-scope.e2e-spec.ts
+├── setup-e2e-env.e2e-spec.ts
├── webhooks.e2e-spec.ts
├── jest-e2e.json
└── setup-e2e.ts
@@ -170,9 +182,9 @@ Main CI is defined in `.github/workflows/ci.yml`.
| Job | Checks |
| --------------- | ----------------------------------------------------------------------------------------------- |
-| `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, OpenAPI snapshot |
+| `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, .dockerignore context, OpenAPI snapshot |
| `audit` | dependency security audit |
-| `test` | backend coverage run, e2e smoke tests, Codecov upload |
+| `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 |
@@ -180,9 +192,11 @@ Main CI is defined in `.github/workflows/ci.yml`.
| `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 server
-contract surfaces that SDKs mirror (`src/**/dto/**` and the engine interface). It runs:
+contract surfaces that SDKs mirror (`src/**/dto/**`, `src/**/*.controller.ts`, `src/**/*.service.ts`, and
+`src/engine/interfaces/whatsapp-engine.interface.ts`), so any backend controller or service change also
+re-runs the SDK suites. It runs:
-- JavaScript SDK tests, build, and dual CJS/ESM smoke test.
+- JavaScript SDK tests, type-check, build, and dual CJS/ESM smoke test.
- Python SDK tests with `pytest`.
- PHP SDK tests with PHPUnit.
- Java SDK tests with Maven.
@@ -261,14 +275,18 @@ Live WhatsApp checks require an operator-owned account and should not be part of
## 9.9 Known Gaps
- No default CI job exercises a real WhatsApp connection.
-- The default `test` job uses SQLite; a dedicated `test-postgres` CI job exercises PostgreSQL 16.
-- No default CI job exercises real Redis, S3/MinIO, or Docker socket proxy integration.
+- The default `test` job uses SQLite; PostgreSQL 16 is only exercised by the dedicated `test-postgres` job.
+- No default CI job exercises S3/MinIO or Docker socket proxy integration. (Redis is no longer a gap: the
+ `test` job starts a `redis:7-alpine` service container so the queue-on e2e suite has a broker. That suite
+ skips itself when no Redis is reachable, so it stays green on a machine without one.)
- Performance testing is not automated.
- Dashboard browser/visual UI tests are not currently automated; dashboard pure utility tests run via `npm --prefix dashboard run test:unit`.
-These gaps are intentional for the default suite because the project prioritizes deterministic tests that
-run without external services. Add opt-in integration jobs only when they are isolated, documented, and do
-not make normal contributor workflows brittle.
+These gaps are intentional because the project prioritizes deterministic tests: no job needs an
+operator-owned WhatsApp account, cloud credentials, or a Docker socket, and neither service container CI
+starts is required locally — `npm test` and `npm run test:e2e` stay on SQLite with the queue disabled. Add
+opt-in integration jobs only when they are isolated, documented, and do not make normal contributor
+workflows brittle.
---
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 34527e258..68a4c8171 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -9,28 +9,30 @@
## 10.1 Infrastructure Overview
+OpenWA is a **single-process** application, so a deployment is exactly one app instance per
+session-data volume (`replicas: 1` — see §10.2). The repo has no staging/production environments and
+no auto-deploy: CI builds and publishes images, and pulling one onto a server is the operator's step.
+
```mermaid
flowchart TB
subgraph Development["Development"]
DEV[Local Docker Compose]
end
- subgraph Staging["Staging"]
- STG[Single Server]
+ subgraph Registry["Container Registry"]
+ GHCR["GHCR branch / SHA / release tags"]
end
- subgraph Production["Production"]
- LB[Load Balancer]
- LB --> APP1[App Instance 1]
- LB --> APP2[App Instance 2]
- APP1 --> DB[(PostgreSQL)]
- APP2 --> DB
- APP1 --> REDIS[(Redis)]
- APP2 --> REDIS
+ subgraph Deployment["Deployment (single server)"]
+ PROXY[Reverse Proxy]
+ PROXY --> APP[OpenWA - one instance]
+ APP --> DB[(PostgreSQL or SQLite)]
+ APP --> REDIS[(Redis - optional)]
+ APP --> VOL["Data volume (/app/data)"]
end
- DEV --> |deploy| STG
- STG --> |promote| Production
+ DEV --> |CI builds and pushes| GHCR
+ GHCR --> |operator pulls| Deployment
```
## 10.2 Docker Configuration
@@ -41,7 +43,7 @@ flowchart TB
# Dockerfile (multi-stage build)
# Build stage
-FROM node:22-slim AS build
+FROM node:22-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
@@ -119,15 +121,21 @@ CMD ["node", "dist/main.js"]
### Docker Compose (Development)
+The repo's own `docker-compose.dev.yml` is a single-container local smoke test that runs the
+**production** image against a bind-mounted `./data` — it has no source mount and no `start:dev`.
+The multi-service file below is a hypothetical hot-reload variant you would write yourself under a
+different name (writing it to `docker-compose.dev.yml` would overwrite the shipped file); the
+`builder` target is the first stage of the repo `Dockerfile`.
+
```yaml
-# docker-compose.yml
+# docker-compose.hotreload.yml (write this yourself; not shipped in the repo)
version: '3.8'
services:
app:
build:
context: .
- target: build
+ target: builder
command: npm run start:dev
ports:
- "2785:2785"
@@ -145,10 +153,15 @@ services:
# The env var is API_MASTER_KEY (not API_KEY_MASTER); never hardcode a key — set a
# strong secret. Production refuses to boot with a placeholder/default.
- API_MASTER_KEY=
+ # Without this, plugins fall back to ./plugins (outside the data volume) and are lost
+ # when the container is replaced. The shipped compose sets it for the same reason.
+ - PLUGINS_DIR=/app/data/plugins
volumes:
- ./:/app
- /app/node_modules
- - session-data:/app/.wwebjs_auth
+ # Everything the app writes locally (session auth, the main (auth/audit) SQLite DB, media,
+ # plugins) lives under /app/data; with DATABASE_TYPE=postgres above, the data DB does not
+ - openwa-data:/app/data
depends_on:
- postgres
- redis
@@ -178,13 +191,21 @@ services:
volumes:
postgres-data:
redis-data:
- session-data:
+ openwa-data:
```
### Docker Compose (Production)
+The repo ships `docker-compose.yml` (full stack, builds the image from source) and
+`docker-compose.dev.yml` (local smoke test). The file below is an image-based variant you would
+write yourself for a release deployment; it mirrors the shipped compose in the part that matters —
+the single `/app/data` volume that holds session auth, the main (auth/audit) SQLite DB, media and
+plugins. Note the example below sets `DATABASE_TYPE=postgres`, so the **data** database lives in
+PostgreSQL and needs its own backup; only with the SQLite default (what the shipped
+`docker-compose.yml` leaves in place) does the data DB sit in this volume too.
+
```yaml
-# docker-compose.prod.yml
+# docker-compose.release.yml (write this yourself; not shipped in the repo)
version: '3.8'
services:
@@ -211,8 +232,13 @@ services:
- REDIS_HOST=${REDIS_HOST}
- REDIS_PORT=${REDIS_PORT}
- API_MASTER_KEY=${API_MASTER_KEY}
+ # Without this, plugins fall back to ./plugins (outside the data volume) and are lost
+ # when the container is replaced. The shipped compose sets it for the same reason.
+ - PLUGINS_DIR=/app/data/plugins
volumes:
- - session-data:/app/.wwebjs_auth
+ # Session auth, the main (auth/audit) SQLite DB, media and plugins all live here — losing
+ # this volume loses the linked WhatsApp sessions and the API keys.
+ - openwa-data:/app/data
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:2785/api/health/ready"]
interval: 30s
@@ -233,7 +259,7 @@ services:
restart: always
volumes:
- session-data:
+ openwa-data:
driver: local
```
@@ -250,146 +276,24 @@ volumes:
### GitHub Actions Workflow
-```yaml
-# .github/workflows/ci.yml
-name: CI/CD Pipeline
-
-on:
- push:
- branches: [main, develop]
- pull_request:
- branches: [main]
-
-env:
- REGISTRY: ghcr.io
- IMAGE_NAME: ${{ github.repository }}
-
-jobs:
- test:
- runs-on: ubuntu-latest
-
- services:
- postgres:
- image: postgres:16
- env:
- POSTGRES_USER: test
- POSTGRES_PASSWORD: test
- POSTGRES_DB: test
- ports:
- - 5432:5432
- options: >-
- --health-cmd pg_isready
- --health-interval 10s
- --health-timeout 5s
- --health-retries 5
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '22'
- cache: 'npm'
-
- - name: Install dependencies
- run: npm ci
-
- - name: Run linter
- run: npm run lint
-
- - name: Run tests
- run: npm run test:cov
- env:
- DATABASE_TYPE: postgres
- DATABASE_HOST: localhost
- DATABASE_PORT: '5432'
- DATABASE_USERNAME: test
- DATABASE_PASSWORD: test
- DATABASE_NAME: test
-
- - name: Upload coverage
- uses: codecov/codecov-action@v3
- with:
- files: ./coverage/lcov.info
-
- build:
- needs: test
- runs-on: ubuntu-latest
- if: github.event_name == 'push'
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v3
-
- - name: Login to Container Registry
- uses: docker/login-action@v3
- with:
- registry: ${{ env.REGISTRY }}
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
-
- - name: Extract metadata
- id: meta
- uses: docker/metadata-action@v5
- with:
- images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- tags: |
- type=ref,event=branch
- type=sha,prefix=
- type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
-
- - name: Build and push
- uses: docker/build-push-action@v5
- with:
- context: .
- push: true
- platforms: linux/amd64,linux/arm64
- tags: ${{ steps.meta.outputs.tags }}
- labels: ${{ steps.meta.outputs.labels }}
- cache-from: type=gha
- cache-to: type=gha,mode=max
-
- deploy-staging:
- needs: build
- runs-on: ubuntu-latest
- if: github.ref == 'refs/heads/develop'
- environment: staging
-
- steps:
- - name: Deploy to Staging
- uses: appleboy/ssh-action@v1
- with:
- host: ${{ secrets.STAGING_HOST }}
- username: ${{ secrets.STAGING_USER }}
- key: ${{ secrets.STAGING_SSH_KEY }}
- script: |
- cd /opt/openwa
- docker compose pull
- docker compose up -d
- docker system prune -f
-
- deploy-production:
- needs: build
- runs-on: ubuntu-latest
- if: github.ref == 'refs/heads/main'
- environment: production
-
- steps:
- - name: Deploy to Production
- uses: appleboy/ssh-action@v1
- with:
- host: ${{ secrets.PROD_HOST }}
- username: ${{ secrets.PROD_USER }}
- key: ${{ secrets.PROD_SSH_KEY }}
- script: |
- cd /opt/openwa
- docker compose -f docker-compose.prod.yml pull
- docker compose -f docker-compose.prod.yml up -d --no-deps app
- docker system prune -f
-```
+`.github/workflows/ci.yml` (`name: CI`) runs on pushes and pull requests targeting `main` /
+`develop`. It is **integration only** — no job deploys anywhere. The final job publishes branch and
+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) |
+
+Rollout is left to the operator — the repo has no SSH deploy step, no staging/production
+environments and no auto-deploy on merge.
## 10.4 Deployment Architecture
@@ -451,14 +355,15 @@ flowchart TB
### Environment Variables
```bash
-# .env.example
+# .env — excerpt of the commonly-tuned keys. The repo's `.env.example` is the canonical,
+# fully annotated list; add nothing here that does not appear there.
# ===========================================
# APPLICATION
# ===========================================
NODE_ENV=production
PORT=2785
-API_PREFIX=/api
+# The global `/api` prefix is fixed in code — there is no env var for it.
LOG_LEVEL=info
LOG_FORMAT=json
@@ -483,47 +388,48 @@ DATABASE_NAME=./data/openwa.sqlite
# ===========================================
# MEDIA STORAGE (choose one)
# ===========================================
+# STORAGE_TYPE accepts only `local` or `s3` — env validation rejects anything else and the app
+# FAILS TO BOOT ("Invalid environment configuration"). There is no silent fallback to local disk.
# Option 1: Local filesystem (default)
STORAGE_TYPE=local
-STORAGE_LOCAL_PATH=./media
-STORAGE_LOCAL_BASE_URL=/media
+STORAGE_LOCAL_PATH=./data/media
-# Option 2: S3
+# Option 2: S3 (AWS) — leave S3_ENDPOINT unset; the SDK derives it from the region
# STORAGE_TYPE=s3
-# STORAGE_S3_BUCKET=openwa-media
-# STORAGE_S3_REGION=ap-southeast-1
-# STORAGE_S3_ACCESS_KEY_ID=your-access-key
-# STORAGE_S3_SECRET_ACCESS_KEY=your-secret-key
-
-# Option 3: MinIO (S3-compatible)
-# STORAGE_TYPE=minio
-# STORAGE_S3_BUCKET=openwa-media
-# STORAGE_S3_ENDPOINT=http://minio:9000
-# STORAGE_S3_ACCESS_KEY_ID=minioadmin
-# STORAGE_S3_SECRET_ACCESS_KEY=minioadmin
-# STORAGE_S3_FORCE_PATH_STYLE=true
+# S3_BUCKET=openwa
+# S3_REGION=ap-southeast-1
+# S3_ACCESS_KEY_ID=your-access-key
+# S3_SECRET_ACCESS_KEY=your-secret-key
+
+# Option 3: MinIO / other S3-compatible store — same STORAGE_TYPE=s3 plus an endpoint.
+# Setting S3_ENDPOINT is what enables path-style addressing; there is no separate flag.
+# STORAGE_TYPE=s3
+# S3_ENDPOINT=http://minio:9000
+# S3_BUCKET=openwa
+# S3_ACCESS_KEY_ID=minioadmin
+# S3_SECRET_ACCESS_KEY=minioadmin
# ===========================================
-# CACHE & QUEUE (choose one)
+# CACHE & QUEUE
# ===========================================
-# Option 1: In-Memory (for single instance)
-CACHE_TYPE=memory
-CACHE_TTL=300
-CACHE_MAX=1000
-
-# Option 2: Redis (for multi-instance / production)
-# CACHE_TYPE=redis
-# REDIS_URL=redis://localhost:6379
+# Both are opt-in and both need a reachable Redis, configured with the discrete host/port pair
+# (there is no REDIS_URL). Defaults: no cache at all (CacheService is a no-op and every read falls
+# through to the database — there is no in-memory tier) and inline (non-queued) dispatch.
+REDIS_ENABLED=false
+REDIS_HOST=localhost
+REDIS_PORT=6379
+# Redis-backed caching switches on when REDIS_ENABLED=true OR CACHE_ENABLED=true — enabling Redis
+# for the queue alone therefore also enables the cache.
+# CACHE_ENABLED=true
+# QUEUE_ENABLED=true # process webhooks/ingress through the BullMQ queue
# ===========================================
# WHATSAPP ENGINE
# ===========================================
-ENGINE_TYPE=whatsapp-web.js
-# ENGINE_TYPE=baileys
# ENGINE_TYPE=baileys # whatsapp-web.js (default) | baileys; omit to use the dashboard selection
# Session
-SESSION_DATA_PATH=./.wwebjs_auth
+SESSION_DATA_PATH=./data/sessions
# Puppeteer (for whatsapp-web.js)
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
@@ -560,7 +466,7 @@ RATE_LIMIT_MEDIUM_LIMIT=100
```typescript
// config/configuration.ts (shape abbreviated — see src/config/configuration.ts for the real file)
export default () => ({
- port: parseInt(process.env.PORT, 10) || 3000,
+ port: parseInt(process.env.PORT || '2785', 10),
// Main boot DB: always SQLite (auth/audit)
database: {
type: 'sqlite',
@@ -583,11 +489,24 @@ export default () => ({
username: process.env.REDIS_USERNAME,
password: process.env.REDIS_PASSWORD,
},
+ // 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: {
- masterApiKey: process.env.API_MASTER_KEY,
+ trustedProxies: (process.env.TRUSTED_PROXIES || '').split(',').map(proxy => proxy.trim()).filter(Boolean),
},
- session: {
- dataPath: process.env.SESSION_DATA_PATH || './data/sessions',
+ // Session data path and Puppeteer both live under `engine` — there is no top-level
+ // `session` or `puppeteer` key.
+ engine: {
+ type: process.env.ENGINE_TYPE || 'whatsapp-web.js',
+ sessionDataPath: process.env.SESSION_DATA_PATH || './data/sessions',
+ puppeteer: {
+ 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')
+ .split(/[\s,]+/)
+ .filter(Boolean),
+ },
},
webhook: {
timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),
@@ -595,18 +514,16 @@ export default () => ({
dispatchConcurrency: parseInt(process.env.WEBHOOK_DISPATCH_CONCURRENCY || '16', 10),
dispatchMaxQueued: parseInt(process.env.WEBHOOK_DISPATCH_MAX_QUEUED || '1000', 10),
},
- rateLimit: {
- shortTtl: parseInt(process.env.RATE_LIMIT_SHORT_TTL, 10) || 1000,
- shortLimit: parseInt(process.env.RATE_LIMIT_SHORT_LIMIT, 10) || 10,
- mediumTtl: parseInt(process.env.RATE_LIMIT_MEDIUM_TTL, 10) || 60000,
- mediumLimit: parseInt(process.env.RATE_LIMIT_MEDIUM_LIMIT, 10) || 100,
- longTtl: parseInt(process.env.RATE_LIMIT_LONG_TTL, 10) || 3600000,
- longLimit: parseInt(process.env.RATE_LIMIT_LONG_LIMIT, 10) || 1000,
- },
- puppeteer: {
- executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
- headless: process.env.PUPPETEER_HEADLESS !== 'false',
- args: process.env.PUPPETEER_ARGS?.split(',') || [],
+ // Rate limits are nested under `api` — read them as `api.rateLimit.*`
+ api: {
+ rateLimit: {
+ shortTtl: parseInt(process.env.RATE_LIMIT_SHORT_TTL || '1000', 10),
+ shortLimit: parseInt(process.env.RATE_LIMIT_SHORT_LIMIT || '10', 10),
+ mediumTtl: parseInt(process.env.RATE_LIMIT_MEDIUM_TTL || '60000', 10),
+ mediumLimit: parseInt(process.env.RATE_LIMIT_MEDIUM_LIMIT || '100', 10),
+ longTtl: parseInt(process.env.RATE_LIMIT_LONG_TTL || '3600000', 10),
+ longLimit: parseInt(process.env.RATE_LIMIT_LONG_LIMIT || '1000', 10),
+ },
},
});
```
@@ -658,6 +575,8 @@ services:
volumes:
- ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml
- ./monitoring/alerts.yml:/etc/prometheus/alerts.yml
+ # Holds the METRICS_TOKEN value; see the scrape config below
+ - ./monitoring/metrics_token:/etc/prometheus/metrics_token:ro
- prometheus-data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
@@ -751,6 +670,12 @@ scrape_configs:
static_configs:
- targets: ['app:2785']
metrics_path: '/api/metrics'
+ # /api/metrics is disabled (404) until METRICS_TOKEN is set, and then rejects a scrape
+ # without the bearer (401) — either way `up` goes to 0 and ServiceDown fires.
+ # Prometheus does not expand env vars in its config, so mount the token as a file.
+ authorization:
+ type: Bearer
+ credentials_file: /etc/prometheus/metrics_token
- job_name: 'node'
static_configs:
@@ -1038,62 +963,36 @@ export class MetricsService {
### Structured Logging
+Logging is dependency-free: there is no winston (or any logging library) in `package.json`. The
+logger is a small custom `LoggerService` in `src/common/services/logger.service.ts` that writes to
+the console — `error` and `warn` go to **stderr**, every other level to **stdout**, so a shipper
+configured for stdout alone drops exactly the lines you most want. `LOG_LEVEL`
+(`error|warn|info|debug|verbose`) sets verbosity and `LOG_FORMAT` (`json|pretty`) the rendering,
+defaulting to `json` under `NODE_ENV=production` and `pretty` elsewhere. Metadata whose **key name**
+looks like a secret (password, token, api-key, authorization, …) keeps the key and has its **value**
+replaced with `[REDACTED]` before the line is written.
+
+There is no in-app Loki transport: in the stack above, logs reach Loki because **promtail** scrapes
+the container's stdout and stderr from `/var/lib/docker/containers`.
+
```typescript
-// common/logging/logger.service.ts
-import { Injectable, LoggerService } from '@nestjs/common';
-import * as winston from 'winston';
+// common/services/logger.service.ts — usage
+import { createLogger } from '../common/services/logger.service';
@Injectable()
-export class AppLoggerService implements LoggerService {
- private logger: winston.Logger;
-
- constructor() {
- this.logger = winston.createLogger({
- level: process.env.LOG_LEVEL || 'info',
- format: winston.format.combine(
- winston.format.timestamp(),
- winston.format.json()
- ),
- defaultMeta: {
- service: 'openwa',
- version: process.env.npm_package_version
- },
- transports: [
- new winston.transports.Console(),
- // For Loki
- new winston.transports.Http({
- host: process.env.LOKI_HOST || 'loki',
- port: 3100,
- path: '/loki/api/v1/push',
- }),
- ],
+export class MessageService {
+ private readonly logger = createLogger('MessageService');
+
+ async send(): Promise<void> {
+ // log/warn/debug/verbose take (message, context?) where context is a string or metadata object;
+ // error() is (message, trace?, context?) — the stack trace comes second
+ this.logger.log('Message sent', {
+ sessionId: 'sess_123',
+ chatId: '[email protected]',
+ messageType: 'text',
});
}
-
- log(message: string, context?: object) {
- this.logger.info(message, { context });
- }
-
- error(message: string, trace?: string, context?: object) {
- this.logger.error(message, { trace, context });
- }
-
- warn(message: string, context?: object) {
- this.logger.warn(message, { context });
- }
-
- debug(message: string, context?: object) {
- this.logger.debug(message, { context });
- }
}
-
-// Usage example
-this.logger.log('Message sent', {
- sessionId: 'sess_123',
- chatId: '[email protected]',
- messageType: 'text',
- duration: 1.5
-});
```
### Key Metrics to Monitor
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index 63ae24716..bf4e2ef94 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -37,8 +37,11 @@ Each runbook follows this format:
# 1. Check container status
docker compose ps
-# 2. Check container logs
-docker compose logs --tail=100 openwa
+# 2. Check container logs. Every `docker compose … openwa-api` below names the service as the
+# production docker-compose.yml defines it — on docker-compose.dev.yml that service is called
+# `openwa`, so substitute it there. The bare `docker stats`/`docker restart` forms take the
+# container name, which is `openwa-api` under both files.
+docker compose logs --tail=100 openwa-api
# 3. Check system resources
docker stats --no-stream
@@ -47,18 +50,18 @@ free -m
# 4. Identify root cause
# A. Container crashed
-docker compose logs openwa 2>&1 | grep -i "error\|fatal\|crash"
+docker compose logs openwa-api 2>&1 | grep -i "error\|fatal\|crash"
# B. Out of memory
-docker compose logs openwa 2>&1 | grep -i "oom\|memory"
+docker compose logs openwa-api 2>&1 | grep -i "oom\|memory"
# C. Database connection
-docker compose logs openwa 2>&1 | grep -i "database\|connection refused"
+docker compose logs openwa-api 2>&1 | grep -i "database\|connection refused"
# 5. Apply fix based on cause:
# A. Simple restart
-docker compose restart openwa
+docker compose restart openwa-api
# B. Full restart with cleanup
docker compose down
@@ -68,11 +71,12 @@ docker compose up -d
# Edit docker-compose.yml and increase memory limit
docker compose up -d
-# D. Database issues
-docker compose restart postgres
+# D. Database issues (built-in PostgreSQL runs as container `openwa-postgres`, both when
+# started via the compose `postgres`/`full` profile and when orchestrated by the app)
+docker restart openwa-postgres
# Wait for postgres to be ready
sleep 10
-docker compose restart openwa
+docker compose restart openwa-api
```
**Verification:**
@@ -81,12 +85,13 @@ docker compose restart openwa
# Check health
curl http://localhost:2785/api/health
-# Check all sessions reconnected
+# Check all sessions reconnected (id alongside status — the send below needs the id)
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions | jq '.[].status'
+ http://localhost:2785/api/sessions | jq '.[] | {id, name, status}'
-# Send test message
-curl -X POST http://localhost:2785/api/sessions/default/messages/send-text \
+# Send test message ({sessionId} is the UUID from the listing above — session routes
+# resolve by id, not by session name)
+curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"chatId": "[email protected]", "text": "Test after restart"}'
@@ -114,7 +119,7 @@ curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}
# 2. Check if auto-reconnect is working
-docker compose logs openwa 2>&1 | grep -i "{sessionId}" | tail -20
+docker compose logs openwa-api 2>&1 | grep -i "{sessionId}" | tail -20
# 3. Try session restart (stop then start — there is no /restart route)
curl -X POST -H "X-API-Key: $API_KEY" \
@@ -173,8 +178,8 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \
**Steps:**
```bash
-# 1. Check current memory usage
-docker stats --no-stream openwa
+# 1. Check current memory usage (the container is named `openwa-api`)
+docker stats --no-stream openwa-api
free -m
# 2. Identify memory consumers
@@ -184,16 +189,16 @@ curl -H "Authorization: Bearer $METRICS_TOKEN" \
| grep -E "openwa_process_resident_memory_bytes|openwa_process_heap_used_bytes"
# 3. Check for memory leaks
-docker compose logs openwa 2>&1 | grep -i "heap\|memory\|gc"
+docker compose logs openwa-api 2>&1 | grep -i "heap\|memory\|gc"
# 4. Immediate actions:
# A. Clear the in-process cache (no runtime cache-clear API — restart the container;
# if using Redis, flush via redis-cli)
-docker compose restart openwa
+docker compose restart openwa-api
# B. Restart container (will reconnect sessions)
-docker compose restart openwa
+docker compose restart openwa-api
# C. If caused by too many sessions:
# List sessions (no sort param); process memory is in stats/overview (memoryUsage, MB)
@@ -211,7 +216,7 @@ curl -H "X-API-Key: $API_KEY" \
```bash
# Memory below threshold
-docker stats --no-stream openwa
+docker stats --no-stream openwa-api
# Expected: Memory usage < 80%
# All sessions still connected
@@ -242,9 +247,17 @@ as a delivery failure rather than retaining payloads without limit.
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks
-# 2. Check recent webhook deliveries
-# There is no webhook-delivery log API — inspect the server logs / audit trail instead:
-docker compose logs openwa 2>&1 | grep -i "webhook" | tail -20
+# 2. Check recent webhook deliveries — this admin-only endpoint lists abandoned deliveries
+# most-recent-first: those that exhausted every retry, plus those never attempted at all
+# (recorded with `attempts: 0` — payload over the cap or an unserializable payload
+# (preflight), inline waiter-queue overflow, or rejection by the shutdown drain).
+# A URL blocked by the SSRF guard never reaches delivery: it is rejected with a 400 when the
+# webhook is registered, so it appears in no delivery-failure row.
+curl -H "X-API-Key: $API_KEY" \
+ "http://localhost:2785/api/webhooks/delivery-failures?sessionId={sessionId}&limit=20"
+
+# Attempts still in flight (not yet exhausted) only appear in the server logs:
+docker compose logs openwa-api 2>&1 | grep -i "webhook" | tail -20
# 3. Identify failure reason:
# A. Endpoint not responding
@@ -301,9 +314,9 @@ curl -X POST -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks/{webhookId}/test
# Expected: {"success": true, "statusCode": 200}
-# Recent deliveries successful
-# No delivery-log API — confirm via the server logs / audit trail:
-docker compose logs openwa 2>&1 | grep -i "webhook" | tail -5
+# No new permanent delivery failures for this session
+curl -H "X-API-Key: $API_KEY" \
+ "http://localhost:2785/api/webhooks/delivery-failures?sessionId={sessionId}&limit=5"
```
---
@@ -334,8 +347,9 @@ docker stats --no-stream
# 3. Create backup
./scripts/backup.sh
-# Verify backup
-ls -la /backups/openwa/$(date +%Y%m%d)/
+# Verify backup (backup.sh writes $BACKUP_DIR/openwa-backup-<timestamp>.tar.gz,
+# BACKUP_DIR defaults to ./backups — it creates no dated subdirectories)
+ls -la ./backups/openwa-backup-*.tar.gz
# 4. Stop accepting new requests (if using load balancer)
# Remove from load balancer or set to maintenance mode
@@ -402,28 +416,31 @@ curl -H "X-API-Key: $API_KEY" \
# 1. Review release notes
# Check for breaking changes, migration requirements
-# 2. Create backup
+# 2. Create backup (BACKUP_DIR must be set BEFORE the script runs — it defaults to ./backups
+# and the archive is written as $BACKUP_DIR/openwa-backup-<timestamp>.tar.gz)
+export BACKUP_DIR="/backups/openwa"
./scripts/backup.sh
-BACKUP_DIR="/backups/openwa/$(date +%Y%m%d-%H%M%S)"
-# 3. Export current state
-docker compose exec openwa npm run export -- --output /tmp/export.json
-docker cp openwa:/tmp/export.json $BACKUP_DIR/
+# 3. Export the Data DB as JSON alongside the archive (admin key)
+curl -H "X-API-Key: $API_KEY" \
+ http://localhost:2785/api/infra/export-data > "$BACKUP_DIR/export-data.json"
# 4. Stop services
docker compose down
-# 5. Update version in docker-compose.yml
-# Change: image: ghcr.io/rmyndharis/openwa:0.1.0
-# To: image: ghcr.io/rmyndharis/openwa:0.7.3
+# 5. Fetch the new release
+# The shipped docker-compose.yml BUILDS openwa-api from source (`build: context: .`) — there is
+# no `image:` tag to edit and `docker compose pull` never updates the app, so upgrade the source:
+git pull
+# or pin to a release: git checkout v<new-version>
-# 6. Pull new image
-docker compose pull
+# 6. Build the new image
+docker compose build openwa-api
# 7. Run database migrations (if any)
# Use migration:run:prod in the production image — `migration:run` needs ts-node + the TS
# source, both stripped from the prod image by `npm ci --omit=dev`.
-docker compose run --rm openwa npm run migration:run:prod
+docker compose run --rm openwa-api npm run migration:run:prod
# 8. Start services
docker compose up -d
@@ -439,20 +456,27 @@ curl http://localhost:2785/api/health | jq '.version'
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions
-# 12. Test critical flows
-./scripts/smoke-test.sh
+# 12. Test critical flows — send through a live session ({sessionId} from step 11)
+curl -X POST http://localhost:2785/api/sessions/{sessionId}/messages/send-text \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"chatId": "[email protected]", "text": "Post-upgrade check"}'
```
+> If you deploy the published image instead of building from source — your own compose file with
+> `image: ghcr.io/rmyndharis/openwa:<tag>` — replace steps 5-6 with editing that tag and running
+> `docker compose pull`.
+
**Verification:**
```bash
# Correct version
curl http://localhost:2785/api/health | jq '.version'
-# Expected: "0.7.3"
+# Expected: "<new-version>"
-# All tests pass
-./scripts/smoke-test.sh
-# Expected: All tests pass
+# All sessions reconnected
+curl -H "X-API-Key: $API_KEY" \
+ http://localhost:2785/api/sessions | jq '.[].status'
```
**Rollback:**
@@ -461,10 +485,13 @@ curl http://localhost:2785/api/health | jq '.version'
# 1. Stop services
docker compose down
-# 2. Revert docker-compose.yml to previous version
+# 2. Check out the previous release and rebuild the image
+git checkout v<old-version>
+docker compose build openwa-api
-# 3. Restore from the pre-upgrade backup (both DBs + sessions)
-./scripts/restore.sh "$BACKUP_FILE"
+# 3. Restore from the pre-upgrade backup (both DBs + sessions) — the archive step 2 produced is
+# "$BACKUP_DIR/openwa-backup-<timestamp>.tar.gz"
+./scripts/restore.sh "$BACKUP_DIR/openwa-backup-<timestamp>.tar.gz"
# 4. Start with old version
docker compose up -d
@@ -592,9 +619,10 @@ curl http://localhost:2785/api/health
curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions
-# Verify data integrity
+# Verify data integrity ({sessionId} is the UUID from the listing above — session routes
+# resolve by id, not by session name)
curl -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/default/messages?limit=1"
+ "http://localhost:2785/api/sessions/{sessionId}/messages?limit=1"
```
---
@@ -653,7 +681,9 @@ df -h
# 2. Find large files
du -sh /var/lib/docker/*
du -sh ./data/*
-du -sh ./logs/*
+# The app writes no log files — it logs to stdout, so log volume is whatever the Docker
+# log driver retains for the container:
+du -sh "$(docker inspect --format='{{.LogPath}}' openwa-api)"
# 3. Clean up:
@@ -661,8 +691,9 @@ du -sh ./logs/*
docker system prune -af
docker volume prune -f
-# B. Old logs
-find ./logs -name "*.log" -mtime +7 -delete
+# B. Container log (Docker-managed; cap it at the daemon/compose log-driver level to stop it
+# growing back)
+sudo truncate -s 0 "$(docker inspect --format='{{.LogPath}}' openwa-api)"
# C. Old backups
find /backups -name "*.tar.gz" -mtime +30 -delete
@@ -671,9 +702,6 @@ find /backups -name "*.tar.gz" -mtime +30 -delete
# Warning: This deletes media files
find ./data/media -mtime +30 -delete
-# E. Truncate large log files
-truncate -s 0 ./logs/openwa.log
-
# 4. Verify
df -h
```
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index f537b06a8..7592d8909 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -21,7 +21,7 @@ docker compose ps
docker compose logs --tail=50
# System resources
-docker stats openwa
+docker stats openwa-api
```
### Diagnostic Flowchart
@@ -141,21 +141,25 @@ RUN apt-get install -y ... curl ...
# Check what's using the port
lsof -i :2785
# or
-netstat -tlnp | grep 3000
+netstat -tlnp | grep 2785
# Kill process using port
kill -9 $(lsof -t -i:2785)
-# Check Docker logs
-docker compose logs openwa
+# Check Docker logs (service name in the shipped production compose; it is `openwa` in
+# docker-compose.dev.yml)
+docker compose logs openwa-api
# Common fixes
-docker compose down --volumes # Reset volumes
-docker system prune -f # Clean up Docker
-docker compose pull # Get latest image
-docker compose up -d
+docker system prune -f # Clean up dangling images/containers
+git pull # The shipped compose BUILDS openwa-api from source —
+docker compose up -d --build # `docker compose pull` never updates it
```
+> Do **not** reach for `docker compose down --volumes` here. It deletes the `openwa-data` volume,
+> which holds the linked WhatsApp session profiles, the auth/audit database and every API key — a
+> port conflict never requires it.
+
### Issue: Dashboard Renders a Blank White Screen
**Symptoms:**
@@ -179,7 +183,7 @@ in the browser, so the server log stays clean.
CSP_UPGRADE_INSECURE_REQUESTS=false
# Confirm it actually reached the process
-docker compose exec openwa printenv NODE_ENV CSP_UPGRADE_INSECURE_REQUESTS
+docker compose exec openwa-api printenv NODE_ENV CSP_UPGRADE_INSECURE_REQUESTS
```
A production boot that serves the dashboard with the opt-out unset prints a warning naming this
@@ -192,9 +196,9 @@ 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"
-- "TIMEOUT" status after scanning QR
-- Session stuck in "CONNECTING" state
+- 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`
**Diagnostic:**
@@ -204,10 +208,10 @@ curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}
# Check WhatsApp engine logs
-docker compose logs openwa 2>&1 | grep -i "whatsapp\|puppeteer\|browser"
+docker compose logs openwa-api 2>&1 | grep -i "whatsapp\|puppeteer\|browser"
-# Check auth folder
-ls -la ./data/.wwebjs_auth/session-{sessionId}/
+# Check auth folder (named after the session NAME, under SESSION_DATA_PATH)
+docker compose exec openwa-api ls -la /app/data/sessions/session-<name>/
```
**Solutions:**
@@ -221,11 +225,18 @@ ls -la ./data/.wwebjs_auth/session-{sessionId}/
| WhatsApp blocked | Set a per-session proxy (`proxyUrl`) |
```bash
-# Clear auth and restart
-rm -rf ./data/.wwebjs_auth/session-{sessionId}
-docker compose restart openwa
+# Clear auth and restart (the profile dir carries the session NAME, not its UUID id)
+docker compose exec openwa-api rm -rf /app/data/sessions/session-<name>
+docker compose restart openwa-api
```
+> The service name above is the one in the shipped production `docker-compose.yml` (`openwa-api`),
+> which mounts `/app/data` from a **named volume** — there is no `./data` on the host to inspect;
+> reach into the container (`docker compose exec openwa-api ls /app/data/sessions`) instead. In
+> `docker-compose.dev.yml` the app service is called `openwa` and `./data` is bind-mounted, so the
+> same paths can be read directly from the host. Host-relative `./data/...` commands elsewhere in
+> this document assume a source install (`npm run start:dev`) or that dev bind mount.
+
Proxy 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`
@@ -444,7 +455,7 @@ except the WhatsApp pairing, which must be re-scanned.
**Symptoms:**
- Session disconnects every few hours
-- "DISCONNECTED" status in logs
+- `disconnected` status in logs
- Need to rescan QR frequently
**Causes & Solutions:**
@@ -465,20 +476,28 @@ flowchart LR
**Configuration fixes:**
-```env
-# Increase reconnection attempts
-WA_RECONNECT_INTERVAL=5000
-WA_MAX_RECONNECT_ATTEMPTS=10
+The reconnect backoff is configured **per session**, not by environment variables — pass it in the
+`config` object on `POST /api/sessions`:
-# Enable session persistence
-WA_PERSISTENT_SESSION=true
-
-# Increase timeouts
-WA_AUTH_TIMEOUT=120000
-WA_QR_TIMEOUT=60000
+```json
+{
+ "name": "my-bot",
+ "config": {
+ "reconnectBaseDelay": 5000,
+ "maxReconnectAttempts": 10
+ }
+}
```
-## 12.3 Messaging Issues
+`reconnectBaseDelay` is the exponential-backoff base in milliseconds (clamped to 1000–300000,
+default 5000). `maxReconnectAttempts` is clamped to 0–20 — `0` disables auto-reconnect entirely, and
+leaving 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).
+
+## 12.4 Messaging Issues
### Issue: Messages Not Sending
@@ -571,13 +590,13 @@ rm -rf node_modules/whatsapp-web.js && npm ci
**Solutions:**
```bash
-# Check file size limit
-echo $MAX_FILE_SIZE # Default: 16MB
+# Media size cap — covers remote-URL sends, inbound media, and outbound base64 sends.
+# Default 50 MiB; oversized base64 is rejected with 413 (Payload Too Large).
+MEDIA_DOWNLOAD_MAX_BYTES=52428800
-# Increase limit in docker-compose.yml
-environment:
- - MAX_FILE_SIZE=64mb
- - UPLOAD_TIMEOUT=60000
+# Max request body — base64 media rides inside the JSON body, so raise this too.
+# Default 25mb.
+BODY_SIZE_LIMIT=25mb
# Supported formats
# Images: jpg, jpeg, png, gif, webp
@@ -614,7 +633,7 @@ curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/{sessionId}/webhooks
# No webhook-delivery log API — check the server logs / audit trail instead
-docker compose logs openwa 2>&1 | grep -i webhook
+docker compose logs openwa-api 2>&1 | grep -i webhook
# Test webhook endpoint
curl -X POST http://your-webhook-url \
@@ -624,23 +643,30 @@ curl -X POST http://your-webhook-url \
**Solutions:**
-```yaml
-# Webhook configuration
-webhook:
- url: https://your-server.com/webhook
- events:
- - message.received
- - message.ack
- - session.status
- retry:
- max_attempts: 3
- delay: 5000
- timeout: 30000
- headers:
- Authorization: "Bearer your-token"
+Webhooks are rows created through the API — there is no webhook config file:
+
+```bash
+curl -X POST http://localhost:2785/api/sessions/{sessionId}/webhooks \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "url": "https://your-server.com/webhook",
+ "events": ["message.received", "message.ack", "session.status"],
+ "secret": "your-signing-secret",
+ "headers": { "Authorization": "Bearer your-token" },
+ "retryCount": 3
+ }'
```
-## 12.4 Performance Issues
+`retryCount` (0–5, default 3) is per webhook. The delivery timings are process-wide environment
+variables:
+
+```bash
+WEBHOOK_TIMEOUT=10000 # per-attempt HTTP timeout in ms (default 10000)
+WEBHOOK_RETRY_DELAY=5000 # base retry backoff in ms (default 5000)
+```
+
+## 12.5 Performance Issues
### Issue: High Memory Usage
@@ -653,7 +679,7 @@ webhook:
```bash
# Check memory usage
-docker stats openwa --no-stream
+docker stats openwa-api --no-stream
# Check process memory (Prometheus text; read openwa_process_resident_memory_bytes)
curl -H "Authorization: Bearer $METRICS_TOKEN" \
@@ -668,27 +694,18 @@ curl -H "Authorization: Bearer $METRICS_TOKEN" \
```yaml
# docker-compose.yml - Set memory limits
services:
- openwa:
- deploy:
- resources:
- limits:
- memory: 2G
- reservations:
- memory: 512M
+ openwa-api:
+ # The shipped compose already exposes this as mem_limit: ${OPENWA_MEM_LIMIT:-2g}
+ mem_limit: 2g
environment:
# Optimize Puppeteer (whatsapp-web.js engine only)
- PUPPETEER_ARGS=--disable-dev-shm-usage,--disable-gpu,--no-sandbox
- # Limit cache
- - WA_CACHE_SIZE=1000
- # Disable media caching
- - CACHE_MEDIA=false
```
**Memory Optimization Tips:**
| Optimization | Impact | Trade-off |
|--------------|--------|-----------|
-| Disable media cache | -30% RAM | Slower media re-send |
| Reduce message history | -20% RAM | Less searchable history |
| Headless Chrome flags | -15% RAM (wwebjs only) | None |
| Limit concurrent sessions | Linear | Fewer sessions |
@@ -717,33 +734,31 @@ curl -H "X-API-Key: $API_KEY" \
**Solutions:**
```sql
--- SQLite: Add indexes
-CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id);
-CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);
-CREATE INDEX IF NOT EXISTS idx_contacts_session_id ON contacts(session_id);
+-- Indexes ship with the schema (migrations) — there is nothing to add by hand. `messages`
+-- carries ("sessionId", "createdAt"), ("chatId"), ("status"), ("createdAt") and a unique
+-- ("sessionId", "waMessageId").
--- PostgreSQL: Analyze tables
+-- PostgreSQL: refresh planner statistics on the hot tables
ANALYZE sessions;
ANALYZE messages;
-ANALYZE contacts;
```
-```yaml
-# Enable connection pooling (PostgreSQL)
-database:
- type: postgresql
- pool:
- min: 5
- max: 20
- idle_timeout: 30000
-
-# Enable Redis caching
-cache:
- adapter: redis
- ttl: 3600
+Pooling and caching are environment variables — OpenWA has no config file:
+
+```bash
+# Connection pool + timeouts (applied to the PostgreSQL data connection)
+DATABASE_POOL_SIZE=10 # max pooled connections (default 10)
+DATABASE_IDLE_TIMEOUT_MS=30000 # idle client eviction (default 30000)
+DATABASE_CONNECTION_TIMEOUT_MS=10000 # wait for a free connection (default 10000)
+DATABASE_STATEMENT_TIMEOUT_MS=30000 # server-side per-query cap (default 30000)
+
+# Redis caching (per-key TTLs are fixed in code — there is no cache TTL env var)
+REDIS_ENABLED=true
+REDIS_HOST=localhost
+REDIS_PORT=6379
```
-## 12.5 Database Issues
+## 12.6 Database Issues
### Issue: Database Locked (SQLite)
@@ -780,8 +795,6 @@ flowchart TD
D -->|No| E[Optimize SQLite]
E --> E1[Enable WAL mode]
- E --> E2[Increase timeout]
- E --> E3[Add indexes]
```
### Issue: Database Migration Failed
@@ -810,7 +823,7 @@ npm run migration:run:main
**PostgreSQL crash-loop on boot after upgrade** — if logs show `column "id" is of type uuid but default expression is of type character varying` or `foreign key constraint ... cannot be implemented ... incompatible types: character varying and uuid`, the deployment was previously bootstrapped with `DATABASE_SYNCHRONIZE=true` (native `uuid` columns vs the migrations' `varchar`). A guard migration converts the columns automatically on the next boot; for large `messages` tables, run the migration against the stopped app (`npm run migration:run`) during a maintenance window. See [14.5 / 14.9 — PostgreSQL crash-loop after upgrading a `DATABASE_SYNCHRONIZE=true` deployment](./14-migration-guide.md). `DATABASE_SYNCHRONIZE=true` is unsupported on PostgreSQL for production.
-## 12.6 Docker Issues
+## 12.7 Docker Issues
### Issue: Volume Permissions
@@ -831,7 +844,7 @@ sudo chown -R $(id -u):$(id -g) ./data/
# Or use Docker's user mapping
# docker-compose.yml
services:
- openwa:
+ openwa-api:
user: "1000:1000" # Your UID:GID
```
@@ -847,7 +860,7 @@ services:
```yaml
# docker-compose.yml - Ensure proper networking
services:
- openwa:
+ openwa-api:
networks:
- openwa-network
extra_hosts:
@@ -864,11 +877,11 @@ networks:
```bash
# Test connectivity from container
-docker exec openwa ping postgres
-docker exec openwa curl http://host.docker.internal:8080
+docker exec openwa-api ping postgres
+docker exec openwa-api curl http://host.docker.internal:8080
```
-## 12.7 Frequently Asked Questions
+## 12.8 Frequently Asked Questions
### General Questions
@@ -1027,6 +1040,9 @@ available_events:
- 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 "*")
+
# Session
- session.status # Session status change
- session.qr # New QR code generated
@@ -1049,6 +1065,8 @@ available_events:
"event": "message.received",
"timestamp": "2026-02-02T10:30:00Z",
"sessionId": "sess_abc123",
+ "idempotencyKey": "msg_sess_abc123_ABC123_DEF456",
+ "deliveryId": "dlv_550e8400-e29b-41d4-a716-446655440000",
"data": {
"id": "ABC123_DEF456",
"from": "[email protected]",
@@ -1064,7 +1082,7 @@ available_events:
}
```
-## 12.8 Error Code Reference
+## 12.9 Error Code Reference
### HTTP Error Codes
@@ -1080,25 +1098,25 @@ available_events:
| 500 | Internal Error | Server error | Check logs |
| 503 | Service Unavailable | Session disconnected | Reconnect session |
-### WhatsApp Error Codes
+### Error Body Shape
+
+There are no machine-readable WhatsApp error codes. Errors use the NestJS default shape, so match on
+`statusCode` (above) and read `message` for the human-readable cause:
-| Code | Meaning | Solution |
-|------|---------|----------|
-| `WA_SESSION_NOT_FOUND` | Session doesn't exist | Create session first |
-| `WA_SESSION_NOT_READY` | Session not connected | Wait for connection or rescan QR |
-| `WA_INVALID_PHONE` | Invalid phone format | Use format: [email protected] |
-| `WA_NUMBER_NOT_EXISTS` | Number not on WhatsApp | Verify number |
-| `WA_RATE_LIMITED` | Too many messages | Wait and reduce rate |
-| `WA_MEDIA_ERROR` | Media processing failed | Check file format/size |
-| `WA_GROUP_NOT_FOUND` | Group doesn't exist | Verify group ID |
-| `WA_NOT_ADMIN` | Not group admin | Need admin rights |
+```json
+{
+ "statusCode": 404,
+ "message": "Session with id 'a1b2c3d4-...' not found",
+ "error": "Not Found"
+}
+```
-## 12.9 Getting Help
+## 12.10 Getting Help
### Before Asking for Help
1. **Check this FAQ** - Most common issues are covered
-2. **Check logs** - `docker compose logs openwa --tail=100`
+2. **Check logs** - `docker compose logs openwa-api --tail=100`
3. **Try basic troubleshooting** - Restart, clear cache, etc.
4. **Search GitHub issues** - Your issue might be already reported
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 4801c3641..8dad36b7c 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -70,10 +70,11 @@ Since WhatsApp sessions maintain active connections (a browser instance for `wha
### Strategy 1: Session-to-Node Mapping (Recommended)
-Store session-node mapping in the database:
+Store session-node mapping in the database. **(Not implemented — no `node_id` / `node_url` column
+exists in any entity or migration; the DDL below is illustrative of the future design.)**
```sql
--- Sessions table includes node assignment
+-- Illustrative only: these columns do not exist in the shipped schema
ALTER TABLE sessions ADD COLUMN node_id VARCHAR(50);
ALTER TABLE sessions ADD COLUMN node_url VARCHAR(255);
```
@@ -82,7 +83,8 @@ The load balancer reads the mapping and routes accordingly.
### Strategy 2: Consistent Hashing
-Route sessions based on session ID hash:
+Route sessions based on session ID hash. **(Not implemented — no such routing helper exists in
+code; the sketch below is illustrative of the future design.)**
```typescript
function getNodeForSession(sessionId: string, nodes: string[]): string {
@@ -105,7 +107,7 @@ version: '3.8'
services:
openwa:
- image: ghcr.io/rmyndharis/openwa:0.4.6
+ image: ghcr.io/rmyndharis/openwa:latest
deploy:
replicas: 1 # MUST stay 1 until session-claim is implemented — multiple replicas on one session volume corrupt WhatsApp auth
update_config:
@@ -124,10 +126,12 @@ services:
- DATABASE_TYPE=postgres
- DATABASE_HOST=postgres
- DATABASE_NAME=openwa
- - DATABASE_USER=openwa
+ - DATABASE_USERNAME=openwa
- DATABASE_PASSWORD=${DB_PASSWORD}
- REDIS_HOST=redis
- - ENABLE_QUEUE=true
+ - QUEUE_ENABLED=true
+ # Operator-facing metadata only — the application does not read NODE_ID (no consumer
+ # exists in src/). Useful for correlating log lines by hand, nothing more.
- NODE_ID={{.Node.Hostname}}-{{.Task.Slot}}
volumes:
- sessions:/app/data/sessions
@@ -187,14 +191,18 @@ docker swarm init
# Deploy stack
docker stack deploy -c docker-compose.swarm.yml openwa
-# Scale up/down
-docker service scale openwa_openwa=5
-
# Check status
docker service ls
docker service ps openwa_openwa
```
+> **Do not scale the `openwa` service** (`docker service scale openwa_openwa=N`). The `sessions`
+> volume above is declared with the default local driver (not `external`), so Swarm creates one per
+> node: replicas co-located on a single node share that directory and corrupt the WhatsApp auth
+> state, while replicas placed on other nodes each get a fresh empty volume and start an
+> unauthenticated engine instead. Either way the deployment breaks — see the warning at the top of
+> this guide. Scaling only becomes safe once session-claim exists.
+
## 13.4 Kubernetes Deployment
### k8s/namespace.yaml
@@ -222,7 +230,7 @@ data:
DATABASE_NAME: 'openwa'
REDIS_HOST: 'redis-service'
REDIS_PORT: '6379'
- ENABLE_QUEUE: 'true'
+ QUEUE_ENABLED: 'true'
PORT: '2785'
```
@@ -236,10 +244,8 @@ metadata:
namespace: openwa
type: Opaque
stringData:
- DATABASE_USER: openwa
+ DATABASE_USERNAME: openwa
DATABASE_PASSWORD: your-secure-password
- ADMIN_API_KEY: your-admin-api-key
- WEBHOOK_SECRET: your-webhook-secret
```
### k8s/deployment.yaml
@@ -251,7 +257,7 @@ metadata:
name: openwa
namespace: openwa
spec:
- serviceName: openwa
+ serviceName: openwa-headless # must match the headless Service declared in k8s/service.yaml
replicas: 1 # MUST stay 1 until session-claim is implemented — see the warning at the top of this guide
selector:
matchLabels:
@@ -271,7 +277,7 @@ spec:
fsGroup: 1000
containers:
- name: openwa
- image: ghcr.io/rmyndharis/openwa:0.10.10
+ image: ghcr.io/rmyndharis/openwa:latest
ports:
- containerPort: 2785
name: http
@@ -281,6 +287,8 @@ spec:
- secretRef:
name: openwa-secrets
env:
+ # Operator-facing metadata only — the application does not read NODE_ID (no consumer
+ # exists in src/); it is retained for the future node-affinity design in 13.2.
- name: NODE_ID
valueFrom:
fieldRef:
@@ -402,12 +410,14 @@ kubectl apply -f k8s/
kubectl get pods -n openwa
# Check logs
-kubectl logs -f deployment/openwa -n openwa
-
-# Scale
-kubectl scale statefulset openwa --replicas=5 -n openwa
+kubectl logs -f statefulset/openwa -n openwa
```
+> **Do not raise `replicas` above 1** (`kubectl scale statefulset openwa --replicas=N`). Each pod
+> gets its own PVC, so extra replicas do not share a session directory — they each start their own
+> unauthenticated engine, and with `AUTO_START_SESSIONS=true` every pod tries to drive the same
+> configured sessions from the shared database. See the warning at the top of this guide.
+
## 13.5 Load Balancer Configuration
### Traefik Dynamic Config
@@ -495,16 +505,23 @@ server {
### Scaling Guidelines
-| Metric | Threshold | Action |
-| ----------------------------- | ---------- | ---------- |
-| CPU > 80% | 5 minutes | Scale up |
-| Memory > 85% | 5 minutes | Scale up |
-| CPU < 30% | 15 minutes | Scale down |
-| Active sessions per node > 20 | - | Scale up |
+The replica count stays at **1** (see 13.3 and 13.4), so the only levers available today are
+**vertical** — adjust the `resources` limits/reservations in the manifests above — or run a second
+single-instance deployment with its own session volume and split sessions between them. Horizontal
+`scale up` / `scale down` becomes an option only once session-claim is implemented.
+
+| Metric | Threshold | Action |
+| --------------------------------- | ---------- | ------------------------------------------------------ |
+| CPU > 80% | 5 minutes | Raise `limits.cpu` (StatefulSet); the Swarm block above declares no CPU constraint, so add one |
+| Memory > 85% | 5 minutes | Raise the memory limit |
+| CPU < 30% | 15 minutes | Lower `requests.cpu` — that is what the scheduler reserves; lowering `limits.cpu` only tightens throttling |
+| Active sessions per instance > 20 | - | Move sessions to a second instance with its own volume |
-### Benchmarks
+### Throughput Projections
-Tested on 2 vCPU / 4GB RAM nodes:
+Design targets for 2 vCPU / 4GB RAM nodes, **not measurements** — no benchmark artifact in this
+repository backs any row, including the 1-node one, and multi-node operation is not implemented (see
+the warning at the top of this guide), so the 3- and 5-node rows could not have been run at all:
| Nodes | Sessions | Messages/sec | p95 Latency |
| ----- | -------- | ------------ | ----------- |
@@ -514,7 +531,25 @@ Tested on 2 vCPU / 4GB RAM nodes:
## 13.7 Monitoring
-### Prometheus Metrics (Future)
+### Prometheus Metrics
+
+OpenWA exports Prometheus text exposition at `GET /api/metrics` (`openwa_*` gauges and counters).
+The endpoint returns `404` until `METRICS_TOKEN` is set, and then requires that token as a Bearer:
+
+```yaml
+# prometheus/prometheus.yml
+scrape_configs:
+ - job_name: 'openwa'
+ static_configs:
+ # Swarm service name (13.3). On Kubernetes there is no Service called `openwa` — scrape the
+ # pod through the headless Service instead, e.g.
+ # openwa-0.openwa-headless.openwa.svc.cluster.local:2785
+ - targets: ['openwa:2785']
+ metrics_path: '/api/metrics'
+ authorization:
+ type: Bearer
+ credentials_file: /etc/prometheus/metrics_token
+```
```yaml
# prometheus/openwa-rules.yaml
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index 5dd8e4d6e..ea5296bf7 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -5,7 +5,7 @@
This document provides a comprehensive guide for migrating OpenWA, including:
- Database migration (SQLite → PostgreSQL)
-- Version upgrades (v0.1 → v0.2 → v1.0)
+- Version upgrades within the 0.x line
- Transfer session authentication state
- Rollback procedures
@@ -36,8 +36,9 @@ flowchart TB
### Backup
-- [ ] Database backup completed
-- [ ] Session auth files backed up (.wwebjs_auth/)
+- [ ] Database backup completed (both connections: ./data/main.sqlite + the data store)
+- [ ] Session auth backed up (SESSION_DATA_PATH, default ./data/sessions)
+- [ ] Baileys auth backed up, if used (BAILEYS_AUTH_DIR, default ./data/baileys)
- [ ] Environment variables documented
- [ ] Docker volumes backed up (if applicable)
@@ -132,17 +133,39 @@ curl -X POST 'http://localhost:2785/api/infra/import-data' \
"sessions": [...],
"webhooks": [...],
"messages": [...],
- "messageBatches": [...]
+ "messageBatches": [...],
+ "templates": [...],
+ "baileysStoredMessages": [...],
+ "lidMappings": [...],
+ "pluginInstances": [...],
+ "conversationMappings": [...],
+ "ingressEvents": [...],
+ "webhookDeliveryFailures": [...],
+ "integrationDeliveryFailures": [...],
+ "statusUpdates": [...]
},
"counts": {
"sessions": 5,
"webhooks": 12,
"messages": 1500,
- "messageBatches": 3
- }
+ "messageBatches": 3,
+ "templates": 4,
+ "baileysStoredMessages": 0,
+ "lidMappings": 87,
+ "pluginInstances": 2,
+ "conversationMappings": 31,
+ "ingressEvents": 12,
+ "webhookDeliveryFailures": 0,
+ "integrationDeliveryFailures": 0,
+ "statusUpdates": 19
+ },
+ "skippedTables": []
}
```
+> [!NOTE]
+> `skippedTables` lists optional tables absent from an older schema; the import tolerates them.
+
### Storage Migration (Local ↔ S3/MinIO)
OpenWA v0.2+ supports migrating media files between storage backends:
@@ -184,7 +207,7 @@ curl -X POST 'http://localhost:2785/api/infra/storage/import' \
### Redis Migration (Cache)
-Redis in OpenWA is used **only for caching** with TTL-based expiration. Cache data is ephemeral and automatically regenerates from the database.
+Redis in OpenWA holds only **ephemeral** state: TTL-based cache entries, BullMQ jobs (see below), and — when `REDIS_ENABLED` — the rate-limit hit counters. Cache data automatically regenerates from the database.
**No migration API needed** - just change configuration:
@@ -198,12 +221,12 @@ REDIS_USERNAME=optional
REDIS_PASSWORD=optional
```
-| Scenario | Support | Notes |
-| ------------------------- | ------- | ---------------------------- |
-| Built-in → External Redis | ✅ | Config change only |
-| External → Built-in Redis | ✅ | Config change only |
-| Enable → Disable Redis | ✅ | App uses memory fallback |
-| Disable → Enable Redis | ✅ | Cache rebuilds automatically |
+| 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 |
> [!TIP]
> **Cache Warm-up**: After switching Redis instances, the cache will automatically rebuild as requests come in. No data migration is necessary.
@@ -216,7 +239,7 @@ BullMQ stores job data in Redis. When switching Redis instances, pending jobs ma
```bash
# Step 1: Check queue status via Bull Board
-# Visit: http://localhost:2785/admin/queues
+# Visit: http://localhost:2785/api/admin/queues
# Step 2: Wait until MESSAGE and WEBHOOK queues are empty
# Or check via API:
@@ -238,7 +261,7 @@ docker compose up -d
| Built-in → External Redis | ⚠️ | Drain queue first |
> [!WARNING]
-> **Job Loss Prevention**: Always ensure the MESSAGE and WEBHOOK queues are empty before switching Redis instances. Check `/admin/queues` dashboard.
+> **Job Loss Prevention**: Always ensure the MESSAGE and WEBHOOK queues are empty before switching Redis instances. Check the `/api/admin/queues` dashboard.
### Infrastructure Migration Summary
@@ -251,7 +274,11 @@ docker compose up -d
### Migration Script (Legacy)
-> **Note:** This example uses the standalone `sqlite3` npm package, which is no longer part of
+> **Note:** This is an illustrative standalone script, not a shipped one — there is no
+> `scripts/migrate-sqlite-to-postgres.ts` in the repo. Save it locally before running it, and prefer
+> the export/import API above, which always covers the full table set.
+>
+> It uses the standalone `sqlite3` npm package, which is no longer part of
> OpenWA's dependencies (the app itself uses `better-sqlite3`). Install it ad hoc before running:
> `npm install --no-save sqlite3`.
>
@@ -261,7 +288,7 @@ docker compose up -d
> (see `src/config/configuration.ts`).
```typescript
-// scripts/migrate-sqlite-to-postgres.ts
+// migrate-sqlite-to-postgres.ts — illustrative, not shipped in the repo
import { DataSource } from 'typeorm';
import * as sqlite3 from 'sqlite3';
@@ -294,16 +321,22 @@ async function migrateSqliteToPostgres(config: MigrationConfig): Promise<Migrati
const tables = await getSqliteTables(sqliteDb);
console.log(`📋 Found ${tables.length} tables to migrate`);
- // 3. Migration order (respect foreign keys)
+ // 3. Migration order (respect foreign keys). Data-DB tables only — the Main DB
+ // (api_keys, audit_logs) is always local SQLite and is never migrated.
const migrationOrder = [
'sessions',
- 'api_keys',
'webhooks',
- 'contacts',
'messages',
- 'media_files',
- 'webhook_logs',
- 'audit_logs',
+ 'message_batches',
+ 'templates',
+ 'baileys_stored_messages',
+ 'lid_mappings',
+ 'plugin_instances',
+ 'conversation_mappings',
+ 'ingress_events',
+ 'webhook_delivery_failures',
+ 'integration_delivery_failures',
+ 'status_updates',
];
// 4. Migrate each table
@@ -360,7 +393,9 @@ async function migrateTable(
// Insert into PostgreSQL
for (const row of rows) {
try {
- const columns = Object.keys(row);
+ // Entity columns are camelCase (e.g. sessionId); PostgreSQL folds unquoted
+ // identifiers to lowercase, so they must be quoted or the INSERT fails.
+ const columns = Object.keys(row).map(column => `"${column}"`);
const values = Object.values(row);
const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
@@ -437,15 +472,15 @@ migrateSqliteToPostgres(config)
# Step 1: Stop OpenWA
docker compose down
-# Step 2: Backup current data
-cp -r ./data ./data-backup-$(date +%Y%m%d)
-docker exec openwa-db pg_dump -U postgres openwa > backup.sql
+# Step 2: Backup current data (both databases + session auth + media)
+./scripts/backup.sh
-# Step 3: Setup PostgreSQL (if not exists)
-docker compose -f docker-compose.postgres.yml up -d postgres
+# Step 3: Setup PostgreSQL (if not exists) — the built-in service lives behind a compose profile
+docker compose --profile postgres up -d postgres
-# Step 4: Run migration script
-npx ts-node scripts/migrate-sqlite-to-postgres.ts
+# Step 4: Run the migration — save the "Migration Script (Legacy)" example above as
+# migrate-sqlite-to-postgres.ts first; it is not shipped in the repo
+npx ts-node migrate-sqlite-to-postgres.ts
# Step 5: Update environment
export DATABASE_TYPE=postgres
@@ -460,39 +495,37 @@ psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT
psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT COUNT(*) FROM messages;"
# Step 7: Start with PostgreSQL
-docker compose -f docker-compose.postgres.yml up -d
+docker compose --profile postgres up -d
# Step 8: Verify functionality
-curl http://localhost:2785/health
+curl http://localhost:2785/api/health
```
### Verification Queries
```sql
-- Compare row counts
--- Run on both SQLite and PostgreSQL
+-- Run on both SQLite and PostgreSQL. Data DB only — api_keys and audit_logs stay in the local Main DB.
-- Sessions
SELECT 'sessions' as table_name, COUNT(*) as count FROM sessions
UNION ALL
SELECT 'messages', COUNT(*) FROM messages
UNION ALL
-SELECT 'contacts', COUNT(*) FROM contacts
-UNION ALL
-SELECT 'webhooks', COUNT(*) FROM webhooks
+SELECT 'message_batches', COUNT(*) FROM message_batches
UNION ALL
-SELECT 'api_keys', COUNT(*) FROM api_keys;
+SELECT 'webhooks', COUNT(*) FROM webhooks;
--- Verify foreign key integrity
-SELECT m.id, m.session_id
+-- Verify foreign key integrity (entity columns are camelCase — quote them)
+SELECT m.id, m."sessionId"
FROM messages m
-LEFT JOIN sessions s ON m.session_id = s.id
+LEFT JOIN sessions s ON m."sessionId" = s.id
WHERE s.id IS NULL;
-- Check for data integrity
-SELECT session_id, COUNT(*) as msg_count
+SELECT "sessionId", COUNT(*) as msg_count
FROM messages
-GROUP BY session_id
+GROUP BY "sessionId"
ORDER BY msg_count DESC
LIMIT 10;
```
@@ -502,450 +535,182 @@ LIMIT 10;
### Understanding Session Auth
```
-Session Auth Structure:
-.wwebjs_auth/
-├── session-{sessionId}/
+whatsapp-web.js (LocalAuth) — SESSION_DATA_PATH, default ./data/sessions
+./data/sessions/
+├── session-{sessionName}/
│ ├── Default/
│ │ ├── IndexedDB/
│ │ ├── Local Storage/
│ │ └── Session Storage/
│ └── ... (Chrome profile data)
-```
-
-### Transfer Methods
-
-#### Method 1: Direct File Copy (Same Host)
-
-```bash
-#!/bin/bash
-# transfer-session.sh
-SOURCE_DIR="/old-server/data/.wwebjs_auth"
-TARGET_DIR="/new-server/data/.wwebjs_auth"
-SESSION_ID=$1
-
-if [ -z "$SESSION_ID" ]; then
- echo "Usage: ./transfer-session.sh <session-id>"
- exit 1
-fi
-
-# Stop both instances
-echo "⏹️ Stopping services..."
-ssh old-server "docker compose down"
-ssh new-server "docker compose down"
-
-# Copy session data
-echo "📦 Copying session data..."
-rsync -avz --progress \
- "old-server:${SOURCE_DIR}/session-${SESSION_ID}/" \
- "${TARGET_DIR}/session-${SESSION_ID}/"
-
-# Copy database record
-echo "📄 Exporting session record..."
-ssh old-server "sqlite3 /data/openwa.sqlite \
- \"SELECT * FROM sessions WHERE id='${SESSION_ID}'\" \
- -csv" > session_record.csv
-
-# Import to new database
-echo "📥 Importing session record..."
-ssh new-server "sqlite3 /data/openwa.sqlite \
- \".import session_record.csv sessions\""
-
-# Start new server
-echo "▶️ Starting new server..."
-ssh new-server "docker compose up -d"
-
-echo "✅ Session ${SESSION_ID} transferred successfully"
+Baileys — BAILEYS_AUTH_DIR, default ./data/baileys
+./data/baileys/
+└── {sessionName}/ # multi-file auth state
```
-#### Method 2: Export/Import via API
-
-```typescript
-// Export session from old server
-// GET /api/sessions/{id}/export
-
-interface SessionExport {
- session: {
- id: string;
- name: string;
- phoneNumber: string;
- status: string;
- config: object;
- };
- authData: string; // Base64 encoded tar.gz of auth folder
- webhooks: WebhookConfig[];
- contacts: Contact[];
-}
-
-// api/sessions/export.controller.ts
-@Get(':id/export')
-@UseGuards(ApiKeyGuard)
-async exportSession(@Param('id') id: string): Promise<SessionExport> {
- const session = await this.sessionService.findOne(id);
-
- // Create tar.gz of auth folder
- const authPath = path.join(this.authDir, `session-${id}`);
- const tarBuffer = await this.createTarGz(authPath);
-
- return {
- session: {
- id: session.id,
- name: session.name,
- phoneNumber: session.phoneNumber,
- status: 'exported',
- config: session.config,
- },
- authData: tarBuffer.toString('base64'),
- webhooks: await this.webhookService.findBySession(id),
- contacts: await this.contactService.findBySession(id),
- };
-}
-
-// Import session to new server
-// POST /api/sessions/import
-
-@Post('import')
-@UseGuards(ApiKeyGuard)
-async importSession(@Body() data: SessionExport): Promise<Session> {
- // 1. Create session record
- const session = await this.sessionService.create({
- id: data.session.id,
- name: data.session.name,
- config: data.session.config,
- });
+> [!IMPORTANT]
+> **Directories are keyed by session NAME, not by the REST id.** The API addresses a session by its
+> UUID (`/api/sessions/{id}`), but the engine receives `session.name` as its client id, so the on-disk
+> profile is `session-<name>` (whatsapp-web.js) or `<name>` (Baileys). Resolve the name via
+> `GET /api/sessions/{id}` before copying anything.
- // 2. Extract auth data
- const authBuffer = Buffer.from(data.authData, 'base64');
- const authPath = path.join(this.authDir, `session-${session.id}`);
- await this.extractTarGz(authBuffer, authPath);
+### Transfer Methods
- // 3. Import webhooks
- for (const webhook of data.webhooks) {
- await this.webhookService.create({
- ...webhook,
- sessionId: session.id,
- });
- }
+#### Method 1: Direct File Copy (Server to Server)
- // 4. Import contacts
- for (const contact of data.contacts) {
- await this.contactService.create({
- ...contact,
- sessionId: session.id,
- });
- }
+Moves the auth profile only. The session's database record is created separately — either by
+`POST /api/sessions` on the target with the same `name`, or with the infra export/import of
+Method 2. Copying rows between SQLite files by hand is not supported: the `sessions` table carries
+columns the copy would have to reproduce exactly, and a mismatch corrupts the row.
- // 5. Initialize session (will use existing auth)
- await this.whatsappService.initSession(session.id);
+Under the shipped compose the data directory lives in a named Docker volume
+(`openwa-data:/app/data`), not a host bind mount, so the profile is copied through the container
+with `docker compose cp` rather than straight off the host filesystem. `APP_DIR` is the directory
+holding `docker-compose.yml` on each server; `SESSION_NAME` is the session `name` (resolve it via
+`GET /api/sessions/{id}` — the on-disk directory is keyed by name, not by the REST id).
- return session;
-}
+```bash
+APP_DIR=/srv/openwa # docker compose project directory on both hosts
+SESSION_NAME=my-session
+
+# 1. Stop the app on both hosts. Use `stop`, not `down`: a running engine holds the profile open,
+# but `down` removes the container that step 2 copies through.
+ssh old-server "cd $APP_DIR && docker compose stop openwa-api"
+ssh new-server "cd $APP_DIR && docker compose stop openwa-api"
+
+# 2. Copy the auth profile out of the source container, to the target host, and back in.
+# whatsapp-web.js: /app/data/sessions/session-<name>.
+# Baileys: /app/data/baileys/<name> (no "session-" prefix).
+ssh old-server "cd $APP_DIR && docker compose cp \
+ openwa-api:/app/data/sessions/session-$SESSION_NAME ./session-$SESSION_NAME"
+rsync -avz --progress "old-server:$APP_DIR/session-$SESSION_NAME/" \
+ "new-server:$APP_DIR/session-$SESSION_NAME/"
+ssh new-server "cd $APP_DIR && docker compose cp \
+ ./session-$SESSION_NAME openwa-api:/app/data/sessions/session-$SESSION_NAME"
+
+# 3. Start the target back up.
+ssh new-server "cd $APP_DIR && docker compose start openwa-api"
```
-### Bulk Session Transfer
+Delete the staging copies (`$APP_DIR/session-$SESSION_NAME` on both hosts) afterwards — they hold
+live WhatsApp credentials.
-```typescript
-// scripts/bulk-transfer-sessions.ts
-
-interface TransferConfig {
- sourceUrl: string;
- sourceApiKey: string;
- targetUrl: string;
- targetApiKey: string;
- sessionIds: string[] | 'all';
-}
+#### Method 2: Records via the Infra API + auth state by file copy
-async function bulkTransferSessions(config: TransferConfig): Promise<void> {
- const axios = require('axios');
+There is **no per-session export/import endpoint** — the session controller exposes only lifecycle and
+chat operations. What ships is a whole-Data-DB export at `/api/infra/export-data` and
+`/api/infra/import-data` (see [14.3](#143-database-migration-sqlite--postgresql)); it carries the session
+_records_, not the on-disk authentication state. A server-to-server move is therefore two steps:
- // Get session list
- let sessionIds = config.sessionIds;
- if (sessionIds === 'all') {
- const response = await axios.get(`${config.sourceUrl}/api/sessions`, {
- headers: { 'X-API-Key': config.sourceApiKey },
- });
- sessionIds = response.data.map((s: any) => s.id);
- }
-
- console.log(`📋 Transferring ${sessionIds.length} sessions...`);
-
- for (const sessionId of sessionIds) {
- try {
- console.log(`\n🔄 Processing session: ${sessionId}`);
-
- // 1. Stop session on source
- await axios.post(
- `${config.sourceUrl}/api/sessions/${sessionId}/stop`,
- {},
- { headers: { 'X-API-Key': config.sourceApiKey } },
- );
-
- // 2. Export from source
- const exportResponse = await axios.get(`${config.sourceUrl}/api/sessions/${sessionId}/export`, {
- headers: { 'X-API-Key': config.sourceApiKey },
- });
+```bash
+# 1. Move the Data DB records (sessions, webhooks, messages, …)
+curl -s 'http://old-server:2785/api/infra/export-data' \
+ -H 'X-API-Key: OLD_KEY' > data-backup.json
- // 3. Import to target
- await axios.post(`${config.targetUrl}/api/sessions/import`, exportResponse.data, {
- headers: { 'X-API-Key': config.targetApiKey },
- });
+curl -X POST 'http://new-server:2785/api/infra/import-data' \
+ -H 'X-API-Key: NEW_KEY' \
+ -H 'Content-Type: application/json' \
+ -d @data-backup.json
- console.log(`✅ Session ${sessionId} transferred`);
- } catch (error: any) {
- console.error(`❌ Failed to transfer ${sessionId}: ${error.message}`);
- }
- }
-}
+# 2. Move the engine auth state with both instances stopped (Method 1), keyed by session NAME.
+# OLD_DIR/NEW_DIR are each host's OpenWA working directory; SESSION_DATA_PATH defaults to
+# ./data/sessions and BAILEYS_AUTH_DIR to ./data/baileys, relative to it. The production
+# docker-compose.yml keeps /app/data in the named volume `openwa_openwa-data` rather than on the
+# host, so on that layout copy through the container (`docker cp`) instead of a host path.
+rsync -avz "old-server:${OLD_DIR}/data/sessions/" "${NEW_DIR}/data/sessions/"
+rsync -avz "old-server:${OLD_DIR}/data/baileys/" "${NEW_DIR}/data/baileys/" # Baileys sessions only
```
+Sessions whose auth directory is not copied arrive as records only and must be re-paired by scanning a
+fresh QR code.
+
## 14.5 Version Upgrade Guide
### Upgrade Matrix
-```mermaid
-flowchart LR
- V01[v0.1.x] -->|Direct| V02[v0.2.x]
- V02 -->|Direct| V10[v1.0.x]
- V01 -->|"Via v0.2"| V10
- V10 -->|Direct| V11[v1.1.x]
- V11 -->|Direct| V12[v1.2.x]
-```
+OpenWA is pre-1.0 — every release to date is on the `0.x` line. Under the project's SemVer 0.x policy a
+breaking change bumps the **minor** (`0.10.x` → `0.11.0`) and everything else is a patch, so a minor bump
+is the one that warrants reading the release notes closely.
-| From | To | Migration Type | Downtime |
-| ------ | ------ | ------------------------- | --------- |
-| v0.1.x | v0.2.x | Schema migration | 5-10 min |
-| v0.2.x | v1.0.x | Schema + Config migration | 10-15 min |
-| v0.1.x | v1.0.x | Must go via v0.2.x | 15-25 min |
-| v1.x | v1.y | Usually automatic | < 5 min |
+| From | To | Migration Type | Downtime |
+| --------------------- | ------------------- | ---------------------------------------------- | --------- |
+| `0.x.y` | `0.x.z` (patch) | Pending migrations only | < 5 min |
+| `0.x.y` | `0.(x+1).0` (minor) | Pending migrations + review the breaking notes | 5-15 min |
+| Several releases back | Current | Same — the migration chain replays in order | 10-15 min |
-### v0.1 → v0.2 Migration
+Upgrades are cumulative: migrations apply in order from wherever the schema currently sits, so jumping
+straight to the current release is supported. There is no required intermediate stop — but read every
+intervening `CHANGELOG.md` entry, because behavior changes are not replayed by migrations.
-#### Breaking Changes in v0.2
-
-```yaml
-breaking_changes:
- api:
- - path: /api/session → /api/sessions (plural)
- - path: /api/send → /api/sessions/{id}/messages
- - auth: Basic Auth → API Key
-
- config:
- - DATABASE_PATH → DATABASE_TYPE + discrete connection vars (DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD) for PostgreSQL
- - WEBHOOK_URL → Managed via API
-
- database:
- - New tables: api_keys, webhook_logs
- - Modified: sessions (added config JSON column)
- - Modified: messages (added metadata column)
-```
+Schema migrations run automatically at boot on the **data** connection only — always on PostgreSQL,
+and on SQLite unless `DATABASE_SYNCHRONIZE=true` puts the data store in synchronize mode. The Main
+(auth/audit) connection defaults to synchronize instead, and under that default runs no migrations at
+boot. Setting `MAIN_DATABASE_SYNCHRONIZE=false` switches it to its own migration chain, which then
+also runs at boot (`migrationsRun` is the inverse of `synchronize` on both connections); run that
+chain by hand with `npm run migration:run:main`.
-#### Migration Steps
+### Upgrade Steps
```bash
#!/bin/bash
-# upgrade-v01-to-v02.sh
-
+# upgrade.sh — same shape for a patch or a minor
set -e
-echo "🚀 Upgrading OpenWA v0.1.x → v0.2.x"
-
-# 1. Backup
-echo "📦 Creating backup..."
-BACKUP_DIR="./backups/v01-$(date +%Y%m%d-%H%M%S)"
-mkdir -p "$BACKUP_DIR"
-cp -r ./data "$BACKUP_DIR/"
-cp .env "$BACKUP_DIR/"
+# 1. Backup: both databases + session auth + media + plugin state
+./scripts/backup.sh
-# 2. Stop current version
-echo "⏹️ Stopping v0.1..."
+# 2. Stop the current version
docker compose down
-# 3. Run database migrations
-echo "🔄 Running migrations..."
-docker run --rm \
- -v $(pwd)/data:/app/data \
- -e DATABASE_TYPE=sqlite \
- -e DATABASE_NAME=/app/data/openwa.sqlite \
- ghcr.io/rmyndharis/openwa:0.2.0 \
- npm run migration:run:prod # the prod image strips ts-node/TS source — use :prod
-
-# 4. Migrate configuration
-echo "⚙️ Migrating configuration..."
-cat > .env.new << 'EOF'
-# OpenWA v0.2.x Configuration
-
-# Database (unchanged if using SQLite)
-DATABASE_TYPE=sqlite
-DATABASE_NAME=./data/openwa.sqlite
-
-# New in v0.2: API Key Authentication
-API_KEY_ENABLED=true
-# Generate with: openssl rand -hex 32
-API_KEY=your-generated-api-key
-
-# Webhook (now managed via API, but can set default)
-DEFAULT_WEBHOOK_URL=${WEBHOOK_URL:-}
-
-# Other settings migrated from v0.1
-NODE_ENV=${NODE_ENV:-production}
-PORT=${PORT:-3000}
-LOG_LEVEL=${LOG_LEVEL:-info}
-EOF
-
-# Merge with existing .env
-source .env
-envsubst < .env.new > .env.migrated
-mv .env.migrated .env
-rm .env.new
-
-# 5. Start new version
-echo "▶️ Starting v0.2..."
-docker compose pull
-docker compose up -d
+# 3. Move to the new version
+# The repo's compose file BUILDS the API image from source:
+git pull && docker compose up -d --build
+# Deployments pinned to a published image instead (ghcr.io/rmyndharis/openwa:<version>)
+# bump the tag in their compose file, then: docker compose pull && docker compose up -d
-# 6. Wait for health
-echo "⏳ Waiting for health check..."
-sleep 10
-curl -f http://localhost:2785/health || exit 1
-
-# 7. Create API key for existing integrations
-echo "🔑 Creating API key..."
-docker exec openwa npm run cli -- create-api-key --name "migrated-key"
-
-echo "✅ Upgrade complete!"
-echo ""
-echo "⚠️ IMPORTANT: Update your API clients:"
-echo " - Change /api/session to /api/sessions"
-echo " - Change /api/send to /api/sessions/{id}/messages"
-echo " - Add X-API-Key header to all requests"
-```
-
-### v0.2 → v1.0 Migration
+# 4. Wait for health — every route lives under the /api prefix
+for i in {1..30}; do
+ if curl -sf http://localhost:2785/api/health > /dev/null; then
+ echo "✅ Health check passed"
+ break
+ fi
+ sleep 2
+done
-#### Breaking Changes in v1.0
+# 5. Confirm the running version
+curl -s http://localhost:2785/api/health | jq '.version'
-```yaml
-breaking_changes:
- api:
- - Groups API restructured
- - Webhook payload format v2
- - Rate limiting enforced
-
- config:
- - ENGINE_TYPE required (default: whatsapp-web.js; also accepts: baileys)
- - STORAGE_ADAPTER required (default: local)
-
- database:
- - New tables: groups, group_participants, channels
- - sessions.status enum expanded
+# 6. Verify sessions came back
+curl -s -H "X-API-Key: $API_KEY" \
+ http://localhost:2785/api/sessions | jq '.[] | {id, name, status}'
```
-#### Migration Steps
-
-```bash
-#!/bin/bash
-# upgrade-v02-to-v10.sh
-
-set -e
-
-echo "🚀 Upgrading OpenWA v0.2.x → v1.0.0"
-
-# Pre-flight checks
-CURRENT_VERSION=$(docker inspect ghcr.io/rmyndharis/openwa --format '{{.Config.Labels.version}}' 2>/dev/null || echo "unknown")
-echo "Current version: $CURRENT_VERSION"
-
-# 1. Comprehensive backup
-echo "📦 Creating comprehensive backup..."
-BACKUP_DIR="./backups/v02-$(date +%Y%m%d-%H%M%S)"
-mkdir -p "$BACKUP_DIR"
-
-# Backup database
-if [ "$DATABASE_TYPE" = "postgres" ]; then
- pg_dump -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" "$DATABASE_NAME" > "$BACKUP_DIR/database.sql"
-else
- cp ./data/openwa.sqlite "$BACKUP_DIR/"
-fi
-
-# Backup auth sessions
-cp -r ./data/.wwebjs_auth "$BACKUP_DIR/"
+> [!NOTE]
+> `GET /api/sessions` returns a bare array — responses carry no `{success, data}` envelope, so filter with
+> `jq '.[]'`, never `jq '.data[]'`.
-# Backup config
-cp .env "$BACKUP_DIR/"
-cp docker-compose.yml "$BACKUP_DIR/"
+Migrations can also be run explicitly against a stopped app — useful when a long index build would
+outlast an orchestrator's liveness grace:
-# 2. Export webhook configurations (per session, new format in v1.0)
-echo "📤 Exporting webhooks..."
-for sessionId in $(curl -s -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions | jq -r '.data[].id'); do
- curl -s -H "X-API-Key: $API_KEY" \
- "http://localhost:2785/api/sessions/${sessionId}/webhooks" \
- > "$BACKUP_DIR/webhooks_${sessionId}.json"
-done
+```bash
+docker compose run --rm openwa-api npm run migration:run:prod
+```
-# 3. Stop services
-echo "⏹️ Stopping v0.2..."
-docker compose down
+> [!WARNING]
+> Use `migration:run:prod` inside the production image. Plain `npm run migration:run` needs `ts-node` and
+> the TypeScript sources, both stripped by `npm ci --omit=dev` in the released image.
-# 4. Update configuration
-echo "⚙️ Updating configuration..."
-cat >> .env << 'EOF'
-
-# New in v1.0
-ENGINE_TYPE=whatsapp-web.js # default (Chromium-based); set to "baileys" for browser-free engine
-STORAGE_ADAPTER=local
-CACHE_ADAPTER=memory
-
-# Webhook v2 format (recommended)
-WEBHOOK_VERSION=2
-EOF
-
-# 5. Run database migrations
-echo "🔄 Running migrations..."
-docker run --rm \
- -v $(pwd)/data:/app/data \
- --env-file .env \
- ghcr.io/rmyndharis/openwa:1.0.0 \
- npm run migration:run
-
-# 6. Migrate webhooks to new format
-echo "🔄 Migrating webhooks..."
-docker run --rm \
- -v $(pwd)/data:/app/data \
- -v "$BACKUP_DIR/webhooks.json:/tmp/webhooks.json" \
- --env-file .env \
- ghcr.io/rmyndharis/openwa:1.0.0 \
- npm run cli -- migrate-webhooks /tmp/webhooks.json
-
-# 7. Start new version
-echo "▶️ Starting v1.0..."
-sed -i 's/:0.2./:1.0./g' docker-compose.yml
-docker compose pull
-docker compose up -d
+### Known Upgrade Hazards
-# 8. Health check
-echo "⏳ Waiting for health check..."
-for i in {1..30}; do
- if curl -sf http://localhost:2785/health > /dev/null; then
- echo "✅ Health check passed"
- break
- fi
- sleep 2
-done
+| Release | Change | Action |
+| -------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
+| `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` |
-# 9. Verify sessions
-echo "🔍 Verifying sessions..."
-curl -s -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions | jq '.[] | {id, status}'
-
-echo ""
-echo "✅ Upgrade to v1.0.0 complete!"
-echo ""
-echo "📝 Post-upgrade tasks:"
-echo " 1. Update webhook consumers for v2 payload format"
-echo " 2. Test all active sessions"
-echo " 3. Review new rate limits"
-echo " 4. Check Groups API if used"
-```
+The authoritative list is `CHANGELOG.md`; breaking items are flagged there with ⚠️ **Breaking**.
## 14.6 Rollback Procedures
@@ -955,12 +720,13 @@ echo " 4. Check Groups API if used"
#!/bin/bash
# rollback.sh
+# A DIRECTORY of restored files — not the tar.gz that scripts/backup.sh writes (see the TIP below).
BACKUP_DIR=$1
TARGET_VERSION=$2
if [ -z "$BACKUP_DIR" ] || [ -z "$TARGET_VERSION" ]; then
echo "Usage: ./rollback.sh <backup-dir> <target-version>"
- echo "Example: ./rollback.sh ./backups/v02-20260215-120000 0.2.0"
+ echo "Example: ./rollback.sh ./backups/pre-upgrade-20260215-120000 0.2.0"
exit 1
fi
@@ -979,26 +745,32 @@ else
cp "$BACKUP_DIR/openwa.sqlite" ./data/
fi
-# 3. Restore auth sessions
+# 3. Restore auth sessions (SESSION_DATA_PATH + BAILEYS_AUTH_DIR)
echo "📥 Restoring auth sessions..."
-rm -rf ./data/.wwebjs_auth
-cp -r "$BACKUP_DIR/.wwebjs_auth" ./data/
+rm -rf ./data/sessions ./data/baileys
+cp -r "$BACKUP_DIR/sessions" ./data/
+[ -d "$BACKUP_DIR/baileys" ] && cp -r "$BACKUP_DIR/baileys" ./data/
# 4. Restore configuration
echo "📥 Restoring configuration..."
cp "$BACKUP_DIR/.env" .
cp "$BACKUP_DIR/docker-compose.yml" .
-# 5. Start old version
+# 5. Start the target version. The repo compose BUILDS the image, so check out the tag and rebuild;
+# a deployment pinned to a published image bumps the tag and runs `docker compose pull` instead.
echo "▶️ Starting v${TARGET_VERSION}..."
-docker compose pull
-docker compose up -d
+git checkout "v${TARGET_VERSION}"
+docker compose up -d --build
# 6. Verify
sleep 10
-curl -f http://localhost:2785/health && echo "✅ Rollback successful"
+curl -f http://localhost:2785/api/health && echo "✅ Rollback successful"
```
+> [!TIP]
+> `./scripts/restore.sh <backup-archive.tar.gz>` performs the same restore from an archive produced by
+> `scripts/backup.sh` — including the Main DB (`./data/main.sqlite`), which the script above does not touch.
+
### Rollback Decision Tree
```mermaid
@@ -1035,33 +807,42 @@ migration:
target: staging
steps:
- - name: Export sessions (anonymized)
+ - name: Export the Data DB from development
command: |
- npm run cli -- export-sessions \
- --anonymize \
- --output /tmp/sessions-staging.json
+ curl -s 'http://dev-host:2785/api/infra/export-data' \
+ -H "X-API-Key: $DEV_API_KEY" > /tmp/dev-data.json
- - name: Reset database
+ - name: Start staging on an empty data store
command: |
- npm run migration:fresh
+ # Schema migrations run at boot, so a removed store is recreated from scratch
+ docker compose down
+ rm -f ./data/openwa.sqlite
+ docker compose up -d
- - name: Import test sessions
+ - name: Import into staging
command: |
- npm run cli -- import-sessions /tmp/sessions-staging.json
+ curl -X POST 'http://staging-host:2785/api/infra/import-data' \
+ -H "X-API-Key: $STAGING_API_KEY" \
+ -H 'Content-Type: application/json' \
+ -d @/tmp/dev-data.json
- name: Configure staging webhooks
command: |
- npm run cli -- set-webhook \
- --url https://staging-webhook.example.com/openwa \
- --events message,status
-
- - name: Set staging limits
- command: |
- npm run cli -- set-limits \
- --max-sessions 10 \
- --rate-limit 100/min
+ curl -X POST 'http://staging-host:2785/api/sessions/{sessionId}/webhooks' \
+ -H "X-API-Key: $STAGING_API_KEY" \
+ -H 'Content-Type: application/json' \
+ -d '{"url":"https://staging-webhook.example.com/openwa","events":["message.received"]}'
+
+ - name: Set staging rate limits
+ note: |
+ Rate limits are environment variables, not an API — set RATE_LIMIT_MEDIUM_TTL and
+ RATE_LIMIT_MEDIUM_LIMIT (plus the SHORT/LONG pairs) in the staging .env, then restart.
```
+> [!NOTE]
+> The export covers the Data DB only. API keys live in the Main DB and are never transferred — staging
+> issues its own keys.
+
### Staging → Production
```yaml
@@ -1072,22 +853,18 @@ migration:
pre_checks:
- name: Staging tests passed
- command: npm run test:e2e -- --tag staging
+ command: npm run test:e2e
required: true
- - name: Performance benchmarks
- command: npm run benchmark
- threshold: 'p99 < 500ms'
-
- name: Security scan
- command: npm audit --production
+ command: npm audit --omit=dev
required: true
steps:
- name: Blue-green deployment
type: blue-green
config:
- health_check: /health
+ health_check: /api/health
switch_after: 60s
rollback_on_error: true
@@ -1104,8 +881,13 @@ migration:
### Full Export
+> [!NOTE]
+> This is an illustrative standalone script, not a shipped one. `/api/infra/export-data` already covers
+> every Data-DB table (see [14.3](#143-database-migration-sqlite--postgresql)); hand-rolled table lists
+> like the one below silently drop whatever they omit.
+
```typescript
-// scripts/full-export.ts
+// full-export.ts — illustrative, not shipped in the repo
interface ExportOptions {
outputDir: string;
@@ -1121,18 +903,21 @@ async function fullExport(options: ExportOptions): Promise<void> {
const exportDir = path.join(options.outputDir, `export-${Date.now()}`);
await fs.ensureDir(exportDir);
- // 1. Export database tables
+ // 1. Export database tables (Data DB only — api_keys/audit_logs stay in the local Main DB)
console.log('📊 Exporting database...');
- const tables = ['sessions', 'messages', 'contacts', 'webhooks', 'api_keys'];
+ const tables = ['sessions', 'webhooks', 'messages', 'message_batches', 'templates'];
for (const table of tables) {
const data = await db.query(`SELECT * FROM ${table}`);
await fs.writeJson(path.join(exportDir, `${table}.json`), data, { spaces: 2 });
}
- // 2. Export auth sessions
+ // 2. Export auth sessions (SESSION_DATA_PATH + BAILEYS_AUTH_DIR)
console.log('🔐 Exporting auth sessions...');
- await fs.copy('./data/.wwebjs_auth', path.join(exportDir, 'auth'));
+ await fs.copy('./data/sessions', path.join(exportDir, 'sessions'));
+ if (await fs.pathExists('./data/baileys')) {
+ await fs.copy('./data/baileys', path.join(exportDir, 'baileys'));
+ }
// 3. Export media (optional)
if (options.includeMedia) {
@@ -1179,8 +964,12 @@ async function fullExport(options: ExportOptions): Promise<void> {
### Full Import
+> [!NOTE]
+> Also illustrative, not a shipped script — `/api/infra/import-data` is the supported counterpart to
+> the export above.
+
```typescript
-// scripts/full-import.ts
+// full-import.ts — illustrative, not shipped in the repo
interface ImportOptions {
inputPath: string;
@@ -1218,7 +1007,7 @@ async function fullImport(options: ImportOptions): Promise<void> {
}
// Import order matters (foreign keys)
- const importOrder = ['sessions', 'api_keys', 'webhooks', 'contacts', 'messages'];
+ const importOrder = ['sessions', 'webhooks', 'messages', 'message_batches', 'templates'];
for (const table of importOrder) {
const dataPath = path.join(importDir, `${table}.json`);
@@ -1233,13 +1022,18 @@ async function fullImport(options: ImportOptions): Promise<void> {
}
// Import auth sessions
- const authPath = path.join(importDir, 'auth');
- if (await fs.pathExists(authPath)) {
- console.log('🔐 Importing auth sessions...');
- if (!options.dryRun) {
- await fs.copy(authPath, './data/.wwebjs_auth', {
- overwrite: options.mergeStrategy === 'replace',
- });
+ for (const [dir, target] of [
+ ['sessions', './data/sessions'],
+ ['baileys', './data/baileys'],
+ ]) {
+ const authPath = path.join(importDir, dir);
+ if (await fs.pathExists(authPath)) {
+ console.log(`🔐 Importing auth state: ${dir}...`);
+ if (!options.dryRun) {
+ await fs.copy(authPath, target, {
+ overwrite: options.mergeStrategy === 'replace',
+ });
+ }
}
}
@@ -1289,21 +1083,23 @@ docker compose up -d
# Check database integrity
sqlite3 ./data/openwa.sqlite "PRAGMA integrity_check;"
-# Verify auth session files
-ls -la ./data/.wwebjs_auth/session-*/
+# Verify auth session files (directories are named after the session NAME)
+ls -la ./data/sessions/session-*/
+ls -la ./data/baileys/ # Baileys engine
# Check file permissions
stat ./data/openwa.sqlite
-stat ./data/.wwebjs_auth
+stat ./data/sessions
# Verify PostgreSQL connection
psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT version();"
-# Check migration status
+# Check migration status (add :main for the auth/audit connection)
npm run migration:show
-# Force re-run specific migration
-npm run migration:run -- --name CreateApiKeysTable
+# Re-apply the most recent migration (there is no per-migration re-run —
+# migration:run always applies the whole pending chain)
+npm run migration:revert && npm run migration:run
```
---
diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.md
index 65298c90e..259233efe 100644
--- a/docs/15-project-roadmap.md
+++ b/docs/15-project-roadmap.md
@@ -40,6 +40,13 @@ timeline
: Bundled Traefik removed
: Bring-your-own reverse proxy
+ section v0.5.0-v0.11.0 - Incremental Releases (Released)
+ Jun-Jul 2026 : Integration Fabric provisioning
+ : Java & Go SDKs
+ : Live message edits
+ : Chat kind discriminator & status store
+ : Security & reliability hardening
+
section v1.0.0 - Enterprise
2027 : Kubernetes Operator
: Multi-tenant
@@ -70,11 +77,16 @@ timeline
| 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 |
| v1.0.0 | Enterprise Ready (K8s Operator, multi-tenant) | 📋 Planned |
-> SDK / docs-site / observability features (Node & Python SDK, Postman collection, Grafana, OpenTelemetry)
-> are delivered **incrementally** in `0.2.x`/`0.3.x` as they're additive — they no longer gate a single
-> version. The version **number** follows SemVer (see §15.2), not the theme.
+> 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
+> site, a Postman export, Grafana and OpenTelemetry remain open (see §15.6). The version **number**
+> follows SemVer (see §15.2), not the theme.
### Risk Buffer
@@ -110,7 +122,7 @@ Examples:
0.1.0 - Initial Stable Release (Full features)
0.1.1 - Bug fix for QR timeout
0.2.0 - i18n, Real-time Chats, Webhook Delivery-state & Hardening
-0.3.0 - SDK & Developer Tools
+0.3.0 - Engine Pluggability (Baileys engine, plugin layer)
1.0.0 - Enterprise Ready
2.0.0 - Breaking API changes
```
@@ -494,7 +506,7 @@ v0.1.0 Release Package:
## 15.6 Future Roadmap (v0.3.0+)
> **Note:** Version 0.1.0 is the initial stable release including all features from Phases 1-3.
-> Versions 0.1.7 through 0.7.8 have since shipped (see the CHANGELOG); v1.0.0
+> Versions 0.1.7 through 0.11.0 have since shipped (see the CHANGELOG); v1.0.0
> onward is forward-looking.
```mermaid
@@ -512,9 +524,10 @@ flowchart LR
V020[v0.2.0 - i18n, Real-time Chats,<br/>Webhook Delivery-state & Hardening]
end
- subgraph v0.x["✅ Released (v0.3–v0.4)"]
+ subgraph v0.x["✅ Released (v0.3–v0.11)"]
V030[v0.3.0 - Engine Pluggability<br/>Baileys engine + plugin layer]
V040[v0.4.0 - Single-Port Deployment<br/>Dashboard on API port, no bundled Traefik]
+ V011[v0.5.0-v0.11.0 - Incremental releases<br/>see the CHANGELOG]
end
subgraph v1.x["v1.x Series - Enterprise"]
@@ -553,13 +566,16 @@ vars are removed. Ships with a migration guide.
#### Incremental themes — SDK, Developer Tools & Observability
-Delivered additively whenever ready, per SemVer (not gated to one version). The client SDKs and Prometheus metrics have **shipped** (v0.7.x); the rest remain open.
+Delivered additively whenever ready, per SemVer (not gated to one version). Prometheus metrics shipped
+in `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 |
@@ -592,14 +608,22 @@ architecture and design rationale):
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |
| 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. | 📋 Planned |
-| P3 | Second adapter (chatbot flow builder) — validates the substrate generalizes. | 📋 Planned |
-| P4 | Developer experience: SDK reference docs, compatibility test suite, secret rotation, multi-node routing. | 📋 Planned |
-
-> **P0 and P1 are an internal foundation, not a user-facing feature yet.** The ingress flow requires an
-> operator provisioning step (minting a plugin instance and its secret) that lands in P2; until then it is
-> reachable only by direct configuration. The public SDK reference and the first ready-to-use adapter
-> arrive in P2–P4.
+| 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
+> through `POST /api/integration/plugins/:pluginId/instances/:instanceId/regenerate-secret`; both are also
+> reachable from the **Instances** tab of the dashboard plugin dialog. Rotation is a hard cutover — the old
+> secret stops verifying the moment the new one is minted, so a dual-secret grace window is still open.
+> `chatwoot-adapter` is P2's helpdesk adapter and needs a gateway on `0.8.7`+. P3 is closed by
+> `supabase-otp-hook`, the second official ingress plugin — a different vehicle than the chatbot flow
+> builder this row originally named, but it is what proved the substrate generalizes to an independent
+> consumer. Adapters ship from the
+> [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) catalog, so consult that repository for
+> each plugin's declared capabilities. P4 remains open: the published SDK reference, a compatibility test
+> suite, and multi-node routing.
### v1.0.0 - Enterprise Ready
diff --git a/docs/16-risk-management.md b/docs/16-risk-management.md
index a8b578399..6473dc749 100644
--- a/docs/16-risk-management.md
+++ b/docs/16-risk-management.md
@@ -100,24 +100,30 @@ flowchart TB
**Built-in Safeguards:**
```typescript
-// Default rate limits to prevent ban
-const DEFAULT_SAFEGUARDS = {
- // Message sending
- minDelayBetweenMessages: 3000, // 3 seconds minimum
- maxMessagesPerMinute: 20,
- maxMessagesPerHour: 200,
-
- // Session behavior
- enableTypingIndicator: true,
- randomizeDelays: true,
-
- // Warnings
- warnOnBulkSend: true,
- warnOnNewNumberSpam: true,
+// src/modules/message/bulk-message.service.ts — bulk-send pacing defaults
+const options = {
+ delayBetweenMessages: dto.options?.delayBetweenMessages ?? 3000, // 3s (DTO range 1000–60000)
+ randomizeDelay: dto.options?.randomizeDelay ?? true, // adds 0–2s jitter per message
+ stopOnError: dto.options?.stopOnError ?? false,
};
```
-**User Guidelines Document:**
+Alongside that:
+
+- `SIMULATE_TYPING` (on by default; `SIMULATE_TYPING_MAX_MS` default 5000) shows the engine's typing
+ indicator and pauses for a length-scaled, jittered interval before a **text** send — `send-text`,
+ and `send-template` only because it renders to text and delegates to the same path. Every other
+ send (image, video, audio, document, sticker, location, contact, poll, reply, forward) reaches the
+ engine with no typing indicator and no pause.
+- `BULK_MAX_CONCURRENT_BATCHES` (default 50, `0` = unlimited) caps concurrent bulk batches per process.
+- A single bulk request carries at most 100 messages (`@ArrayMaxSize(100)` on
+ `SendBulkMessageDto.messages`); a 101st entry is rejected by the global `ValidationPipe` with HTTP 400.
+
+Not implemented: there are no per-minute / per-hour / per-day send caps, no media-specific delay and
+no new-number warmup enforcement. The guidelines below are operator discipline, not something the
+gateway enforces.
+
+**User Guidelines:**
```markdown
## Anti-Ban Best Practices
@@ -289,7 +295,7 @@ Dependencies (`whatsapp-web.js`, Puppeteer, NestJS, etc.) may have vulnerabiliti
**Mitigation Strategies:**
-> **Current state:** the real dependency check is an inline `npm audit --audit-level=critical` step in `ci.yml` (runs on push / PR — not on a daily schedule), plus Dependabot PRs (`.github/dependabot.yml`: npm for `/` and `/dashboard`, weekly). There is **no** standalone `security.yml` and **no** Snyk integration. The workflow below is a recommended enhancement to add scheduled scanning.
+> **Current state:** the real dependency check is a dedicated `audit` job in `ci.yml` running `npm audit --audit-level=high` (on push / PR — not on a daily schedule); it is deliberately split out of the `Lint` job so a newly published advisory cannot abort the other quality gates. `release.yml` repeats the same `npm audit --audit-level=high` and additionally runs a Trivy image scan (`CRITICAL,HIGH`, `ignore-unfixed`) against an explicit `.trivyignore` before the release tags are promoted. Dependabot PRs cover npm for `/` and `/dashboard` (weekly), GitHub Actions (monthly) and Docker base/compose images (weekly), with version-pinned ignores for `typescript >=7` and `better-sqlite3 >=13`. There is **no** standalone `security.yml` and **no** Snyk integration. The workflow below is a recommended enhancement to add scheduled scanning.
```yaml
# .github/workflows/security.yml
@@ -320,9 +326,11 @@ jobs:
| Action | Frequency |
|--------|-----------|
-| npm audit (`--audit-level=critical`, inline in CI) | Every push / PR |
+| 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`) | Weekly |
+| Dependabot PRs (npm: `/` and `/dashboard`; docker) | Weekly |
+| Dependabot PRs (github-actions) | Monthly |
| Major updates | Reviewed manually |
| Security patches | Immediate |
@@ -504,28 +512,23 @@ WhatsApp has undocumented internal rate limits. Sending too many messages can tr
**Built-in Safeguards:**
-```typescript
-// Anti-ban configuration defaults
-const RATE_LIMIT_CONFIG = {
- // Per session limits
- messagesPerMinute: 20,
- messagesPerHour: 200,
- messagesPerDay: 1000,
-
- // Delays
- minDelayBetweenMessages: 3000, // 3 seconds
- maxDelayBetweenMessages: 5000, // 5 seconds
- delayAfterMedia: 5000, // 5 seconds after media
-
- // Bulk messaging
- bulkBatchSize: 50,
- bulkDelayBetweenBatches: 60000, // 1 minute
-
- // New number warmup
- newNumberDailyLimit: 50,
- newNumberWarmupDays: 14,
-};
-```
+The 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`) |
+
+These bound API traffic and bulk pacing — they are **not** per-session WhatsApp send caps. The
+gateway does not count messages per minute, hour or day per session, so staying inside WhatsApp's
+undocumented limits remains the operator's responsibility. The thresholds below are targets for
+operator-side monitoring, not values the gateway enforces.
**Monitoring Metrics:**
@@ -571,15 +574,20 @@ flowchart TB
Prevention --> Detection --> Recovery
```
-**Backup Schedule:**
+**Backup Coverage:**
| Data Type | Frequency | Retention | Storage |
|-----------|-----------|-----------|---------|
-| Database (full) | Daily 02:00 | 30 days | S3/GCS |
-| Database (incremental) | Every 6 hours | 7 days | S3/GCS |
-| Session auth state | On change | Indefinite | Database |
+| 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 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>`.
+> A database-only backup loses every pairing — those directories must be in the file-level backup.
+> `scripts/backup.sh` already captures both alongside the databases. Running it on a schedule and
+> copying the archives off-box are the operator's responsibility.
+
---
## 16.6 Escalation Procedures
@@ -715,12 +723,12 @@ flowchart LR
| ID | Risk | Probability | Impact | Level | Status |
|----|------|-------------|--------|-------|--------|
| R001 | Protocol Changes | High | High | 🔴 Critical | Monitoring |
-| R002 | Account Ban | Medium | Medium | 🟡 Medium | Mitigated |
+| 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 | Mitigated |
+| R007 | Rate Limiting | High | Medium | 🟡 Medium | Partially mitigated |
| R008 | Data Loss | Low | High | 🟡 Medium | Mitigated |
### Risk Trend
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index b8893aabe..3b1416e37 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -31,11 +31,13 @@ flowchart LR
```
The styling foundation is **plain CSS** — there is no Tailwind, no shadcn/ui, and no CSS-in-JS.
-Each page and shared component ships its own stylesheet colocated beside the source
+Every page — and most shared components — ships its own stylesheet colocated beside the source
(`Sessions.tsx` + `Sessions.css`, `Layout.tsx` + `Layout.css`, ...), imported directly by the
-component. Icons come from `lucide-react`; charts from `recharts`; i18n from `react-i18next`.
-Client state is **TanStack Query** for server data (see `src/hooks/queries.ts`) plus a couple of
-small React Context providers (`useRole`, `useTheme`) — there is no Zustand store.
+component (see §17.4 for the handful that carry no stylesheet of their own). Icons come from
+`lucide-react`; charts from `recharts`; i18n from `react-i18next`.
+Client state is **TanStack Query** for server data (see `src/hooks/queries.ts`) plus two small React
+Context providers (`RoleProvider`, `ToastProvider`); theme mode is a provider-less `useTheme` hook
+backed by `localStorage` — there is no Zustand store.
### Design Principles
@@ -351,18 +353,30 @@ a non-admin hitting the path falls through to the `*` redirect.
### Bespoke components
The UI is built from a small set of project-specific components under `dashboard/src/components/`,
-each with a colocated CSS file. There is no design-system package to pull from.
+most with a colocated CSS file. Five ship none: `ErrorBoundary` styles inline via `style={{...}}`,
+`GithubIcon` carries no styling beyond `fill="currentColor"`, `Modal` reuses the global `.modal-*`
+rules from `index.css`, and the `chats/` pair take their classes from the page stylesheet
+(`pages/Chats.css`) plus the `yet-another-react-lightbox` vendor CSS. There is no design-system
+package to pull from.
| Component | File | Responsibility |
| ---------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `Layout` | `components/Layout.tsx` | App shell: collapsible sidebar nav, mobile drawer, language menu, light/dark theme toggle, logout, live version badge |
| `ToastProvider` / `useToast` | `components/Toast.tsx` | Context-based toast notifications (success/error/warning/info) with de-dup keys |
| `PageHeader` | `components/PageHeader.tsx` | Shared page title / subtitle / badge / actions header |
+| `Modal` | `components/Modal.tsx` | Accessible dialog (`role="dialog"`, Escape/overlay close, focus trap + restore); uses the global `.modal-*` styles |
+| `CustomSelect` | `components/CustomSelect.tsx` | Keyboard-navigable select replacement (type-ahead, arrow keys) used by Sessions / Logs / Login |
| `DashboardCharts` | `components/DashboardCharts.tsx` | `recharts`-based message-volume / activity charts on the Dashboard |
| `FilterBuilder` | `components/FilterBuilder.tsx` | Visual condition builder for webhook event filters |
+| `GlobalSearch` | `components/GlobalSearch.tsx` | Debounced message-search box in the Chats header, with all-sessions / current-session scope |
+| `PluginInstances` | `components/PluginInstances.tsx` | Per-plugin instance list: create / edit / delete and secret regeneration |
| `ErrorBoundary` | `components/ErrorBoundary.tsx` | Top-level React error boundary wrapping the whole app |
| `GithubIcon` | `components/GithubIcon.tsx` | Inline brand SVG |
+Chat-specific pieces live one level down in `components/chats/`: `MessageBody` (WhatsApp text
+formatting + link detection) and `MediaLightbox` (the media viewer, built on
+`yet-another-react-lightbox`).
+
Pages live under `dashboard/src/pages/`, each as a `*.tsx` + `*.css` pair (e.g. `Sessions.tsx` +
`Sessions.css`). Pages are lazy-loaded in `App.tsx` via `React.lazy` + `Suspense`.
@@ -401,9 +415,11 @@ library — those visuals are composed directly with `div`s and the page's own C
## 17.5 State Management
There is **no Zustand store** (and no global client-state library). Server data is owned by
-**TanStack Query** (`@tanstack/react-query`); the only other shared state is two small React Context
-providers — `useRole` (the authenticated key's role) and `useTheme` (mode, persisted to
-`localStorage`).
+**TanStack Query** (`@tanstack/react-query`); the only other shared state lives in the two React
+Context providers in the app — `RoleProvider` (the authenticated key's role, read through the
+`useRole` hook) and `ToastProvider` (transient notifications). Theme mode is deliberately _not_ a
+context: `useTheme` is a plain hook that persists to `localStorage` and writes one attribute on
+`<html>` (see §17.7).
### API client — raw payloads, no `{ data }` envelope
@@ -615,16 +631,19 @@ The dev server listens on **2886** and proxies `/api` to the API on `2785`. The
on **`/socket.io`** (socket.io's transport path) with `ws: true` — _not_ `/ws`. There is no `@`
import alias and no custom `manualChunks`/Radix vendor split; code-splitting is handled by the
per-page `React.lazy` imports in `App.tsx`. The build-time version (`__APP_VERSION__`) is injected
-from `package.json` via `define`.
+via `define` from the **root** `package.json` — the file a release bumps — resolved relative to the
+config file rather than `process.cwd()`, because the dashboard is normally built from inside
+`dashboard/`, where a cwd-relative read picks up the release-untouched `dashboard/package.json`
+instead. `APP_VERSION` in the environment still overrides it.
```typescript
// vite.config.ts
import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
-const { version: pkgVersion } = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf-8')) as {
+// Root package.json, resolved from this file — NOT process.cwd().
+const { version: pkgVersion } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8')) as {
version: string;
};
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 710089396..d949795a4 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -20,7 +20,7 @@ OpenWA ships five official, hand-written client libraries for the REST API. They
- **It is a request/response client, not an event SDK.** There is no WebSocket, EventEmitter, or `client.on(...)`. To receive inbound messages and acks, register a webhook (the `webhooks` resource) and host your own receiver, or connect to the real-time Socket.IO API directly (see [API Specification §6.5](./06-api-specification.md)).
- **Typed errors.** Non-2xx responses raise/throw a typed error mapped from the HTTP status (`401/403/404/409/429/501`), plus a timeout error — all `instanceof`/`catch`-checkable. See each language's Error Handling subsection.
- **Injectable transport.** The HTTP layer is replaceable (`fetch` in JS, an `httpx` transport in Python, a Guzzle client in PHP) — the extension point for retry/observability middleware and for testing without the network.
-- **Safe by default.** Redirects are never followed (so the API key is never re-sent to a redirect target), the auth/JSON headers always take precedence over caller-supplied defaults, path segments are percent-encoded, a base-URL path prefix (e.g. behind a reverse proxy at `/v1`) is preserved, and there is a default 30s per-request timeout. **No automatic retries** — wrap calls in your own backoff if you need them (especially for `429`).
+- **Safe by default.** Redirects are never followed (so the API key is never re-sent to a redirect target), the auth/JSON headers always take precedence over caller-supplied defaults, path segments are percent-encoded, a base-URL path prefix (e.g. behind a reverse proxy at `/v1`) is preserved, and there is a default 30s per-request timeout. **No automatic retries by default** — in JS, Python, PHP, and Java wrap calls in your own backoff if you need them (especially for `429`); the Go SDK additionally ships an opt-in `WithRetry(RetryPolicy)` that never replays a `POST` after a network error and limits `POST` retries to `429`/`503`.
### Resource Coverage
@@ -29,19 +29,22 @@ All five SDKs expose the same fluent surface:
| Resource | Methods |
| --- | --- |
| `sessions` | list, get, create, delete, start, stop, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, history, reactions, sendBulk, batchStatus, cancelBatch |
-| `contacts` | list, get, check, profilePicture, phone, block, unblock |
-| `groups` | list, get, create, add/remove/promote/demoteParticipants, setSubject, setDescription, leave, inviteCode, revokeInviteCode |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, sendBulk, batchStatus, cancelBatch |
+| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
+| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
| `chats` | list, markRead, markUnread, delete, sendState |
| `labels` | list, get, forChat, addToChat, removeFromChat *(WhatsApp Business)* |
| `channels` | list, get, messages, subscribe, unsubscribe *(Newsletters)* |
| `catalog` | info, products, product, sendProduct, sendCatalog *(WhatsApp Business)* |
-| `status` | list, fromContact, sendText, sendImage, sendVideo, delete *(Stories)* |
+| `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 operator/admin-only server modules — `docker`, `metrics`, `infra`, `plugins`, `mcp` — are intentionally **not** exposed in the SDKs; all user-facing resources above are. Methods that require an `OPERATOR`-level key are annotated **OPERATOR** in the per-language tables below.
+> 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.
## 18.2 TypeScript / JavaScript SDK
@@ -109,7 +112,7 @@ The constructor takes a single `OpenWAClientOptions` object. `baseUrl` and `apiK
### Resources & Methods
-All resources are accessed as properties on the client (`client.<resource>.<method>`). Every method returns a `Promise`. Methods marked **OPERATOR** require an API key with the `OPERATOR` role; a non-operator key receives a `403` (`OpenWAForbiddenError`).
+All resources are accessed as properties on the client (`client.<resource>.<method>`). Every method returns a `Promise`. Methods marked **OPERATOR** require an `OPERATOR`-level API key (an `ADMIN` key satisfies it); a `VIEWER` key receives a `403` (`OpenWAForbiddenError`).
The top-level client also exposes:
@@ -126,11 +129,11 @@ The top-level client also exposes:
| `get` | `get(id)` | Get a single session by id. |
| `create` | `create(body)` | Create a new session (`body.name` required). **OPERATOR** |
| `delete` | `delete(id)` | Delete a session. **OPERATOR** |
-| `start` | `start(id)` | Start a session and initialize the WhatsApp connection. |
-| `stop` | `stop(id)` | Stop a session and disconnect gracefully. |
-| `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). |
-| `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). |
-| `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. |
+| `start` | `start(id)` | Start a session and initialize the WhatsApp connection. **OPERATOR** |
+| `stop` | `stop(id)` | Stop a session and disconnect gracefully. **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`
@@ -138,22 +141,24 @@ The top-level client also exposes:
| Method | Signature | Description |
| --- | --- | --- |
| `list` | `list(sessionId, query?)` | List messages (filter by chat/sender); returns `{ messages, total }`. |
-| `sendText` | `sendText(sessionId, { chatId, text })` | Send a text message (`text` max 4096 chars). |
-| `sendImage` | `sendImage(sessionId, body)` | Send an image (`url` or `base64`). |
-| `sendVideo` | `sendVideo(sessionId, body)` | Send a video (`url` or `base64`). |
-| `sendAudio` | `sendAudio(sessionId, body)` | Send an audio file (`url` or `base64`). |
-| `sendDocument` | `sendDocument(sessionId, body)` | Send a document (`url` or `base64`; `filename` recommended). |
-| `sendSticker` | `sendSticker(sessionId, body)` | Send a sticker (`url` or `base64`). |
-| `sendLocation` | `sendLocation(sessionId, body)` | Send a location (`{ chatId, latitude, longitude, description? }`). |
-| `sendContact` | `sendContact(sessionId, body)` | Send a contact card. |
-| `sendTemplate` | `sendTemplate(sessionId, body)` | Render and send a stored message template. |
-| `reply` | `reply(sessionId, body)` | Reply to a specific message. |
-| `forward` | `forward(sessionId, body)` | Forward a message to another chat. |
-| `react` | `react(sessionId, body)` | React to a message (empty `reaction` removes it). |
-| `delete` | `delete(sessionId, body)` | Delete a message. |
+| `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`. |
+| `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** |
@@ -167,6 +172,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| `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** |
@@ -178,12 +184,15 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| `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** |
@@ -202,8 +211,8 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| Method | Signature | Description |
| --- | --- | --- |
-| `list` | `list(sessionId)` | List all webhooks for a session. |
-| `get` | `get(sessionId, id)` | Get a single webhook by id. |
+| `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** |
@@ -245,6 +254,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| --- | --- | --- |
| `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** |
@@ -252,16 +262,36 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
> This is WhatsApp "Status/Stories", distinct from session lifecycle status.
+#### `search`
+
+| 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. |
-| `get` | `get(sessionId, id)` | Get a single template by id. |
+| `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** |
+
+#### `calls`
+
+| Method | Signature | Description |
+| --- | --- | --- |
+| `rejectCall` | `rejectCall(sessionId, callId)` | Reject a ringing incoming call (`callId` comes from the `call.received` event). **OPERATOR** |
+
#### `health`
| Method | Signature | Description |
@@ -320,7 +350,7 @@ try {
### Notable Behaviors
- **Redirects are never followed.** The transport uses `redirect: 'manual'`, so a `3xx` surfaces to the caller as an error (via `OpenWAApiError`) rather than being followed — this guarantees the `X-API-Key` header is never re-sent to a redirect target (potentially a different origin).
-- **Auth and JSON headers take precedence.** Request headers are merged in the order `Content-Type: application/json` → `defaultHeaders` → per-call headers → `X-API-Key`. The `X-API-Key` is applied last and cannot be overridden; `Content-Type` defaults to JSON.
+- **Auth and JSON headers take precedence.** Request headers are merged in the order `defaultHeaders` → per-call headers → `Content-Type: application/json` → `X-API-Key`. Both `Content-Type` and `X-API-Key` are applied last, so neither can be overridden by a caller-supplied header.
- **Path segments are percent-encoded.** Ids (session, chat, message, etc.) are encoded so a value cannot break out of its path position, while keeping the WhatsApp-safe characters `@`, `:`, and `+` readable (e.g. `[email protected]`).
- **Base-URL path prefix is preserved.** A `baseUrl` such as `https://gateway.example.com/v1` keeps its `/v1` prefix on every request; only a trailing slash is trimmed.
- **No automatic retries.** A failed request rejects immediately — the SDK does not retry, even on `429`. Wrap calls in your own backoff if you need retries.
@@ -422,13 +452,13 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| --- | --- | --- |
| `list` | `list() -> list[SessionResponse]` | List all sessions. |
| `get` | `get(session_id) -> SessionResponse` | Get one session. |
-| `create` | `create(body) -> SessionResponse` | Create a session (`body["name"]` required). |
-| `delete` | `delete(session_id) -> None` | Delete a session. |
-| `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. |
-| `stop` | `stop(session_id) -> SessionResponse` | Stop a session. |
-| `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. |
-| `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. |
-| `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. |
+| `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** |
+| `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`
@@ -436,22 +466,24 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| Method | Signature | Description |
| --- | --- | --- |
| `list` | `list(session_id, query=None) -> MessageListResponse` | List stored messages. |
-| `send_text` | `send_text(session_id, body) -> MessageResponse` | Send a text message. |
-| `send_image` | `send_image(session_id, body) -> MessageResponse` | Send an image. |
-| `send_video` | `send_video(session_id, body) -> MessageResponse` | Send a video. |
-| `send_audio` | `send_audio(session_id, body) -> MessageResponse` | Send audio. |
-| `send_document` | `send_document(session_id, body) -> MessageResponse` | Send a document. |
-| `send_sticker` | `send_sticker(session_id, body) -> MessageResponse` | Send a sticker. |
-| `send_location` | `send_location(session_id, body) -> MessageResponse` | Send a location. |
-| `send_contact` | `send_contact(session_id, body) -> MessageResponse` | Send a contact card. |
-| `send_template` | `send_template(session_id, body) -> MessageResponse` | Send a stored template. |
-| `reply` | `reply(session_id, body) -> MessageResponse` | Reply to a message. |
-| `forward` | `forward(session_id, body) -> MessageResponse` | Forward a message. |
-| `react` | `react(session_id, body) -> SuccessResult` | React to a message. |
-| `delete` | `delete(session_id, body) -> SuccessResult` | Delete a message. |
+| `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. |
+| `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** |
@@ -463,6 +495,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| `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** |
@@ -474,12 +507,15 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| `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** |
@@ -498,8 +534,8 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| Method | Signature | Description |
| --- | --- | --- |
-| `list` | `list(session_id) -> list[WebhookResponse]` | List webhooks. |
-| `get` | `get(session_id, webhook_id) -> WebhookResponse` | Get one webhook. |
+| `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** |
@@ -541,21 +577,42 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| --- | --- | --- |
| `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 |
+| --- | --- | --- |
+| `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. |
-| `get` | `get(session_id, template_id) -> TemplateRecord` | Get one template. |
+| `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** |
+#### `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** |
+| `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 |
+| --- | --- | --- |
+| `reject_call` | `reject_call(session_id, call_id) -> SuccessResult` | Reject a ringing incoming call. **OPERATOR** |
+
#### `client.health`
| Method | Signature | Description |
@@ -658,7 +715,7 @@ $result = $client->messages->sendText('my-session', [
echo $result['messageId'];
```
-The entry class is `OpenWA\Client`. It validates that `baseUrl` and `apiKey` are present (throwing `OpenWAException` otherwise), constructs the shared HTTP transport, and exposes each resource as a public property: `$client->sessions`, `$client->messages`, `$client->contacts`, `$client->groups`, `$client->webhooks`, `$client->chats`, `$client->status`, `$client->health`, `$client->labels`, `$client->channels`, `$client->catalog`, `$client->templates`.
+The entry class is `OpenWA\Client`. It validates that `baseUrl` and `apiKey` are present (throwing `OpenWAException` otherwise), constructs the shared HTTP transport, and exposes each resource as a public property: `$client->sessions`, `$client->messages`, `$client->search`, `$client->contacts`, `$client->groups`, `$client->webhooks`, `$client->chats`, `$client->status`, `$client->health`, `$client->labels`, `$client->channels`, `$client->catalog`, `$client->templates`, `$client->profile`, `$client->calls`.
Two escape hatches sit on the client itself:
@@ -691,13 +748,13 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| --- | --- | --- |
| `list` | `list(): array` | List all sessions. |
| `get` | `get(string $id): array` | Get one session. |
-| `create` | `create(array $body): array` | Create a session (`$body['name']` required). |
-| `delete` | `delete(string $id): void` | Delete a session. |
-| `start` | `start(string $id): array` | Start a session. |
-| `stop` | `stop(string $id): array` | Stop a session. |
-| `forceKill` | `forceKill(string $id): array` | Force-kill a session. |
-| `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. |
-| `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. |
+| `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** |
+| `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`
@@ -705,22 +762,24 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| Method | Signature | Description |
| --- | --- | --- |
| `list` | `list(string $sessionId, array $query = []): array` | List stored messages. |
-| `sendText` | `sendText(string $sessionId, array $body): array` | Send a text message (`send-text`). |
-| `sendImage` | `sendImage(string $sessionId, array $body): array` | Send an image. |
-| `sendVideo` | `sendVideo(string $sessionId, array $body): array` | Send a video. |
-| `sendAudio` | `sendAudio(string $sessionId, array $body): array` | Send audio. |
-| `sendDocument` | `sendDocument(string $sessionId, array $body): array` | Send a document. |
-| `sendSticker` | `sendSticker(string $sessionId, array $body): array` | Send a sticker. |
-| `sendLocation` | `sendLocation(string $sessionId, array $body): array` | Send a location. |
-| `sendContact` | `sendContact(string $sessionId, array $body): array` | Send a contact card. |
-| `sendTemplate` | `sendTemplate(string $sessionId, array $body): array` | Send a stored template. |
-| `reply` | `reply(string $sessionId, array $body): array` | Reply to a message. |
-| `forward` | `forward(string $sessionId, array $body): array` | Forward a message. |
-| `react` | `react(string $sessionId, array $body): array` | React to a message. |
-| `delete` | `delete(string $sessionId, array $body): array` | Delete a message. |
+| `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. |
+| `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** |
@@ -732,6 +791,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| `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** |
@@ -743,12 +803,15 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| `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** |
@@ -767,8 +830,8 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| Method | Signature | Description |
| --- | --- | --- |
-| `list` | `list(string $sessionId): array` | List webhooks. |
-| `get` | `get(string $sessionId, string $id): array` | Get one webhook. |
+| `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** |
@@ -810,21 +873,42 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| --- | --- | --- |
| `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 |
+| --- | --- | --- |
+| `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. |
-| `get` | `get(string $sessionId, string $templateId): array` | Get one template. |
+| `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** |
+
+#### `calls`
+
+| 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 |
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index e18e0b207..8cf3ef23b 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -19,7 +19,7 @@
| Component | Status | Notes |
|-----------|--------|-------|
-| **Sandboxed execution** | ✅ Implemented | Untrusted (disk-loaded) plugins run in a `worker_thread`; see [23 — Plugin Sandboxing](./23-plugin-sandboxing.md). No `vm2`. |
+| **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 |
@@ -52,7 +52,7 @@ flowchart TB
end
```
-1. **Isolation** - Untrusted plugins (anything loaded from the `plugins/` directory) run in a `worker_thread`, separate from in-process built-ins; capability calls round-trip to the host. First-party built-ins (the engine adapters) run in-process. A `worker_thread` is V8-context isolation in the same OS process, not an OS-level sandbox — see [23 — Plugin Sandboxing](./23-plugin-sandboxing.md) for what it does and does not guarantee, and the OS-containment guidance.
+1. **Isolation** - Untrusted plugins (anything loaded from the `plugins/` directory) run in a `worker_thread`, separate from in-process built-ins; capability calls round-trip to the host. First-party built-ins (the engine adapters) run in-process. A `worker_thread` is V8-context isolation in the same OS process, not an OS-level sandbox — see [30 — Plugin Sandboxing](./30-plugin-sandboxing.md) for what it does and does not guarantee, and the OS-containment guidance.
2. **Extensibility** - Easy to add new features
3. **Safety** - Capability permissions are enforced at the call boundary (`assertPermission` throws `PluginCapabilityError`), session scope is enforced per call, and outbound HTTP is SSRF-guarded.
4. **Performance** - Lazy loading, minimal overhead
@@ -110,7 +110,8 @@ plugins/
`id`, `name`, `version`, `type`, and `main` are required; the rest are optional. There is **no**
`types` field and **no** version-compatibility (`min`/`maxVersion`) check — the loader does not gate on
-a host version. The config schema is the top-level `configSchema` (note: not nested under `config`).
+a host version, except for the SDK-major check applied to a manifest that declares `ingress` (see the
+`sdkVersion` row). The config schema is the top-level `configSchema` (note: not nested under `config`).
```json
{
@@ -157,12 +158,15 @@ a host version. The config schema is the top-level `configSchema` (note: not nes
| `id` | ✅ | Unique identifier (also the plugin's on-disk directory name) |
| `name` | ✅ | Display name |
| `version` | ✅ | Semver |
-| `type` | ✅ | One of `engine`, `storage`, `queue`, `auth`, `extension` |
+| `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 |
+| `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) |
@@ -275,10 +279,17 @@ export interface PluginContext {
// Register a hook handler (optionally with a priority; lower runs first).
registerHook: (event: HookEvent, handler: HookHandler, priority?: number) => void;
+ // Claim one of the manifest's declared ingress routes (requires 'webhook:ingress'). Sandboxed
+ // plugins only — an in-process built-in that calls it throws.
+ 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, net.allow-scoped)
+ 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'
}
export interface PluginLogger {
@@ -289,15 +300,20 @@ export interface PluginLogger {
}
```
-There is **no** `ctx.api`, `ctx.router`, or `ctx.events` — plugins do not mount HTTP routes or get an
-event emitter. Hook handlers use the host `HookContext` / `HookResult` shape (see §19.5), not a
-`{ continue, modified }` shape.
+There is **no** `ctx.api`, `ctx.router`, or `ctx.events` — a plugin never binds a port, mounts its own
+route, or gets an event emitter. Inbound HTTP reaches a plugin only through `ctx.registerWebhook`, which
+claims a route the manifest already declared under `ingress`: the host owns the URL (mounted under
+`ingress`), verifies the provider signature, dedups and enqueues, then dispatches to the handler — see
+[25 — Integration Fabric](./25-integration-fabric.md). A sandboxed plugin additionally gets
+`ctx.registerSearchProvider` for answering global-search queries — see
+[27 — Writing a Search-Provider Plugin](./27-plugin-search-providers.md). Hook handlers use the host
+`HookContext` / `HookResult` shape (see §19.5), not a `{ continue, modified }` shape.
### Capability facade
-A plugin reaches WhatsApp, the engine, and the network **only** through these three namespaces. Each
-call is gated by the matching declared permission (and, for `messages`/`engine`, the session scope) —
-a missing grant throws a `PluginCapabilityError`.
+A plugin reaches WhatsApp, the engine, and the network **only** through these namespaces. Each call is
+gated by the matching declared permission (and, for everything except `net`, the session scope) — a
+missing grant throws a `PluginCapabilityError`.
```typescript
// ctx.messages — requires 'messages:send'. Routes through MessageService (persistence preserved).
@@ -313,12 +329,32 @@ export interface PluginEngineReadCapability {
getContactById(sessionId: string, contactId: string): Promise<...>;
checkNumberExists(sessionId: string, phone: string): Promise<...>;
getChats(sessionId: string): Promise<...>;
+ // Recent messages for a chat, both directions (history backfill). `limit` is clamped host-side to 1-100.
+ getChatHistory(sessionId: string, chatId: string, limit?: number, includeMedia?: boolean): Promise<...>;
+ // Canonical form of a chat id: resolves a known '@lid' privacy id to its stable '<phone>@c.us',
+ // otherwise returns the id unchanged (best-effort).
+ canonicalChatId(sessionId: string, chatId: string): Promise<string>;
}
-// ctx.net — requires 'net:fetch'. Always through the host SSRF guard, scoped to manifest net.allow.
+// ctx.net — requires 'net:fetch'. Always through the host SSRF guard, scoped to the effective host
+// allowlist (manifest net.allow + the hosts of the net.allowConfigHosts config keys).
export interface PluginNetCapability {
fetch(url: string, init?: PluginNetRequestInit): Promise<PluginNetResponse>;
}
+
+// ctx.conversations / ctx.handover / ctx.mappings — all require 'conversation:send'. The normalized
+// outbound surface an integration adapter uses; sends translate host-side to MessageService.
+export interface PluginConversationsCapability {
+ send(env: ConversationSendEnvelope): Promise<unknown>;
+}
+export interface PluginHandoverCapability {
+ set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;
+}
+export interface PluginMappingsCapability {
+ upsert(key: { sessionId: string; chatId: string; instanceId: string }, providerConversationId: string): Promise<void>;
+ get(key: { sessionId: string; chatId: string; instanceId: string }): Promise<... | null>;
+ getByProvider(instanceId: string, providerConversationId: string): Promise<... | null>;
+}
```
`ctx.net.fetch` returns a serializable response (`{ ok, status, statusText, headers, body }`, body as
@@ -453,7 +489,9 @@ adapters; see §19.7), then scans the plugins directory (`plugins.dir`, default
sub-directory with a `manifest.json` it reads the manifest, validates the required fields
(`id`/`name`/`version`/`type`/`main`), and records an `INSTALLED` plugin plus a persisted registry
entry — **without running any plugin code**. Persisted config and per-session activation/config are
-read back so an operator's choices survive a restart. There is **no** version-compatibility check.
+read back so an operator's choices survive a restart. There is **no** host version-compatibility check;
+the one version gate is `validateIngressManifest`, which refuses a manifest declaring `ingress` whose
+`sdkVersion` major is not the supported Integration SDK major (`1`).
> Loading a plugin from disk never runs it: a load always yields `INSTALLED`. Enabling is a separate
> step that runs the lifecycle, and happens either on an explicit ADMIN action or — for a plugin the
@@ -481,7 +519,7 @@ double-enable, and engines must match the configured active engine):
drive `onLoad`/`onEnable` over the channel. Capability calls and hook dispatches round-trip to the
host, which runs the **same** permission + session-scope checks. Lifecycle calls are bounded by a
30 s timeout and hooks by a 5 s timeout; a failure tears the worker back down. See
- [23 — Plugin Sandboxing](./23-plugin-sandboxing.md).
+ [30 — Plugin Sandboxing](./30-plugin-sandboxing.md).
**Disable / unload / uninstall.** `disablePlugin` runs `onDisable` (force-terminating the worker for a
sandboxed plugin, even if `onDisable` hangs or throws) and unregisters the plugin's hooks. `onModuleDestroy`
@@ -492,10 +530,11 @@ for a sandboxed plugin it runs in the worker between `onDisable` and terminate (
NOT fire `onUnload` — disable is reversible and its cleanup hook is `onDisable`).
**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger, plugin-scoped
-storage, `registerHook` (wrapped with the per-session activation gate), the live `config` getter, and
-the permission-checked `messages` / `engine` / `net` capabilities. The capability methods call
-`assertPermission` (and, for messages/engine, `resolveEngine` → `assertSessionAllowed`) before doing any
-work, so a missing grant or out-of-scope session fails fast with a `PluginCapabilityError`.
+storage, `registerHook` (wrapped with the per-session activation gate), `registerWebhook`, the live
+`config` getter, and the permission-checked `messages` / `engine` / `net` / `conversations` / `handover` /
+`mappings` capabilities. The capability methods call `assertPermission` before doing any work, and — for
+everything but `net` — `assertSessionActive` → `assertSessionAllowed` on the session they act on, so a
+missing grant or out-of-scope session fails with a `PluginCapabilityError`.
> ⚠️ **`ctx.storage` is plugin-scoped, not per-session — unlike `ctx.config`.** `ctx.config` is merged
> automatically for the firing session, but `ctx.storage` is a single namespace shared across **all** of a
@@ -592,26 +631,30 @@ URL / catalog), not an npm/github source descriptor.
### Permission model
-There are exactly **three** capability permissions, declared in the manifest `permissions` array and
-enforced at the capability boundary:
+There are exactly **five** capability permissions, declared in the manifest `permissions` array — four
+enforced at the capability boundary, `webhook:ingress` at load and at route subscription:
```typescript
-// src/core/plugins/plugin.interfaces.ts
+// src/core/plugins/plugin.interfaces.ts (doc comments condensed)
export const PluginCapabilityPermission = {
/** ctx.messages.* — send / reply on a session. */
MESSAGES_SEND: 'messages:send',
- /** ctx.engine.* — read-only engine queries (group info, contacts, chats, number check). */
+ /** ctx.engine.* — read-only engine queries (group info, contacts, chats, history, number check). */
ENGINE_READ: 'engine:read',
/** ctx.net.fetch — SSRF-guarded outbound HTTP, scoped to the manifest net.allow host list. */
NET_FETCH: 'net:fetch',
+ /** ctx.registerWebhook — claim an inbound ingress route declared in the manifest. */
+ WEBHOOK_INGRESS: 'webhook:ingress',
+ /** ctx.conversations.send plus ctx.handover.* and ctx.mappings.* — the normalized outbound surface. */
+ CONVERSATION_SEND: 'conversation:send',
} as const;
```
-There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement lives in the loader:
-each capability method calls `assertPermission(manifest, permission)` before doing any work, and a
-plugin whose manifest does not declare the matching permission (or declares none) is rejected with a
-`PluginCapabilityError`:
+There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement of the four
+capability-facade permissions lives in the loader: each capability method calls
+`assertPermission(manifest, permission)` before doing any work, and a plugin whose manifest does not
+declare the matching permission (or declares none) is rejected with a `PluginCapabilityError`:
```typescript
// src/core/plugins/plugin-loader.service.ts (paraphrased)
@@ -625,13 +668,26 @@ private assertPermission(manifest: PluginManifest, permission: PluginCapabilityP
}
```
+`webhook:ingress` is the exception — nothing passes it to `assertPermission`. It is enforced earlier, in
+two places: at **load**, `validateIngressManifest` throws when a manifest declares `ingress` routes without
+the permission, so the plugin never loads; and at the **ingress-subscribe guard**, a route claim from a
+worker whose manifest lacks the permission is silently dropped (no `PluginCapabilityError`) and the plugin
+simply owns no routes.
+
Two further checks apply on top of the permission:
-- **Session scope.** `messages` and `engine` calls run `assertSessionAllowed(manifest, sessionId)` —
- the plugin may only act on sessions in its manifest `sessions` list (`['*']` = all). The `sessionId`
- comes from the plugin, so this is the security boundary; it is static (editing config can't widen it).
-- **Network allowlist.** `ctx.net.fetch` additionally requires the target host to be in `manifest.net.allow`,
- and the request always passes through the SSRF guard (which blocks internal IPs even for an allowlisted host).
+- **Session scope.** Every capability but `net` is session-scoped through `assertSessionActive`, which
+ requires **both** that the manifest `sessions` list admits the session (`assertSessionAllowed`; `['*']` =
+ all) and that the operator has activated the plugin for it. Most verbs run it up front, on the
+ `sessionId` the plugin passed; `ctx.mappings.getByProvider` takes no `sessionId`, so it runs the check
+ after the lookup, on the `sessionId` of the row it found (and returns `null` when there is none) — either
+ way an out-of-scope session is never reachable. The `sessionId` comes from the plugin, so this is the
+ security boundary; the manifest half is static (editing config can't widen it).
+- **Network allowlist.** `ctx.net.fetch` additionally requires the target host to be on the plugin's
+ **effective** allowlist: `manifest.net.allow` plus the host of every `net.allowConfigHosts` config key
+ that resolves to an https URL, taken across the base config **and** every per-session override. A host
+ admitted only through `allowConfigHosts` is therefore allowed while absent from `net.allow`. The request
+ always passes through the SSRF guard (which blocks internal IPs even for an allowlisted host).
### Sandboxed execution
@@ -652,7 +708,7 @@ tier automatically. Key properties:
This is V8-context isolation in the same OS process, not an OS-level sandbox: a worker can still reach
Node built-ins (`fs`, `process`, sockets). For genuinely untrusted plugins, combine it with OS
containment (the shipped Docker image runs read-only rootfs, non-root, `cap_drop: ALL`). See
-[23 — Plugin Sandboxing](./23-plugin-sandboxing.md) for the full security model and author rules.
+[30 — Plugin Sandboxing](./30-plugin-sandboxing.md) for the full security model and author rules.
---
diff --git a/docs/20-community-guidelines.md b/docs/20-community-guidelines.md
index 0f41e2e33..879cd0002 100644
--- a/docs/20-community-guidelines.md
+++ b/docs/20-community-guidelines.md
@@ -135,6 +135,8 @@ refactor(database): migrate to TypeORM repository pattern
2. **PR Description Template:**
+ GitHub pre-fills `.github/pull_request_template.md`:
+
```markdown
## Description
@@ -142,31 +144,30 @@ Brief description of changes
## Type of Change
-- [ ] Bug fix (non-breaking change which fixes an issue)
-- [ ] New feature (non-breaking change which adds functionality)
-- [ ] Breaking change (fix or feature that causes existing functionality to change)
+- [ ] Bug fix
+- [ ] New feature
+- [ ] Breaking change
- [ ] Documentation update
-## Testing
+## Checklist
+
+- [ ] Tests added/updated
+- [ ] Documentation updated
+- [ ] Lint passes
+- [ ] Self-reviewed
-Describe how you tested your changes
+## Screenshots (if applicable)
-## Checklist
+## Related Issues
-- [ ] My code follows the project's style guidelines
-- [ ] I have performed a self-review of my code
-- [ ] I have commented my code, particularly in hard-to-understand areas
-- [ ] I have made corresponding changes to the documentation
-- [ ] My changes generate no new warnings
-- [ ] I have added tests that prove my fix is effective or feature works
-- [ ] New and existing unit tests pass locally with my changes
+Closes #
```
3. **Review Process:**
- - At least one maintainer approval required
- - All CI checks must pass
- - Address all review comments
- - Squash commits if requested
+ - CI (`.github/workflows/ci.yml`) runs on every pull request targeting `main` or `develop`
+ - A maintainer reviews the change and merges it
+ - Address review comments
+ - Keep the PR focused on one logical change
### Code Style
@@ -240,70 +241,38 @@ Discussions.
### Bug Reports
-Use the bug report template:
-
-```markdown
-## Bug Description
-
-Clear and concise description of the bug
-
-## Environment
-
-- OpenWA Version:
-- Node.js Version:
-- OS:
-- Docker Version (if applicable):
-- Database: SQLite / PostgreSQL
-
-## Steps to Reproduce
-
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
-
-## Expected Behavior
-
-What you expected to happen
-
-## Actual Behavior
-
-What actually happened
-
-## Screenshots/Logs
+Blank issues are disabled — GitHub presents the **Bug report** form
+(`.github/ISSUE_TEMPLATE/bug_report.yml`). Required fields:
-If applicable, add screenshots or logs
+| Field | Notes |
+| ------------------ | ---------------------------------------------------------------------------- |
+| Pre-flight | Both checkboxes: searched for duplicates, and on the latest released version |
+| OpenWA version | e.g. `0.2.1` (shown on the dashboard Login screen) or a commit SHA |
+| Deployment | Docker Compose / Docker (manual run) / Bare metal (npm) / Other |
+| Database | SQLite (default) / PostgreSQL |
+| What happened? | The bug and its impact |
+| Steps to reproduce | Exact steps, including the API call or dashboard action |
-## Additional Context
-
-Any other relevant information
-```
+Optional but valuable: **WhatsApp engine** (defaults to `whatsapp-web.js`), **Expected
+behavior**, **Relevant logs** (redact API keys and secrets), and **Environment /
+additional context**.
### Feature Requests
-Use the feature request template:
-
-```markdown
-## Feature Description
-
-Clear description of the feature you'd like
-
-## Use Case
-
-Why do you need this feature? What problem does it solve?
-
-## Proposed Solution
+The **Feature request** form (`.github/ISSUE_TEMPLATE/feature_request.yml`) asks for the
+problem first — describe what you are trying to do and what gets in the way, since the
+best solution isn't always the one initially imagined.
-If you have a solution in mind, describe it here
+| Field | Notes |
+| ----------------------- | ----------------------------------------------------------- |
+| Pre-flight | Required: searched existing issues, not already requested |
+| Problem / motivation | Required: what you're trying to do and what blocks it today |
+| Proposed solution | Optional: API shape, dashboard behavior, config, etc. |
+| Alternatives considered | Optional |
+| Scope | Acknowledgment that some features are limited by the engine |
-## Alternatives Considered
-
-Other solutions you've considered
-
-## Additional Context
-
-Any other relevant information, mockups, or examples
-```
+The scope checkbox matters: capabilities such as interactive Buttons / List messages are
+not supported on whatsapp-web.js, the default engine.
### Issue Labels
@@ -345,27 +314,14 @@ Categories:
- **Show and Tell**: Share your projects using OpenWA
- **General**: General discussion
-### Discord Server (Optional)
-
-Real-time chat for:
-
-- Quick questions
-- Community support
-- Development discussions
-
-Channels:
-
-- `#general` - General discussion
-- `#support` - Help with OpenWA
-- `#development` - Development discussions
-- `#showcase` - Share your projects
-- `#off-topic` - Non-OpenWA discussions
-
### Support Priority
1. **GitHub Issues** - Bug reports and feature requests
2. **GitHub Discussions** - Questions and general discussion
-3. **Discord** - Quick questions and community chat
+
+There is no official real-time chat server. The issue-template contact links
+(`.github/ISSUE_TEMPLATE/config.yml`) point only to the documentation and to the private
+security-advisory form.
## 20.5 Governance
@@ -375,90 +331,52 @@ Channels:
flowchart TB
A[Proposal] --> B{Type?}
B -->|Minor| C[Maintainer Decision]
- B -->|Major| D[RFC Process]
+ B -->|Major| D[Design Issue]
- D --> E[Community Discussion]
- E --> F[Voting Period]
- F --> G{Consensus?}
+ D --> E[Discussion in Thread]
+ E --> G{Approach Agreed?}
G -->|Yes| H[Implement]
G -->|No| I[Revise or Reject]
C --> H
```
-### RFC Process (Request for Comments)
-
-For major changes:
-
-1. **Create RFC** - Submit RFC in `rfcs/` directory
-2. **Discussion** - Community discusses for 2 weeks
-3. **Voting** - Maintainers vote
-4. **Decision** - Accept, revise, or reject
-5. **Implementation** - If accepted, implement
-
-RFC Template:
-
-```markdown
-# RFC: [Title]
-
-## Summary
-
-One paragraph explanation
-
-## Motivation
-
-Why are we doing this?
-
-## Detailed Design
-
-Technical details of the implementation
+### Design Discussions
-## Drawbacks
+There is no separate RFC repository or directory. For substantial architectural changes
+(new frameworks, large rewrites) — and for any change to REST response shapes or status
+codes, since the REST API is the public contract — open a GitHub Issue to align on the
+approach **before** investing the work. Maintainers label these `design`, and the issue
+thread is the design record.
-Why should we NOT do this?
+A design issue should cover:
-## Alternatives
+- **Summary** - one paragraph explaining the change
+- **Motivation** - the problem it solves, and for whom
+- **Proposed design** - the API, config, or schema surface it touches
+- **Alternatives** - other approaches considered, and why they were set aside
+- **Open questions** - what is still undecided
-What other designs have been considered?
+Once the approach is agreed, implementation proceeds as an ordinary pull request.
-## Unresolved Questions
+### Roles
-What related issues are out of scope?
-```
-
-### Maintainer Roles
-
-| Role | Responsibilities |
-| --------------- | ------------------------------------------- |
-| **Owner** | Final decision authority, project direction |
-| **Maintainer** | Code review, merge PRs, triage issues |
-| **Committer** | Merge own PRs after approval |
-| **Contributor** | Submit PRs, report issues |
-
-### Becoming a Maintainer
+| Role | Responsibilities |
+| --------------- | ----------------------------------------------------------------------------------- |
+| **Maintainer** | Triage and label issues, review and merge PRs, version stamping and release cutting |
+| **Contributor** | Submit PRs, report issues, take part in Discussions |
-Maintainer status is earned through:
-
-- Consistent quality contributions
-- Helpful community participation
-- Understanding of project goals
-- Positive collaboration
-
-Process:
-
-1. Nominated by existing maintainer
-2. Discussion among maintainers
-3. Unanimous approval required
+There is no tiered committer body and no documented nomination process.
## 20.6 Recognition
### Contributors
-All contributors are recognized in:
+Contributions are credited in:
-- `CONTRIBUTORS.md` file
-- Release notes
-- README acknowledgments
+- `CHANGELOG.md` - a "Thanks @handle." line on the entry describing the change
+- GitHub release notes, which are generated from that release's CHANGELOG section
+- The pull request and issue threads themselves
### Contribution Types
@@ -474,54 +392,45 @@ We value all contributions:
### Acknowledgment
-```markdown
-## Contributors
+A CHANGELOG entry carrying credit looks like this:
-Thanks to all the people who have contributed to OpenWA!
-
-<!-- ALL-CONTRIBUTORS-LIST:START -->
-<!-- ALL-CONTRIBUTORS-LIST:END -->
-
-This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification.
+```markdown
+- **Short summary of the user-visible change.** What was wrong, and what happens instead
+ now. Thanks @handle. (#1234)
```
+Security reporters are credited in the advisory and the release notes instead, unless they
+prefer to remain anonymous - see `SECURITY.md`.
+
## 20.7 Security Policy
+`SECURITY.md` at the repository root is the authoritative policy; it also carries
+hardening notes for operators. The summary below tracks it.
+
### Reporting Vulnerabilities
-**DO NOT** report security vulnerabilities through public GitHub issues.
+**DO NOT** report security vulnerabilities through public GitHub issues, discussions, or
+pull requests.
-Instead:
+Report privately through either channel:
-1. GitHub Security Advisories (private) — **preferred**:
+1. **GitHub Security Advisories** (preferred) — open a private report at
<https://github.com/rmyndharis/OpenWA/security/advisories/new>
-
-See [SECURITY.md](../SECURITY.md) for the authoritative policy.
-
-Include:
+2. **Email** — [email protected]
-- Type of vulnerability
-- Full paths of affected files
-- Step-by-step instructions to reproduce
-- Proof-of-concept or exploit code
-- Impact assessment
+Include, where possible:
-### Response Timeline
+- A description of the issue and its impact
+- Steps to reproduce or a proof of concept
+- Affected version(s) and deployment details (Docker / bare metal, database, engine)
-| Severity | Initial Response | Resolution Target |
-| -------- | ---------------- | ----------------- |
-| Critical | 24 hours | 7 days |
-| High | 48 hours | 14 days |
-| Medium | 7 days | 30 days |
-| Low | 14 days | 90 days |
+### What to Expect
-### Disclosure Policy
+No fixed response SLA is promised, but in practice:
-- We will acknowledge receipt within 48 hours
-- We will confirm the vulnerability and work on a fix
-- We will notify you when the fix is released
-- We will credit you in the security advisory (unless you prefer anonymity)
+- An acknowledgement, typically within a few days
+- An assessment, and — where applicable — a coordinated fix and release
+- Credit in the advisory / release notes, unless you'd prefer to remain anonymous
---
diff --git a/docs/21-glossary.md b/docs/21-glossary.md
index 0c1042b04..a3e1c364e 100644
--- a/docs/21-glossary.md
+++ b/docs/21-glossary.md
@@ -3,26 +3,26 @@
## A
### ACK (Acknowledgement)
-Delivery acknowledgment status. WhatsApp ACK levels:
-- `error` (-1): Failed to send
-- `pending` (0): Pending
-- `server` (1): Sent to WhatsApp server
-- `device` (2): Delivered to recipient device
-- `read` (3): Read by recipient
-- `played` (4): Media played (audio/video)
+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`
+- `2` DEVICE -> `delivered`
+- `3` READ -> `read`
+- `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 Adapter**: Memory, Redis
+- **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 stored in the `.wwebjs_auth/` folder. Includes cookies, session storage, and Chrome profile data.
+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
@@ -32,11 +32,10 @@ Node.js library for WhatsApp Web that uses WebSocket directly without a browser
### Broadcast
Sending the same message to multiple recipients. On WhatsApp, this differs from the native "Broadcast List" feature.
-### Bull
-A Redis-based Node.js job queue library. Used for:
-- Message queue (delayed sends)
-- Webhook delivery queue (retry mechanism)
-- Background tasks
+### 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
@@ -55,10 +54,10 @@ 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 + shadcn/ui.
+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)
-Queue that stores messages that failed after all retry attempts. Used for debugging and manual retry.
+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.
@@ -78,7 +77,7 @@ A system-emitted occurrence, for example:
## F
### Factory Pattern
-Design pattern used to create adapter instances based on configuration. Example: `DatabaseAdapterFactory.create()`.
+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
@@ -94,7 +93,7 @@ GitHub Container Registry - registry for storing Docker images. The OpenWA image
Browser mode that runs without a GUI. Puppeteer runs Chrome in headless mode.
### Health Check
-Endpoint to check system health. `/health` is public for basic status, `/health/detailed` requires an API key for full status.
+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.
@@ -102,7 +101,7 @@ An extension point that allows plugins to intercept and modify processing flows.
## I
### In-Memory
-Data stored in RAM. Fast but non-persistent. Used for cache in minimal deployments.
+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
@@ -110,7 +109,7 @@ Data stored in RAM. Fast but non-persistent. Used for cache in minimal deploymen
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. Used for webhook delivery and message scheduling.
+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
@@ -126,7 +125,7 @@ Icon library used in the dashboard. A fork of Feather Icons with more icons.
## M
### Message Queue
-Queue for asynchronous message delivery. Prevents rate limiting and ensures message ordering.
+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.
@@ -185,10 +184,9 @@ Limiting request volume over time to prevent abuse and WhatsApp bans.
### Redis
In-memory data store used for:
-- Caching
-- Message queue (with Bull)
-- Session storage
-- Real-time pub/sub
+- 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).
@@ -207,9 +205,6 @@ An instance of a WhatsApp Web connection. One phone number = one session.
### SQLite
Embedded database used as the default for minimal deployments.
-### shadcn/ui
-Component library for React used in the dashboard. Built on top of Radix UI.
-
### Strategy Pattern
Design pattern that allows selecting an algorithm/implementation at runtime. Used for pluggable adapters.
@@ -218,9 +213,6 @@ API documentation tool. OpenWA provides Swagger UI at `/api/docs`.
## T
-### Tailwind CSS
-Utility-first CSS framework used in the dashboard.
-
### TanStack Query
Library for data fetching and caching in React. Previously known as React Query.
@@ -257,11 +249,6 @@ Protocol for real-time bidirectional communication. Used for:
### 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).
-## Z
-
-### Zustand
-State management library for React used in the dashboard.
-
---
## Abbreviations
diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.md
index b80c1815f..2d1552cf1 100644
--- a/docs/22-n8n-integration.md
+++ b/docs/22-n8n-integration.md
@@ -82,6 +82,7 @@ Start workflows when WhatsApp events occur.
| `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 |
@@ -120,9 +121,10 @@ Start workflows when WhatsApp events occur.
> **Deduplication.** Every delivery includes `idempotencyKey` and `deliveryId` in the body **and** as the
> `X-OpenWA-Idempotency-Key` / `X-OpenWA-Delivery-Id` headers. `idempotencyKey` is **stable across retries**
-> of the same event, while `deliveryId` is unique per HTTP attempt. Because a webhook can be retried, add a
-> dedup step keyed on `idempotencyKey` (e.g. an n8n IF or "Remove Duplicates" node) so a retried delivery
-> isn't processed twice.
+> of the same event; `deliveryId` identifies one delivery to one webhook and is stable across that
+> delivery's retry attempts too — read the `X-OpenWA-Retry-Count` header for the attempt number. Because a
+> webhook can be retried, add a dedup step keyed on `idempotencyKey` (e.g. an n8n IF or "Remove Duplicates"
+> node) so a retried delivery isn't processed twice.
## Example Workflows
@@ -263,7 +265,7 @@ Always use the correct format for chat IDs:
### Message Not Sending
-1. Verify session status is "READY"
+1. Verify session status is `ready` (the API returns lowercase status values)
2. Check chat ID format is correct
3. Ensure recipient number exists on WhatsApp
4. Check message content isn't empty
@@ -308,7 +310,7 @@ docker run -it --rm \
## Related Documentation
- [OpenWA API Specification](./06-api-specification.md)
-- [Webhook System](./03-system-architecture.md#webhooks)
+- [Webhook System](./03-system-architecture.md#353-webhook-system)
- [n8n Appointment Booking Workflow](./examples/n8n-appointment-booking.md)
- [n8n Documentation](https://docs.n8n.io/)
diff --git a/docs/23-plugin-sandboxing.md b/docs/23-plugin-sandboxing.md
deleted file mode 100644
index 6c1734230..000000000
--- a/docs/23-plugin-sandboxing.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# 23 — Plugin Sandboxing
-
-OpenWA runs **untrusted plugins** (anything loaded from the plugins directory) in an isolated worker
-thread, separate from first-party built-ins (engines, bundled extensions) which run in-process. This
-page describes the security model honestly — what the sandbox guarantees and, just as important, what
-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 |
-
-The loader routes by tier automatically: a plugin registered programmatically is built-in; one loaded
-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 out is
- a `MessagePort`.
-- **Capability mediation.** A plugin can touch WhatsApp / the database **only** through
- `ctx.messages.*` / `ctx.engine.*` / `ctx.storage.*`, which round-trip to the host. The host runs
- each call through the same permission + session-scope checks an in-process plugin gets
- (`assertPermission` / declared `sessions`), so a sandboxed plugin can never exceed its declared
- manifest permissions. Verbs are allowlisted — a worker cannot invoke an arbitrary host method.
-- **Hook safety.** Hook handlers run in the worker and are dispatched with a **time budget**
- (`SANDBOX_HOOK_TIMEOUT_MS`, default 5s). A slow or wedged handler is skipped (`continue: true`) so
- it can never stall the host's hook chain.
-- **Resource & runaway containment.** Each worker has a heap cap (`maxOldGenerationSizeMb`, default
- 256). An OOM terminates the worker, not the host. A wedged **lifecycle** call (load/unload) times out
- and tears the worker down, and a crash rejects its in-flight calls — the host survives either way. A
- runaway **hook** handler (e.g. an infinite synchronous loop) is skipped on the hook timeout so it can't
- stall the host's hook chain, but the worker keeps running it (pegging a core) until the plugin is
- reloaded or hits the heap cap — it is contained to its own thread, not instantly force-killed.
-
-## What the sandbox does NOT guarantee
-
-> A `worker_thread` is a separate V8 context **in the same OS process, under the same user**. It is
-> not an OS-level sandbox.
-
-A worker still has access to Node built-ins — `require('fs')`, `process`, network sockets — and runs
-as the same uid as OpenWA. The sandbox therefore does **not**, by itself, stop a malicious plugin
-from 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.
-
-For genuinely untrusted, third-party plugins, combine the sandbox with **OS-level containment**:
-
-- **Run OpenWA in its container** (the shipped Docker image already runs read-only rootfs, non-root,
- and `cap_drop: ALL`), which bounds what any plugin's `fs`/network access can reach.
-- Until a marketplace exists, the standing guidance remains: **install only plugins you trust.**
-
-A stronger isolation variant (child process with Node's permission model, or an `isolated-vm`) is a
-possible future enhancement for maximum-hostility deployments; the transport is already abstracted
-behind a channel interface so it can slot in without touching plugin code.
-
-## What changes for plugin authors
-
-Sandboxed plugins keep the same `IPlugin` shape (`onLoad`/`onEnable`/`onDisable`/`onUnload`,
-`ctx.messages`, `ctx.engine`, `ctx.storage`, `ctx.registerHook`), with these rules:
-
-1. **Capability calls are remote.** They were already `async`; they now genuinely cross a thread
- boundary. Nothing to change in usage.
-2. **Only serializable data crosses.** Hook payloads and capability args/results must be
- structured-clone-safe — plain objects, arrays, primitives, `Date`, typed arrays. **No functions,
- no class instances with methods, no live references.**
-3. **No ambient host access.** `require('fs')`/`process` etc. still exist in the worker but must not
- be relied on as a capability — anything the plugin legitimately needs should be a declared
- capability, and OS containment may block direct access.
-4. **Declare your permissions.** A capability call is denied unless the manifest declares it
- (`messages:send`, `engine:read`). See [19 — Plugin Architecture](./19-plugin-architecture.md).
-
-This is a **breaking change for third-party plugin authoring** and ships in a minor release. Built-in
-plugins are unaffected (they remain in-process).
-
-## Configuration
-
-| Env / constant | Default | Purpose |
-|----------------|---------|---------|
-| `maxOldGenerationSizeMb` (worker) | 256 | per-plugin heap cap; OOM kills the worker, not the host |
-| hook handler timeout | 5000 ms | budget before a sandboxed hook handler is skipped |
diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.md
index a06fb306d..7c07797da 100644
--- a/docs/25-integration-fabric.md
+++ b/docs/25-integration-fabric.md
@@ -1,9 +1,10 @@
# 25 - Integration Fabric
-> **Status:** P0 substrate merged as an internal foundation. This document describes the architecture and
-> the design rationale — *why* it is built this way — not a how-to or an API reference. The public SDK
-> reference and the first ready-to-use adapter arrive in later phases (see
-> [15 - Project Roadmap](./15-project-roadmap.md)).
+> **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
+> built this way — not a how-to or an API reference (see
+> [15 - Project Roadmap](./15-project-roadmap.md) for the phase table).
## 25.1 What it is
@@ -28,7 +29,7 @@ public contract — Integration SDK v1** — because the contract, not any singl
The overriding goal is to preserve the untrusted-worker safety invariants *by construction*. OpenWA
plugins run in a capability-gated worker thread with no ambient host access (see
-[23 - Plugin Sandboxing](./23-plugin-sandboxing.md)). Every host↔worker message is a serializable POJO
+[30 - Plugin Sandboxing](./30-plugin-sandboxing.md)). Every host↔worker message is a serializable POJO
across a `structuredClone` boundary; host-initiated calls fail open on a timeout and drain on a worker
crash; permissions are manifest-static and cannot be widened by configuration; session scope is enforced
host-side.
@@ -130,7 +131,7 @@ Four tables live on the data connection, each created by a hand-authored dual-di
a human-handled conversation deterministically stops the bot. `sessionId` is non-foreign-key provenance
because a mapping outlives a session.
- **`ingress_events`** — the persist-before-acknowledge row and the inbound deduplication oracle
- (`UNIQUE(instanceId, providerDeliveryId)`, insert-or-skip). It also carries the dispatch-lifecycle
+ (`UNIQUE(pluginId, instanceId, providerDeliveryId)`, insert-or-skip). It also carries the dispatch-lifecycle
markers the reconciler sweeps on: `dispatchState` (`pending | dispatched | failed`, `NULL` on rows
that predate the columns on a synchronize-bootstrapped DB — "not watched"), `dispatchAttempts`, and
`lastDispatchAt`. New rows are `pending`; a recorded enqueue outcome flips them to `dispatched`;
@@ -155,8 +156,8 @@ Four tables live on the data connection, each created by a hand-authored dual-di
guard still applies, and the payload is intentionally not bound to a DTO so strict validation cannot
reject unknown provider fields.
- **Replay and duplication.** A signed-timestamp tolerance rejects stale deliveries, and
- `(instanceId, providerDeliveryId)` deduplication plus a queue job id keyed on the delivery id provides
- best-effort de-duplication when the provider supplies a stable delivery id. Standard Webhooks defaults
+ `(pluginId, instanceId, providerDeliveryId)` deduplication plus a queue job id keyed on the delivery id
+ provides best-effort de-duplication when the provider supplies a stable delivery id. Standard Webhooks defaults
to its signed `webhook-id`; other handlers must remain idempotent because arbitrary provider headers
are not authenticated by every scheme. Freshness is enforced whenever a route declares
`signature.timestampHeader`: the declared `toleranceSec` wins, and otherwise the host default
@@ -175,7 +176,10 @@ Four tables live on the data connection, each created by a hand-authored dual-di
- **Fail-closed by construction.** No request — including an empty-body request — is accepted by an
authenticating scheme without the correct per-instance secret. HMAC and Standard Webhooks bind body
integrity; `shared-secret` authenticates only the caller header and does not bind the body.
- `scheme: "none"` is the only unauthenticated path.
+ `scheme: "none"` is the only unauthenticated path, and a route declaring it **fails the whole plugin's
+ load** unless the operator has explicitly opted in with `ALLOW_UNSIGNED_INGRESS=true` — manifest
+ validation throws, so none of that plugin's other routes load either and its registry status is set to
+ `ERROR`. When the operator has opted in, the loader still logs its boot warning for every such route.
- **Raw-body content types.** Signature verification observes exact bytes for `application/json` and
`application/x-www-form-urlencoded`. Plain text, XML, octet streams, and non-UTF JSON charsets are not
supported ingress body formats and fail verification/content handling rather than being re-serialized.
@@ -225,13 +229,14 @@ dedup rows and re-admit their replays, which is worse than the bounded growth it
The stable surface untrusted adapters consume. A plugin declares `sdkVersion: "1"` and an `ingress`
descriptor (the route, its signature scheme, replay tolerance, dedup header, and an optional verification
handshake) in its manifest, and requests the `webhook:ingress` and `conversation:send` permissions. The
-host refuses to route ingress to a plugin whose declared **major** differs from the host's supported
-major, and the surface is **additive-only** within a major. The worker-facing API centres on
+host refuses to load an ingress-declaring plugin whose declared **major** differs from the host's
+supported major, and the surface is **additive-only** within a major. The worker-facing API centres on
`ctx.registerWebhook(...)` (claim an inbound route), `ctx.conversations.send(...)` (normalized reply), and
per-instance mapping and handover helpers.
The `signature.scheme` field enumerates `hmac-sha256` (HMAC over a `contentTemplate`), `shared-secret`
-(constant-time header compare), `standard-webhooks`, and `none` (unauthenticated — see §25.6). The
+(constant-time header compare), `standard-webhooks`, and `none` (unauthenticated — a route declaring it
+fails the whole plugin's load unless the operator sets `ALLOW_UNSIGNED_INGRESS=true`; see §25.6). The
`standard-webhooks` scheme verifies a [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks)
payload host-side — Supabase Auth's Send-SMS hook and any Svix-routed provider speak it natively. Its wire
format is fixed by the spec (the `webhook-id` / `webhook-timestamp` / `webhook-signature` header triple,
@@ -257,25 +262,32 @@ that was never wired to the HTTP response (the pipeline is always async + fast-a
not rely on it at runtime.
The full SDK reference — every manifest field, the envelope schema, the lifecycle, and the golden
-compatibility fixtures — is published alongside the first adapter, so it documents a contract that can
-actually be exercised end to end. Until then this document and the manifest types are the source of truth.
+compatibility fixtures — is a P4 deliverable and is not published yet, so this document and the manifest
+types remain the source of truth.
## 25.9 Phasing and status
See [15 - Project Roadmap](./15-project-roadmap.md) for the full phase table. In brief: **P0** (this
-substrate) is merged as an internal foundation; **P1** adds scale-correctness (per-conversation ordering,
-per-instance fairness, DLQ redrive, handover); **P2** adds operator provisioning and ships the first
-adapter as a marketplace plugin; **P3** ships a second adapter; **P4** covers developer experience (SDK
-reference, compatibility suite, secret rotation, multi-node routing).
-
-> **P0 and P1 are not a user-facing feature yet.** The ingress flow requires an operator provisioning step
-> (minting a plugin instance and its secret) that lands in P2; until then it is reachable only by direct
-> configuration.
+substrate) is merged; **P1** added scale-correctness (per-conversation ordering, per-instance fairness,
+DLQ redrive, handover); **P2** shipped operator provisioning in v0.8.0 — an ADMIN-only instance API
+(`POST|GET /api/integration/plugins/:pluginId/instances` to create and list, with
+`GET|PATCH|DELETE /api/integration/plugins/:pluginId/instances/:instanceId` and
+`POST /api/integration/plugins/:pluginId/instances/:instanceId/regenerate-secret` on the item path) and a
+dashboard **Instances** tab; **P3** validated the substrate against a second ingress adapter
+(`supabase-otp-hook`). The official
+ingress adapters ship as sandboxed plugins in the
+[OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) catalog, not in this repository. What
+remains open is **P4**: the published SDK reference, a compatibility test suite, and multi-node routing.
+
+> **Provisioning is a first-class operator surface.** An ADMIN key mints a plugin instance against an
+> ingress-capable plugin, binds it to a session scope, and receives the ingress URLs for the plugin's
+> declared routes. The instance's ingress secret (and its `verifyToken`) are revealed once, on create and
+> on regenerate, and masked on every later read.
---
> See also: [03 - System Architecture](03-system-architecture.md),
> [04 - Security Design](04-security-design.md),
> [19 - Plugin Architecture](19-plugin-architecture.md),
-> [23 - Plugin Sandboxing](23-plugin-sandboxing.md),
+> [30 - Plugin Sandboxing](30-plugin-sandboxing.md),
> [15 - Project Roadmap](15-project-roadmap.md).
diff --git a/docs/26-global-search.md b/docs/26-global-search.md
index c327538cd..88f7e2b83 100644
--- a/docs/26-global-search.md
+++ b/docs/26-global-search.md
@@ -3,8 +3,8 @@
> **Status:** Backend shipped — `GET /api/search` works out of the box on SQLite and PostgreSQL with
> the built-in database full-text provider, behind an open `SearchProvider` contract. This document is
> the user-facing feature guide: what it is, how to configure and query it, and when to reach for a
-> plugin backend. A dashboard panel and the SDK helpers arrive in a later phase; until then the feature
-> is driven through the REST endpoint documented here and in
+> plugin backend. The dashboard search panel and the SDK search resources shipped in v0.8.13; both
+> build on the REST endpoint documented here and in
> [06 - API Specification](./06-api-specification.md).
## 26.1 What it is
@@ -29,16 +29,17 @@ interface SearchProvider {
readonly id: string; // e.g. 'builtin-fts'
readonly label: string; // human label for dashboard/config
search(query: SearchQuery): Promise<SearchResults>;
- health(): Promise<SearchHealth>; // ok=false surfaces as 503
+ health(): Promise<SearchHealth>; // provider liveness; not yet surfaced on any route
}
```
A registry holds the set of registered providers and the currently active one. Core registers
-`builtin-fts` at bootstrap; a marketplace plugin registers itself the same way and can be promoted
-with `SEARCH_PROVIDER`. When no provider is registered, the route returns `501` (never crashes boot).
-The active provider answers every `/search` call, so swapping backends is a config change, not a code
-change. Importantly, **indexing is not part of the contract** — each provider owns how its index stays
-current (the built-in is DB-level; a plugin is hook-driven, see §26.7).
+`builtin-fts` at bootstrap; a marketplace plugin registers itself the same way and, under the default
+`SEARCH_PROVIDER=auto`, supersedes the built-in when it is enabled (see §26.5). When no provider is
+registered, the route returns `501` (never crashes boot). The active provider answers every `/search`
+call, so swapping backends is a config change, not a code change. Importantly, **indexing is not part
+of the contract** — each provider owns how its index stays current (the built-in is DB-level; a plugin
+is hook-driven, see §26.7).
## 26.3 The built-in DB full-text default
@@ -53,11 +54,14 @@ is maintained by the DB on every INSERT/UPDATE/DELETE with no application code i
`rowid`, kept in sync by AFTER INSERT/UPDATE/DELETE triggers and backfilled once at migration time.
Ranking uses FTS5 `rank`; snippets use `snippet()`.
-Both dialects wrap the search term in their native "web search"-style helper (`websearch_to_tsquery`
-on Postgres, FTS5 `MATCH` on SQLite), so quoted phrases, `OR`, and `-`exclusion behave as the
-underlying engine defines them. Snippets are emitted with `<mark>`/`</mark>` highlight markers on both
-dialects so the `SearchHit.snippet` contract is dialect-agnostic — and the snippet is already
-XSS-safe text; render it as text, never as HTML.
+On Postgres the search term goes through `websearch_to_tsquery`, so quoted phrases, `OR`, and
+`-`exclusion behave as Postgres defines them. On SQLite the term is matched **literally**: every
+whitespace-separated token is quoted (internal quotes doubled) before it reaches FTS5 `MATCH`, so FTS5
+query grammar (phrases, bare `OR`/`AND`/`NOT`/`NEAR`, parentheses, `*`) is neutralised and inputs such
+as phone numbers or `…@lid` ids match as plain text; multiple tokens are still implicitly ANDed.
+Snippets are emitted with `<mark>`/`</mark>` highlight markers on both dialects so the
+`SearchHit.snippet` contract is dialect-agnostic — and the snippet is already XSS-safe text; render it
+as text, never as HTML.
## 26.4 Dual-database switching safety
@@ -90,7 +94,7 @@ All search configuration lives in the environment (`.env` / Compose / dashboard
| 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; `builtin-fts` pins it explicitly; `none` disables the route at runtime while keeping the config namespace loaded. A plugin provider id selects that plugin once registered. Validated at boot — a typo fails fast. |
+| `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 note
@@ -104,17 +108,18 @@ Postgres, a trigger-fire on SQLite — both in-process, both on columns already
want to drop the index entirely, run the migration `down` against the data connection.
> **Dev note — `DATABASE_SYNCHRONIZE=true`.** With synchronize on (a common zero-config dev setting),
-> TypeORM creates the `messages` table from the entity, but the FTS migration does **not** run, so
-> `/search` returns `501` (no FTS schema) until you run `npm run migration:run` once to install the FTS
-> virtual table / generated column. Prod defaults to `synchronize=false` + `migrationsRun=true`, so this
-> is dev-only.
+> TypeORM creates the `messages` table from the entity but never runs migrations, so the FTS schema
+> would be missing. The built-in provider therefore re-applies the migration's idempotent DDL at boot
+> (including the one-time SQLite backfill), so `/search` works on a fresh synchronize-based box with no
+> manual `npm run migration:run` step. On migrations-based deployments the same DDL is a set of no-ops.
>
-> **Postgres caveat — do not combine `DATABASE_TYPE=postgres` with `DATABASE_SYNCHRONIZE=true`.** The
-> Postgres data connection hardcodes `migrationsRun=true` (unlike SQLite, where it is `!synchronize`),
-> so on Postgres both run every boot: the migration adds the generated `body_ts` column, then
-> `synchronize` immediately drops it (the `Message` entity does not declare `body_ts`). The result is
-> `/search` returning `501` silently on every restart. Use migrations (`DATABASE_SYNCHRONIZE=false`, the
-> prod default) for Postgres. SQLite is unaffected (its `migrationsRun` is `!synchronize`).
+> **Postgres caveat — `DATABASE_TYPE=postgres` with `DATABASE_SYNCHRONIZE=true` is rejected at boot.**
+> The Postgres data connection hardcodes `migrationsRun=true` (unlike SQLite, where it is
+> `!synchronize`), so on Postgres both would run every boot: the migration adds the generated `body_ts`
+> column, then `synchronize` immediately drops it (the `Message` entity does not declare `body_ts`),
+> leaving `/search` returning `501` on every restart. Env validation refuses the boot with an explicit
+> error instead. Use migrations (`DATABASE_SYNCHRONIZE=false`, the prod default) for Postgres. SQLite is
+> unaffected (its `migrationsRun` is `!synchronize`).
## 26.6 The HTTP endpoint
@@ -122,7 +127,7 @@ See [06 - API Specification §6.4.12](./06-api-specification.md) for the full pa
In brief:
```
-GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<in|out>&type=<type>
+GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<incoming|outgoing>&type=<type>
&from=<sender>&dateFrom=<ms>&dateTo=<ms>&limit=<n>&offset=<n>
```
@@ -138,19 +143,20 @@ GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<in|out>&type=<typ
`direction`, `from`, and optional `score`. `total` is an exact count (bounded; computed lazily only
when the page could be full). `tookMs` is the provider-side query time. `provider` names which
backend answered (e.g. `builtin-fts`).
-- **Errors:** `400` empty/whitespace `q`, a non-numeric numeric param, or a malformed SQLite FTS5 query
- (unbalanced quote/paren, bare operator) — Postgres is tolerant · `401`/`403` auth · `501` no
- provider configured / FTS schema absent (e.g. a non-FTS5 SQLite build) · `503` provider unhealthy
- (**reserved**: the built-in provider does not return it; it is the contract surface for a future
- plugin provider whose `search()` throws `ServiceUnavailableException`).
+- **Errors:** `400` empty/whitespace `q` or a non-numeric numeric param (an FTS5 query-grammar error is
+ also mapped to `400`, but since the SQLite path quotes every token ordinary input no longer reaches
+ that fallback) · `401`/`403` auth · `501` no provider configured / FTS schema absent (e.g. a non-FTS5
+ SQLite build) · `502` a plugin provider returned a malformed `SearchResults` payload · `503` a plugin
+ provider whose worker timed out or failed (the built-in provider does not return it).
The endpoint requires at least `OPERATOR` role.
## 26.7 When to use a plugin backend
The built-in DB full-text provider is the right default for the common case: moderate volume, Latin and
-mixed-Script text, exact-word and phrase matching, and no extra infrastructure. Reach for a plugin
-provider when you need capabilities the SQL engines do not give you:
+mixed-Script text, whole-token matching (phrase and boolean operators only on Postgres — see §26.3),
+and no extra infrastructure. Reach for a plugin provider when you need capabilities the SQL engines do
+not give you:
- **CJK word-segmentation and morphological analysis** — Postgres `'simple'` and SQLite FTS5 tokenize
on whitespace/punctuation, which does not segment Chinese/Japanese/Korean. A dedicated engine
@@ -161,12 +167,13 @@ provider when you need capabilities the SQL engines do not give you:
(field weights, synonyms, stop-word lists, custom ranking), a purpose-built search server
outperforms a relational FTS query and is tunable without touching the message schema.
-The upgrade path is the **Meilisearch provider plugin** (the reference plugin backend, Spec 2). It
+The upgrade path is a **search-provider plugin**. The host→plugin search RPC has shipped, so a plugin
registers as a `SearchProvider`, indexes via the `message:persisted` plugin hook (so it stays current
-without coupling to the message/session services — outbound rows are re-emitted as upserts on every
-state transition, and `message:deleted` fires when a redundant pending row is dropped), and is
-selected by setting `SEARCH_PROVIDER` to its id. Because the route and the response shape are
-identical across providers, dashboard panels and SDKs keep working unchanged when you switch backends.
+without coupling to the message/session services), and becomes the active backend under the default
+`SEARCH_PROVIDER=auto`. No reference plugin is published yet — see
+[27 - Writing a Search-Provider Plugin](./27-plugin-search-providers.md) for the author's contract.
+Because the route and the response shape are identical across providers, dashboard panels and SDKs
+keep working unchanged when you switch backends.
> **Backfill is the plugin's responsibility.** The `message:persisted` hook fires only for **live**
> traffic — outbound on send, inbound on receive — never for history-backfill persistence. So a plugin
diff --git a/docs/27-plugin-search-providers.md b/docs/27-plugin-search-providers.md
index 4d4bd30f9..d44b3bd4c 100644
--- a/docs/27-plugin-search-providers.md
+++ b/docs/27-plugin-search-providers.md
@@ -220,5 +220,5 @@ ctx interface is planned; for now the search contract types above are the stable
> See also: [26 - Global Search](./26-global-search.md) (the feature + the built-in provider),
> [19 - Plugin Architecture](./19-plugin-architecture.md),
-> [23 - Plugin Sandboxing](./23-plugin-sandboxing.md),
+> [30 - Plugin Sandboxing](./30-plugin-sandboxing.md),
> [06 - API Specification](./06-api-specification.md) §6.4.12 Search.
diff --git a/docs/engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
similarity index 96%
rename from docs/engine-capability-matrix.md
rename to docs/29-engine-capability-matrix.md
index c2061a21a..d3478070d 100644
--- a/docs/engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -1,4 +1,4 @@
-# Engine Capability Matrix
+# 29 - Engine Capability Matrix
This page is the operator- and engineer-facing view of which `IWhatsAppEngine` capabilities are real on each adapter — `wwjs` (whatsapp-web.js, the default) and `baileys` (the browser-free alternative) — and, for the ones that are missing, *why* and *where to start*.
@@ -22,7 +22,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins
## Unwired-capability inventory
-15 of the 80 interface methods are `not-available` on at least one adapter (20 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.
+16 of the 80 interface methods are `not-available` on at least one adapter (21 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.
### Channels / Newsletter
@@ -91,6 +91,14 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins
- **`getChatHistory` (baileys, library-limitation).** The only history primitive is `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)` (`Socket/business.d.ts:25`) — it returns a sync-token *string*, not messages; the messages are delivered later via the `messaging-history.set` event. There is no per-chat `fetchMessages(chatId, limit)` on the socket. A synchronous `Promise<IncomingMessage[]>` for one chat would require an OpenWA-side chat-indexed store populated from `messages.upsert` + `messaging-history.set` events.
- **`getMessageReactions` (baileys, library-limitation).** No on-demand server fetch. Reactions exist only as event-augmented state on `WAMessage.reactions` (`proto.IReaction[]` at `WAProto/index.d.ts:10623`), mutated by `updateMessageWithReaction` and surfaced via the `messages.reaction` event. The adapter already processes `reactionMessage` events (`baileys.adapter.ts:1048-1057`) and emits `onMessageReaction`, but it does **not** persist `.reactions` into its `messageStore` (early-returns at line 1058). A store-backed read would need that persistence added first; even then, only reactions observed since session start are known (no historical backfill).
+### Groups — disappearing messages
+
+| Method | baileys | wwjs |
+|---|---|---|
+| `setGroupEphemeral` | supported | not-available — **library-limitation** |
+
+- **`setGroupEphemeral` (wwjs, library-limitation).** whatsapp-web.js 1.34.7 exposes no disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); the only timer surface is the create-time `messageTimer` option (`Client.js:2371`). The adapter throws `EngineNotSupportedError` (501). Baileys wires `groupToggleEphemeral(jid, ephemeralExpiration)` (`Socket/groups.d.ts:40`).
+
---
## Prioritized roadmap — adapter gaps (fixable in this repo)
diff --git a/docs/30-plugin-sandboxing.md b/docs/30-plugin-sandboxing.md
new file mode 100644
index 000000000..6e0102ac0
--- /dev/null
+++ b/docs/30-plugin-sandboxing.md
@@ -0,0 +1,114 @@
+# 30 — Plugin Sandboxing
+
+OpenWA runs **untrusted plugins** (anything loaded from the plugins directory) in an isolated worker
+thread, separate from the first-party built-ins (the two engine adapters) which run in-process. This
+page describes the security model honestly — what the sandbox guarantees and, just as important, what
+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 |
+
+The loader routes by tier automatically: a plugin registered programmatically is built-in; one loaded
+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
+ is 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 runs
+ each call through the same permission + session-scope checks an in-process plugin gets
+ (`assertPermission` / declared `sessions`), so a sandboxed plugin can never exceed its declared
+ manifest permissions on those verbs (the permission model gates the `ctx.*` verbs, not raw Node
+ access — see the limits below). Verbs are allowlisted — a worker cannot invoke an arbitrary host
+ method — and the router validates the string and mapping-key args before they reach a host service
+ (other positional args are passed through as declared types, not re-checked). `ctx.net.fetch` is
+ additionally bounded by the host SSRF guard and the manifest `net.allow` host list, so outbound
+ HTTP from a worker is neither ambient nor unrestricted.
+- **Host-initiated dispatches are mediated too.** Besides hooks, the host drives two other bridges into
+ the worker over the same request/reply channel: inbound webhooks
+ (`ctx.registerWebhook`, gated by the `webhook:ingress` permission and dropped for any route the
+ manifest does not declare — see [25 — Integration Fabric](./25-integration-fabric.md)) and search
+ queries (`ctx.registerSearchProvider` — see
+ [27 — Plugin Search Providers](./27-plugin-search-providers.md)). The bridged `ctx.*` surface hands
+ the plugin no listening socket and no route of its own — there is no `ctx.api` or `ctx.router`; the
+ host terminates, authenticates and enqueues the delivery first.
+- **Hook safety.** Hook handlers run in the worker and are dispatched with a **time budget**
+ (`SANDBOX_HOOK_TIMEOUT_MS`, a hardcoded 5s). A slow or wedged handler is skipped (`continue: true`)
+ so it can never stall the host's hook chain.
+- **Resource & runaway containment.** Each worker has a heap cap (`maxOldGenerationSizeMb`, a hardcoded
+ 256 MB). An OOM terminates the worker, not the host. A wedged **lifecycle** call (load/unload) times out
+ and tears the worker down, and a crash rejects its in-flight calls — the host survives either way. A
+ runaway **hook** handler (e.g. an infinite synchronous loop) is skipped on the hook timeout so it can't
+ stall the host's hook chain, but the worker keeps running it (pegging a core) until the plugin is
+ reloaded or hits the heap cap — it is contained to its own thread, not instantly force-killed.
+
+## What the sandbox does NOT guarantee
+
+> A `worker_thread` is a separate V8 context **in the same OS process, under the same user**. It is
+> not an OS-level sandbox.
+
+A worker still has access to Node built-ins — `require('fs')`, `process`, network sockets — and runs
+as the same uid as OpenWA. The sandbox therefore does **not**, by itself, stop a malicious plugin
+from 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.
+
+For genuinely untrusted, third-party plugins, combine the sandbox with **OS-level containment**:
+
+- **Run OpenWA in a container.** The image's entrypoint already drops to the non-root `openwa` user
+ (via `gosu`, after fixing volume ownership). The rest of the confinement comes from the bundled
+ `docker-compose.yml`, not from the image: `read_only: true` rootfs with a tmpfs `/tmp`,
+ `no-new-privileges`, and `cap_drop: ALL` with a minimal re-add
+ (`CHOWN`/`DAC_OVERRIDE`/`FOWNER`/`SETGID`/`SETUID`) that only the root entrypoint uses — once `gosu`
+ setuids, the Node process keeps no effective capabilities. Together these bound what any plugin's
+ `fs`/network access can reach; a plain `docker run` of the image gets none of the compose-level
+ settings, so replicate them yourself if you deploy that way.
+- Until a marketplace exists, the standing guidance remains: **install only plugins you trust.**
+
+A stronger isolation variant (child process with Node's permission model, or an `isolated-vm`) is a
+possible future enhancement for maximum-hostility deployments; the transport is already abstracted
+behind a channel interface so it can slot in without touching plugin code.
+
+## What changes for plugin authors
+
+Sandboxed plugins keep the same `IPlugin` shape (`onLoad`/`onEnable`/`onDisable`/`onUnload`,
+`ctx.messages`, `ctx.engine`, `ctx.storage`, `ctx.net`, `ctx.conversations`, `ctx.handover`,
+`ctx.mappings`, `ctx.registerHook`). Two entries are sandbox-only in practice:
+`ctx.registerWebhook` is declared on the shared context but is functional only in a worker — an
+in-process plugin that calls it fails loud rather than silently never firing — and
+`ctx.registerSearchProvider` exists only in the worker context. The rules:
+
+1. **Capability calls are remote.** They were already `async`; they now genuinely cross a thread
+ boundary. Nothing to change in usage.
+2. **Only serializable data crosses.** Hook payloads and capability args/results must be
+ structured-clone-safe — plain objects, arrays, primitives, `Date`, typed arrays. **No functions,
+ no class instances with methods, no live references.**
+3. **No ambient host access.** `require('fs')`/`process` etc. still exist in the worker but must not
+ be relied on as a capability — anything the plugin legitimately needs should be a declared
+ capability, and OS containment may block direct access.
+4. **Declare your permissions.** A capability call is denied unless the manifest declares it:
+ `messages:send` for `ctx.messages`, `engine:read` for `ctx.engine`, `net:fetch` for `ctx.net.fetch`
+ (plus a `net.allow` host list), `conversation:send` for `ctx.conversations` / `ctx.handover` /
+ `ctx.mappings`, and `webhook:ingress` for `ctx.registerWebhook` (enforced at load and again at route
+ subscription). `ctx.storage` needs no permission — it is already per-plugin scoped. See
+ [19 — Plugin Architecture](./19-plugin-architecture.md).
+
+Sandboxing was a **breaking change for third-party plugin authoring** when it shipped in v0.6.0.
+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 |
+
+Both are hardcoded constants in the plugin loader — **neither is an environment variable**, so
+changing either requires a code change.
diff --git a/docs/DOCKER_ID.md b/docs/DOCKER_ID.md
deleted file mode 100644
index 782da2b9f..000000000
--- a/docs/DOCKER_ID.md
+++ /dev/null
@@ -1,120 +0,0 @@
-# Panduan Deployment Docker OpenWA
-
-Panduan ini menjelaskan cara melakukan deployment **OpenWA** (WhatsApp API Gateway) menggunakan Docker dan Docker Compose.
-
----
-
-## 🚀 Persyaratan Sistem
-Sebelum memulai, pastikan server Anda sudah terinstal:
-* **Docker** (versi 20.10+)
-* **Docker Compose** (versi 2.0+)
-
----
-
-## 📁 Struktur Konfigurasi
-
-OpenWA menggunakan fitur **Profiles** di Docker Compose untuk mempermudah orkestrasi layanan tambahan (database, cache, dll) sesuai kebutuhan infrastruktur Anda.
-
-### Layanan Utama (Core)
-* **`openwa-api`**: Server backend utama REST API OpenWA, sekaligus menyajikan Dashboard web (React UI) pada port yang sama.
-
-### Layanan Tambahan (Optional Profiles)
-* **`postgres`**: Database PostgreSQL (bawaan docker).
-* **`redis`**: Caching layer untuk performa tinggi.
-* **`minio`**: Penyimpanan berkas media yang kompatibel dengan Amazon S3.
-
----
-
-## ⚡ Langkah Cepat (Development)
-
-Untuk kebutuhan uji coba lokal dengan database bawaan SQLite dan penyimpanan lokal:
-
-```bash
-# 1. Clone repositori hasil fork Anda
-git clone [email protected]:jimmimohtar/OpenWA.git
-cd OpenWA
-
-# 2. Jalankan docker compose khusus development
-docker compose -f docker-compose.dev.yml up -d
-```
-
-Aplikasi dapat diakses di (Dashboard sudah menyatu dengan API pada port yang sama):
-* **Dashboard UI**: `http://localhost:2785`
-* **Swagger Docs**: `http://localhost:2785/api/docs`
-
----
-
-## 🏭 Deployment Produksi
-
-### 1. File Environment (`.env`)
-Salin file `.env.example` menjadi `.env` lalu sesuaikan konfigurasi kunci keamanan Anda:
-
-```bash
-cp .env.example .env
-```
-
-Pastikan untuk mengubah nilai rahasia berikut di dalam `.env`:
-* `API_MASTER_KEY`: Kunci keamanan untuk autentikasi API.
-* `DATABASE_PASSWORD`: Sandi untuk database PostgreSQL (jika dipakai).
-
-### 2. Memilih Skenario Deployment (Docker Profiles)
-
-> Dashboard sudah menyatu ke dalam image API dan disajikan oleh NestJS pada port API (2785),
-> jadi tidak ada lagi profil/container `with-dashboard` terpisah.
-
-#### Skenario A: Produksi Minimalis (SQLite + Dashboard)
-Cocok untuk VPS resource kecil (RAM 1GB - 2GB):
-```bash
-docker compose up -d
-```
-
-#### Skenario B: Produksi Menengah (PostgreSQL + Dashboard)
-Cocok untuk keandalan data lebih tinggi:
-```bash
-docker compose --profile postgres up -d
-```
-
-#### Skenario C: Full Stack (PostgreSQL + Redis + S3 MinIO)
-Cocok untuk skala enterprise dengan multi-sesi aktif:
-```bash
-docker compose --profile full up -d
-```
-
----
-
-## ⚙️ Variabel Lingkungan Penting (Environment Variables)
-
-Berikut variabel penting yang bisa disesuaikan di `.env`:
-
-| Nama Variabel | Nilai Default | Deskripsi |
-|---|---|---|
-| `API_PORT` | `2785` | Port REST API sekaligus Dashboard UI (disajikan oleh NestJS). |
-| `DATABASE_TYPE` | `sqlite` | Jenis database yang digunakan (`sqlite` atau `postgres`). |
-| `DATABASE_NAME` | `/app/data/openwa.sqlite` | Lokasi database SQLite atau nama database PostgreSQL. |
-| `ENGINE_TYPE` | `whatsapp-web.js` | Driver/mesin engine WhatsApp yang digunakan (`whatsapp-web.js` default, berbasis Chromium; atau `baileys`, tanpa browser). |
-| `SERVE_DASHBOARD` | `true` | Sajikan Dashboard UI dari port API yang sama. Set `false` untuk menonaktifkan penyajian static files. |
-| `PUPPETEER_HEADLESS` | `true` | Menjalankan browser WhatsApp secara tersembunyi (hanya berlaku untuk engine `whatsapp-web.js`). |
-
----
-
-## 🔍 Pemeriksaan Status & Diagnostik
-
-Memeriksa apakah kontainer berjalan lancar:
-```bash
-docker compose ps
-```
-
-Melihat log aktivitas sistem OpenWA:
-```bash
-docker compose logs -f openwa-api
-```
-
-Melakukan pembersihan/berhenti:
-```bash
-docker compose down
-```
-
----
-
-## 🤝 Kontribusi
-Jika Anda menemukan kendala saat setup menggunakan Docker, silakan ajukan Issue atau Pull Request di repositori ini.
diff --git a/docs/README.md b/docs/README.md
index 23a4d1d83..5939c1637 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -42,7 +42,6 @@
| 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 |
-| 10-ID| [Panduan Docker (ID)](./DOCKER_ID.md) | Panduan deployment Docker dalam Bahasa Indonesia |
| 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 |
@@ -56,10 +55,13 @@
| 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 |
-| 23-S| [Plugin Sandboxing](./23-plugin-sandboxing.md) | Worker isolation, capabilities, and plugin limits |
| 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**
@@ -238,6 +240,6 @@ MIT License.
**Start Reading: [01 - Project Overview](./01-project-overview.md)**
-_OpenWA Documentation · Last updated: 2026-06-18_
+_OpenWA Documentation · Last updated: 2026-07-28_
</div>
diff --git a/src/engine/engine-parity.spec.ts b/src/engine/engine-parity.spec.ts
index 9f91bab61..3744f5640 100644
--- a/src/engine/engine-parity.spec.ts
+++ b/src/engine/engine-parity.spec.ts
@@ -7,7 +7,7 @@ import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';
/**
* Drift invariants for the engine capability matrix. The matrix's `status` (supported /
* not-available) is hand-curated and richer than a throw-scan: it also marks "phantom support"
- * methods (adapter stubs that return null/[] without throwing — see docs/engine-capability-matrix.md).
+ * methods (adapter stubs that return null/[] without throwing — see docs/29-engine-capability-matrix.md).
* So the gate asserts the invariants a throw-scan CAN verify, not full equality:
*
* 1. A method whose adapter body throws EngineNotSupportedError/ChannelMediaNotSupportedError