Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

docs: bring the architecture, security, FAQ and upgrade pages up to date

Yudhi Armyndharis2b6bc8ff114d
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index 654b537cb..6dad4aaa3 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -917,16 +917,22 @@ export enum EngineStatus {
export interface EngineEventCallbacks {
onQRCode?: (qr: string) => void;
onReady?: (phone: string, pushName: string) => void;
- onMessage?: (message: IncomingMessage) => void;
- onMessageCreate?: (message: IncomingMessage) => void; // outgoing (incl. linked-phone sends)
+ admitInbound?: (arrival: {
+ id: string;
+ chatId: string;
+ needsRoom: boolean;
+ status: boolean;
+ }) => InboundTicket | undefined; // PostgreSQL: reserves room for a download before the emit
+ onMessage?: (message: IncomingMessage, ticket?: InboundTicket) => void;
+ onMessageCreate?: (message: IncomingMessage, ticket?: InboundTicket) => void; // outgoing (incl. linked-phone sends)
onMessageAck?: (messageId: string, status: DeliveryStatus, chatId?: string) => void;
- onMessageRevoked?: (message: RevokedMessage) => void;
+ onMessageRevoked?: (message: RevokedMessage, actor?: { fromMe: boolean }) => void;
onMessageReaction?: (event: ReactionEvent) => void;
onMessageEdited?: (message: EditedMessage) => void;
onEventResponse?: (event: EventResponseEvent) => void; // an RSVP to a WhatsApp event; Baileys only
onGroupEvent?: (event: GroupEvent) => void; // kind selects group.join / group.leave / group.update / group.join_request
onCall?: (event: IncomingCallEvent) => void; // incoming call ringing; Baileys can rejectCall() while it rings
- onHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatch
+ onHistoryMessages?: (messages: IncomingMessage[]) => void | Promise<IncomingMessage[] | void>; // bulk initial sync; persist, don't dispatch
onDisconnected?: (reason: string) => void; // recoverable -> reconnect
onReconnecting?: (attempt: number, nextDelayMs: number) => void; // engines that retry internally (Baileys)
onStateChanged?: (state: EngineStatus) => void;
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 312df0ced..716ddfe02 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -283,13 +283,13 @@ flowchart TB
### Validation Examples
-| 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 |
+| Field | Rules |
+| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `chatId` | Non-empty string of at most 255 characters — **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
@@ -298,6 +298,7 @@ flowchart TB
export class SendTextMessageDto {
@IsString()
@IsNotEmpty()
+ @MaxLength(CHAT_ID_MAX_LENGTH) // 255
chatId: string;
@IsString()
@@ -422,10 +423,10 @@ app.enableCors({
},
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'],
+ allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID', 'Idempotency-Key'],
// 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', '...'],
+ exposedHeaders: ['X-RateLimit-Limit-short', 'X-RateLimit-Remaining-short', '...', 'Idempotent-Replayed'],
maxAge: 86400, // 24 hours
});
```
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 7c608b8b1..8ae55592f 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -167,6 +167,9 @@ version: '3.8'
services:
app:
image: ghcr.io/rmyndharis/openwa:latest
+ # Teardown takes up to 63 s with every datastore on; raise this by the amount SHUTDOWN_DELAY_MS or
+ # WEBHOOK_SHUTDOWN_DRAIN_MS exceeds its default, or Docker's 10 s default kills the container mid-teardown.
+ stop_grace_period: 75s
deploy:
replicas: 1
resources:
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 00fe617d1..53d398649 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -1064,8 +1064,10 @@ curl -H "X-API-Key: $API_KEY" \
```sql
-- Indexes ship with the schema (migrations) — there is nothing to add by hand. `messages`
-- carries ("sessionId", "createdAt"), ("sessionId", "chatId", "createdAt"), ("chatId"),
--- ("status"), ("createdAt"), a partial ("mediaPath") where it is not null, a unique
--- ("sessionId", "waMessageId"), and on PostgreSQL a GIN index on the full-text "body_ts" column.
+-- ("status"), ("createdAt"), the message-time indexes ("sessionId", "timestamp", "id"),
+-- ("sessionId", "chatId", "timestamp", "id") and ("sessionId", "direction", "timestamp", "id"),
+-- a partial ("mediaPath") where it is not null, a unique ("sessionId", "waMessageId"), and on
+-- PostgreSQL a GIN index on the full-text "body_ts" column.
-- PostgreSQL: refresh planner statistics on the hot tables
ANALYZE sessions;
@@ -1509,22 +1511,24 @@ A media message also carries `media: { mimetype, filename?, data?, omitted?, siz
### HTTP Error Codes
-| Code | Meaning | Common Cause | Solution |
-| ---- | ------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------- |
-| 400 | Bad Request | Invalid parameters, or the session is not started | Check request body/params; start the session |
-| 401 | Unauthorized | Missing/invalid API key | Add X-API-Key header |
-| 403 | Forbidden | Insufficient permissions | Check API key permissions |
-| 404 | Not Found | Invalid session/endpoint | Verify session exists |
-| 409 | Conflict | Session name already exists, or the session is not ready (retryable) | Use a different session name, or wait for `ready` |
-| 413 | Payload Too Large | File too large | Reduce file size |
-| 429 | Too Many Requests | Rate limited | Reduce request rate |
-| 500 | Internal Error | Server error | Check logs |
-| 503 | Service Unavailable | The engine transport died during a read, or a media fetch through the session proxy failed | Retry; restart the session if it persists |
+| Code | Meaning | Common Cause | Solution |
+| ---- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
+| 400 | Bad Request | Invalid parameters, or the session is not started | Check request body/params; start the session |
+| 401 | Unauthorized | Missing/invalid API key | Add X-API-Key header |
+| 403 | Forbidden | Insufficient permissions | Check API key permissions |
+| 404 | Not Found | Invalid session/endpoint | Verify session exists |
+| 409 | Conflict | Session name already exists, the session is not ready (retryable), or an idempotent send is in progress or of unknown outcome | Use a different session name, wait for `ready`, or follow the `code` (docs/06, idempotent sends) |
+| 422 | Unprocessable | An `Idempotency-Key` reused with another route or body | Use a new key for a different send |
+| 413 | Payload Too Large | File too large | Reduce file size |
+| 429 | Too Many Requests | Rate limited | Reduce request rate |
+| 500 | Internal Error | Server error | Check logs |
+| 503 | Service Unavailable | The engine transport died during a read, or a media fetch through the session proxy failed | Retry; restart the session if it persists |
### 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:
+`statusCode` (above) and read `message` for the human-readable cause. A few refusals also carry a stable
+`code` (see the error response section of docs/06):
```json
{
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 031cd759f..91877ea3b 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -264,6 +264,9 @@ version: '3.8'
services:
openwa:
image: ghcr.io/rmyndharis/openwa:latest
+ # Teardown takes up to 63 s with every datastore on; raise this by the amount SHUTDOWN_DELAY_MS or
+ # WEBHOOK_SHUTDOWN_DRAIN_MS exceeds its default, or the 10 s default kills the task mid-teardown.
+ stop_grace_period: 75s
deploy:
replicas: 1 # MUST stay 1 until multi-replica is supported — multiple replicas on one session volume corrupt WhatsApp auth
update_config:
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index d23e0bcaf..101cc93af 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -885,6 +885,18 @@ skips: check `pg_index.indisvalid` and drop the invalid index before building it
| Release | Change | Action |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `0.25.0` | Once teardown begins (SIGTERM, SIGINT, `POST /api/infra/restart`) every request except `/api/health`, `/api/health/*`, the dashboard's HTML pages and CORS preflights answers `503` with `Connection: close`, `GET /api/infra/health` included | Probe `/api/health/live` for liveness that survives teardown, and retry a `503` once the instance is up again |
+| `0.25.0` | `stop_grace_period` (Docker) and `terminationGracePeriodSeconds` (Kubernetes) go from 45 to 75 s, and a stop that runs 67 s past the shutdown delay exits with status 1 instead of 137 | Raise a pinned 45 s value to at least 75 s; a container that drops all capabilities and starts as root must add `KILL` to the capabilities 0.24.0 shipped, or a stop never reaches the app; update exit-code alerts |
+| `0.25.0` | `400` instead of `201` or `200` for a phone number WhatsApp reports as unregistered (Baileys; `503` when the lookup gets no answer) and for `vote-poll` with no matching option text (whatsapp-web.js) | Handle `400` (`POLL_OPTION_NOT_FOUND` carries `validOptions`) and `503` on these routes; an empty `options` list still clears a vote |
+| `0.25.0` | `400` for an `allowedChats` list over 2000 entries, `GET /api/search` with `q` over 1000 characters or 32 words, an animated image over 500 frames, and an `image/svg+xml` sticker, profile picture or group picture | Shorten the list or the query, send an animated image as WebP, and convert SVG to PNG or WebP before sending |
+| `0.25.0` | `PUT /api/infra/config` answers `400` for a database or Redis port outside 1-65535 and a negative or fractional pool size | Fix the value in the request; it used to be stored and the next boot refused it |
+| `0.25.0` | Boot fails on a `PORT` with surrounding whitespace and on a `WEBHOOK_SHUTDOWN_DRAIN_MS` that is not a non-negative integer (for example `30s`) | Remove the padding or the unit |
+| `0.25.0` | New Baileys pairings show `Ubuntu` as the linked-device name | Set `BAILEYS_BROWSER_NAME=OpenWA` to keep the old name; linked sessions are unaffected |
+| `0.25.0` | `backup.sh` and `restore.sh` exit with status 2 on an unparsable or unreadable `./.env` or `.env.generated`, read the default SQLite paths under `OPENWA_DATA_DIR`, and with `DATABASE_SSL=true` verify the PostgreSQL certificate as the app does | Fix the line or the permissions, or pass the key in the environment; trust a private CA through `NODE_EXTRA_CA_CERTS` or `PGSSLROOTCERT` |
+| `0.25.0` | With `DATABASE_SSL=true` the PostgreSQL certificate is verified against `DATABASE_HOST` even when it is an IP address | Use the certificate's DNS name as the host or add the IP to its subject alternative names; `DATABASE_SSL_REJECT_UNAUTHORIZED=false` remains the escape hatch |
+| `0.25.0` | The first boot builds three indexes on `messages` without `CONCURRENTLY` (about 240 MB per million messages; on PostgreSQL writes wait), and the Helm startup probe restarts a pod whose boot outlasts about 295 s | On a large table run the migrations first (section 14.5) |
+| `0.25.0` | Rolling back to 0.24.0 strands webhook outbox rows in state `queued`, and the upgrade deletes duplicate terminal `webhook_delivery_failures` rows | Drain or accept the queued rows before a rollback; the deleted duplicates are not restored |
+| `0.25.0` | A Baileys voice note goes out with flat waveform bars when no ffmpeg binary is found, and an `FFMPEG_PATH` wrapper script sees only `PATH`, the library paths, `HOME`, the temp directories, `LANG`, `LC_ALL` and `SystemRoot` of the gateway's environment | Use the official image, which ships ffmpeg, and export what a wrapper script needs inside the script |
| `0.24.0` | A live key refused by its `allowedIps` (including an undeterminable client IP) or its `allowedSessions` answers `403` instead of `401`; `401` now means only a missing, unknown, revoked or expired key | Handle `403` for these refusals: SDK callers catch the forbidden error (Go `ErrForbidden`) instead of the auth error |
| `0.24.0` | Every `POST /mcp` request needs a valid API key: `initialize` and `tools/list` without one answer `401`, a tool call with a missing or invalid key gets `401` instead of an `isError` result, and a key with `allowedIps` is refused with `403` on every request | Configure the API key in every MCP client, including one that only lists tools, and use a key without `allowedIps` for MCP |
| `0.24.0` | `GET /api/sessions/:sessionId/contacts/check/:number` and the MCP `ContactCheckNumber` tool require an OPERATOR key; a VIEWER key gets `403` | Give number-check integrations an OPERATOR key |
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 89c0a0e5b..07a65364d 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -598,7 +598,7 @@ its `ctx.storage` data dir (built-ins are protected and cannot be uninstalled).
dispatches `onUnload`: for a sandboxed plugin it runs in the worker between `onDisable` and terminate
(a plain disable does NOT fire `onUnload`; disable is reversible and its cleanup hook is `onDisable`).
-**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger,
+**Context.** `PluginCapabilityContext.createPluginContext` (`src/core/plugins/plugin-capability-context.ts`) builds the `PluginContext` (§19.4): a per-plugin logger,
`registerHook` (wrapped with the per-session activation gate), `registerWebhook`, the live
`config` getter, and the permission-checked `messages` / `engine` / `net` / `storage` / `conversations` /
`handover` / `mappings` capabilities. The capability methods call `assertPermission` before doing any
@@ -739,12 +739,12 @@ export const PluginCapabilityPermission = {
```
There is no `PermissionChecker` class and no `PermissionDeniedError`. Enforcement of the five
-capability-facade permissions lives in the loader: each capability method calls
+capability-facade permissions lives in `PluginCapabilityContext`: 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)
+// src/core/plugins/plugin-capability-context.ts (paraphrased)
private assertPermission(manifest: PluginManifest, permission: PluginCapabilityPermission): void {
if (!(manifest.permissions ?? []).includes(permission)) {
diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.md
index 13cfe25ff..d71c68245 100644
--- a/docs/24-mcp-integration.md
+++ b/docs/24-mcp-integration.md
@@ -9,16 +9,16 @@
> default** and **purely additive**: when disabled, none of its code (or the MCP SDK)
> is loaded and every REST route behaves exactly as before.
-| Component | Status | Location |
-| -------------------------------------------- | -------------- | ---------------------------------------------------- |
-| **Tool registry (`ToolDescriptor`)** | ✅ Implemented | `src/core/agent-tools/tool-descriptor.ts` |
-| **Tool invoker (auth → validate → service)** | ✅ Implemented | `src/core/agent-tools/tool-invoker.ts` |
-| **Registry service** | ✅ Implemented | `src/core/agent-tools/tool-registry.service.ts` |
-| **Curated tool tables (51 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` |
-| **MCP transport adapter** | ✅ Implemented | `src/modules/mcp/mcp.server.ts` |
-| **Opt-in module gate** | ✅ Implemented | `src/modules/mcp/mcp.module.ts`, `src/app.module.ts` |
-| **Per-key rate limiter** | ✅ Implemented | `src/modules/mcp/mcp-rate-limit.ts` |
-| **Result shaping (smart/json)** | ✅ Implemented | `src/modules/mcp/tool-result.ts` |
+| Component | Status | Location |
+| ------------------------------------------------------------------------- | -------------- | ---------------------------------------------------- |
+| **Tool registry (`ToolDescriptor`)** | ✅ Implemented | `src/core/agent-tools/tool-descriptor.ts` |
+| **Tool invoker (auth → chat gate → validate → chat arguments → service)** | ✅ Implemented | `src/core/agent-tools/tool-invoker.ts` |
+| **Registry service** | ✅ Implemented | `src/core/agent-tools/tool-registry.service.ts` |
+| **Curated tool tables (51 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` |
+| **MCP transport adapter** | ✅ Implemented | `src/modules/mcp/mcp.server.ts` |
+| **Opt-in module gate** | ✅ Implemented | `src/modules/mcp/mcp.module.ts`, `src/app.module.ts` |
+| **Per-key rate limiter** | ✅ Implemented | `src/modules/mcp/mcp-rate-limit.ts` |
+| **Result shaping (smart/json)** | ✅ Implemented | `src/modules/mcp/tool-result.ts` |
| Capability | Status | Notes |
| --------------------------------- | -------------- | --------------------------------------------------------------------- |
@@ -86,7 +86,7 @@ flowchart LR
Client[MCP client] -->|POST /mcp| Adapter
subgraph Core["src/core/agent-tools (SDK-free)"]
Registry[ToolRegistryService<br/>51 ToolDescriptors]
- Invoker[invokeTool<br/>auth → validate → handler]
+ Invoker[invokeTool<br/>auth → chat gate → validate → chat arguments → handler]
end
subgraph Adapter["src/modules/mcp (SDK, opt-in)"]
Server[StreamableHTTP transport]