Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs: backfill missing API reference entries and operator warnings
Yudhi Armyndharise0cbcf9e24d9
diff --git a/.env.example b/.env.exampleindex ebff7a279..c0982e180 100644--- a/.env.example+++ b/.env.example@@ -291,6 +291,9 @@ BAILEYS_AUTH_DIR=./data/baileys# Production refuses to start if this is empty or a known placeholder when DATABASE_TYPE=postgres.# DATABASE_PASSWORD=DATABASE_SYNCHRONIZE=false # WARNING: Set false in production! (data DB)+# WARNING (PII): "true" makes TypeORM log every query WITH its bound parameters, and those+# parameters carry message bodies, phone numbers and webhook payloads. Debug-only on a local+# data set — never enable in production or hand the logs to a wider audience than the DB itself.# DATABASE_LOGGING=false# SQLite file for the 'main' (auth/audit) connection. Must not resolve to DATABASE_NAME.# MAIN_DATABASE_NAME=./data/main.sqlitediff --git a/charts/openwa/values.yaml b/charts/openwa/values.yamlindex ff1b3e4b9..2f0fe66eb 100644--- a/charts/openwa/values.yaml+++ b/charts/openwa/values.yaml@@ -18,6 +18,9 @@ imagePullSecrets: []# NOTE: the container port is fixed at 2785 (containerPort, probes and the Service# targetPort are all pinned to it). Setting PORT here breaks the pod — use# service.port to change the Service port instead.+# PII warning: never leave DATABASE_LOGGING=true here outside a debug session — TypeORM+# then logs every query WITH its parameters (message bodies, phone numbers) into pod+# logs, which a wider RBAC audience can usually read than the database itself.env:NODE_ENV: productionLOG_LEVEL: infodiff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 13115ca5c..1d7e064df 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -842,6 +842,7 @@"installModal": {"title": "تثبيت إضافة","hint": "ارفع إضافة معبّأة بصيغة .zip (تحتوي على manifest.json). تعمل في بيئة معزولة بعد تمكينها.",+ "trustWarning": "تعمل الإضافات بكامل صلاحيات عملية البوابة — البيئة المعزولة تحتوي الأعطال فقط، لا الشيفرة الخبيثة. ثبّت فقط الإضافات التي تثق بها.","choose": "اختر ملف .zip…","tooLarge": "يتجاوز الملف الحد الأقصى البالغ 5 MB.","catalogHint": "ثبّت مباشرة من كتالوج إضافات OpenWA. يتم جلب ملف .zip من جانب الخادم عبر حماية SSRF، ثم يُتحقق منه ويُشغَّل في وضع الحماية.",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 64056a87e..00084be66 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -827,6 +827,7 @@"installModal": {"title": "Plugin installieren","hint": "Lade ein als ZIP-Datei verpacktes Plugin mit einer manifest.json hoch. Nach der Aktivierung wird es in einer Sandbox ausgeführt.",+ "trustWarning": "Plugins laufen mit den vollen Prozessrechten des Gateways — die Sandbox fängt Abstürze ab, keinen Schadcode. Installiere nur Plugins, denen du vertraust.","choose": "ZIP-Datei auswählen…","tooLarge": "Die Datei überschreitet das Limit von 5 MB.","catalogHint": "Installieren Sie direkt aus dem OpenWA-Plugin-Katalog. Die .zip-Datei wird serverseitig durch den SSRF-Schutz abgerufen, dann validiert und in einer Sandbox ausgeführt.",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 18d877ba1..9e9d61419 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -827,6 +827,7 @@"installModal": {"title": "Install a plugin","hint": "Upload a plugin packaged as a .zip (with a manifest.json). It runs sandboxed once enabled.",+ "trustWarning": "Plugins run with the gateway's full process privileges — the sandbox contains crashes, not malicious code. Install only plugins you trust.","choose": "Choose a .zip file…","tooLarge": "The file exceeds the 5 MB limit.","catalogHint": "Install directly from the OpenWA plugin catalog. The .zip is fetched server-side through the SSRF guard, then validated and sandboxed.",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 53342bb67..a5fa235e0 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -827,6 +827,7 @@"installModal": {"title": "Instalar un plugin","hint": "Sube un plugin empaquetado como un .zip (con un manifest.json). Se ejecuta en modo aislado una vez habilitado.",+ "trustWarning": "Los plugins se ejecutan con todos los privilegios del proceso de la puerta de enlace: el modo aislado contiene fallos, no código malicioso. Instala solo plugins en los que confíes.","choose": "Elige un archivo .zip…","tooLarge": "El archivo supera el límite de 5 MB.","catalogHint": "Instala directamente desde el catálogo de plugins de OpenWA. El .zip se obtiene en el servidor a través de la protección SSRF, luego se valida y se ejecuta en sandbox.",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex f8914f761..ff63594e2 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -827,6 +827,7 @@"installModal": {"title": "Installer un plugin","hint": "Téléversez un plugin empaqueté au format .zip (avec un manifest.json). Il s'exécute en bac à sable une fois activé.",+ "trustWarning": "Les plugins s'exécutent avec tous les privilèges du processus de la passerelle — le bac à sable contient les plantages, pas le code malveillant. N'installez que des plugins de confiance.","choose": "Choisir un fichier .zip…","tooLarge": "Le fichier dépasse la limite de 5 MB.","catalogHint": "Installez directement depuis le catalogue de plugins OpenWA. Le .zip est récupéré côté serveur via la protection SSRF, puis validé et exécuté en sandbox.",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 7cfb68f80..57a7e531e 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -836,6 +836,7 @@"installModal": {"title": "התקנת תוסף","hint": "ניתן להעלות תוסף ארוז כקובץ .zip (הכולל manifest.json). הוא פועל בארגז חול לאחר ההפעלה.",+ "trustWarning": "תוספים רצים עם הרשאות התהליך המלאות של השער — ארגז החול מכיל קריסות, לא קוד זדוני. התקינו רק תוספים שאתם סומכים עליהם.","choose": "בחירת קובץ .zip…","tooLarge": "הקובץ חורג מהמגבלה של 5 MB.","catalogHint": "התקינו ישירות מקטלוג התוספים של OpenWA. קובץ ה-.zip נשלף מהשרת דרך מגן ה-SSRF, מאומת ומורץ בארגז חול.",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex b6fb2a01e..8b97d54bc 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -827,6 +827,7 @@"installModal": {"title": "Installa un plugin","hint": "Carica un plugin pacchettizzato come file .zip (con un manifest.json). Viene eseguito in sandbox una volta abilitato.",+ "trustWarning": "I plugin vengono eseguiti con i pieni privilegi del processo del gateway — la sandbox contiene gli arresti anomali, non il codice dannoso. Installa solo plugin di cui ti fidi.","choose": "Scegli un file .zip…","tooLarge": "Il file supera il limite di 5 MB.","catalogHint": "Installa direttamente dal catalogo dei plugin di OpenWA. Lo .zip viene recuperato lato server tramite la protezione SSRF, quindi validato ed eseguito in sandbox.",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex d913c4465..a9a382def 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -827,6 +827,7 @@"installModal": {"title": "플러그인 설치","hint": "manifest.json이 포함된 .zip으로 패키징된 플러그인을 업로드하세요. 활성화되면 샌드박스에서 실행됩니다.",+ "trustWarning": "플러그인은 게이트웨이의 전체 프로세스 권한으로 실행됩니다. 샌드박스는 충돌만 격리할 뿐 악성 코드는 막지 못합니다. 신뢰할 수 있는 플러그인만 설치하세요.","choose": ".zip 파일 선택…","tooLarge": "파일이 5MB 제한을 초과합니다.","catalogHint": "OpenWA 플러그인 카탈로그에서 직접 설치하세요. .zip 파일은 SSRF 가드를 통해 서버에서 가져온 후 검증되고 샌드박스에서 실행됩니다.",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex e48effbca..cb05f62d2 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -827,6 +827,7 @@"installModal": {"title": "Instalar um plugin","hint": "Envie um plugin empacotado como .zip (com um manifest.json). É executado em modo isolado quando habilitado.",+ "trustWarning": "Plugins são executados com todos os privilégios do processo do gateway — o modo isolado contém falhas, não código malicioso. Instale apenas plugins em que você confia.","choose": "Escolha um arquivo .zip…","tooLarge": "O arquivo excede o limite de 5 MB.","catalogHint": "Instale diretamente do catálogo de plugins do OpenWA. O .zip é baixado no servidor através da proteção SSRF, depois validado e executado em sandbox.",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 985e3b2ba..c2cbe0878 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -827,6 +827,7 @@"installModal": {"title": "ఒక ప్లగిన్ను ఇన్స్టాల్ చేయి","hint": "ఒక .zip గా ప్యాక్ చేయబడిన ప్లగిన్ను అప్లోడ్ చేయండి (manifest.json తో). ప్రారంభించిన తర్వాత ఇది శాండ్బాక్స్లో రన్ అవుతుంది.",+ "trustWarning": "ప్లగిన్లు గేట్వే ప్రాసెస్ యొక్క పూర్తి అధికారాలతో నడుస్తాయి — శాండ్బాక్స్ క్రాష్లను మాత్రమే అడ్డుకుంటుంది, హానికరమైన కోడ్ను కాదు. మీరు విశ్వసించే ప్లగిన్లను మాత్రమే ఇన్స్టాల్ చేయండి.","choose": "ఒక .zip ఫైల్ను ఎంచుకోండి…","tooLarge": "ఫైల్ 5 MB పరిమితిని మించిపోయింది.","catalogHint": "OpenWA ప్లగిన్ కేటలాగ్ నుండి నేరుగా ఇన్స్టాల్ చేయండి. .zip సర్వర్లో SSRF గార్డ్ ద్వారా పొందబడి, ఆపై ధృవీకరించబడి శాండ్బాక్స్లో అమలవుతుంది.",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 915caca12..947f153d5 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -827,6 +827,7 @@"installModal": {"title": "Bir eklenti yükle","hint": ".zip olarak paketlenmiş (manifest.json içeren) bir eklenti yükleyin. Etkinleştirildiğinde yalıtılmış alanda (sandbox) çalışır.",+ "trustWarning": "Eklentiler, ağ geçidinin tüm süreç yetkileriyle çalışır — yalıtılmış alan (sandbox) çökmeleri kontrol altına alır, kötü amaçlı kodu değil. Yalnızca güvendiğiniz eklentileri yükleyin.","choose": "Bir .zip dosyası seçin…","tooLarge": "Dosya 5 MB sınırını aşıyor.","catalogHint": "Doğrudan OpenWA eklenti kataloğundan yükleyin. .zip dosyası SSRF koruması üzerinden sunucu tarafında çekilir, ardından doğrulanır ve korumalı alana alınır.",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex c9ec9ff99..b801f4b1f 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -827,6 +827,7 @@"installModal": {"title": "安装插件","hint": "上传打包为 .zip 的插件(包含 manifest.json)。启用后将在沙箱中运行。",+ "trustWarning": "插件以网关进程的完整权限运行——沙箱只能隔离崩溃,无法防御恶意代码。请只安装你信任的插件。","choose": "选择 .zip 文件…","tooLarge": "文件超过 5 MB 限制。","catalogHint": "直接从 OpenWA 插件目录安装。.zip 文件由服务器通过 SSRF 防护获取,然后经过验证并在沙箱中运行。",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 0210d257b..4fbbe07c0 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -827,6 +827,7 @@"installModal": {"title": "安裝外掛","hint": "上載打包成 .zip 的外掛(內含 manifest.json)。啟用後會以沙盒方式執行。",+ "trustWarning": "外掛會以閘道處理程序的完整權限執行——沙盒只能隔離當機,不能阻擋惡意程式碼。請只安裝你信任的外掛。","choose": "選擇 .zip 檔案…","tooLarge": "檔案超出 5 MB 上限。","catalogHint": "直接從 OpenWA 外掛目錄安裝。.zip 檔案由伺服器透過 SSRF 防護取得,然後經過驗證並在沙箱中執行。",diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex 2ec323e3c..a2135cd11 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -703,6 +703,20 @@color: var(--text-muted);}+/* Trusted-code warning at the top of the install modal — the warning colour and the icon mark it+ as a caution, not a hint (mirrors .migration-warning on the infrastructure page). */+.plugins-page .install-hint-warning {+ display: flex;+ gap: 0.4rem;+ align-items: flex-start;+ color: var(--warning);+}++.plugins-page .install-hint-warning svg {+ flex-shrink: 0;+ margin-top: 0.15rem;+}+/* Inline "Catalog" link inside the sub-hint — looks like a link, not a button, so it doesn't competewith the tab strip above or the footer actions. */.plugins-page .install-inline-link {diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 95625c22d..a877251c5 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -984,6 +984,15 @@ export default function Plugins() {)}>+ {/* Trusted-code warning sits ABOVE the tab conditional: upload and catalog land the+ same payload in the same process, so it must show on both. */}+ <p className="install-hint install-hint-warning">+ <AlertCircle size={15} />+ {t(+ 'plugins.installModal.trustWarning',+ "Plugins run with the gateway's full process privileges — the sandbox contains crashes, not malicious code. Install only plugins you trust.",+ )}+ </p>{installMode === 'upload' ? (<><p className="install-hint">diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 8d52a634e..56061a151 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -271,6 +271,64 @@ Get a single session by ID.**Errors:** `401` missing/invalid key, or key not scoped to this session · `404` session not found+#### GET /api/sessions/:id/config++Get the effective tunable configuration for a session. Only the three recognised keys are reported,+resolved through the same clamps the engine applies — the opaque stored `config` column is never+echoed back (it is stripped from `SessionResponseDto` alongside `proxyUrl`, and anything else placed+in it is stored but ignored).++**Auth:** API key · **Scope:** session-scoped (key's `allowedSessions` enforced against `:id`)++**Path parameters**++| Name | Type | Description |+| ---- | ------ | ------------ |+| `id` | string | Session UUID |++**Response** `200`++```json+{ "autoRejectCalls": false, "maxReconnectAttempts": null, "reconnectBaseDelay": 5000 }+```++`maxReconnectAttempts: null` means unlimited (the default); `reconnectBaseDelay` is milliseconds.+See §5 (Database Design) for what each key does and the moment it is read.++**Errors:** `401` · `403` key not scoped to this session · `404` session not found++#### PATCH /api/sessions/:id/config++Merge a patch into the session's tunable configuration. No restart is required or performed:+omitted keys keep their stored value, and an explicit `null` clears a key back to its default (the+only way back to unlimited reconnect attempts once a cap is set). `autoRejectCalls` is re-read on+every incoming call, so it applies immediately; the two reconnect settings are read once per start+and therefore apply on the next start, leaving a reconnect sequence already in flight alone.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped++**Path parameters**++| Name | Type | Description |+| ---- | ------ | ------------ |+| `id` | string | Session UUID |++**Request body** — `UpdateSessionConfigDto` (any subset; each key also accepts `null`)++| Field | Type | Constraints | Description |+| ---------------------- | ------- | ------------------------- | ------------------------------------------------------------------ |+| `autoRejectCalls` | boolean | — | Auto-reject every incoming call as soon as it rings |+| `maxReconnectAttempts` | number | integer, 0–20 | Reconnect attempt cap (`0` disables reconnect; `null` = unlimited) |+| `reconnectBaseDelay` | number | integer, 1000–300000 (ms) | Base delay of the reconnect backoff |++```json+{ "maxReconnectAttempts": 5 }+```++**Response** `200` — the resulting `SessionConfigResponseDto` (same shape as the GET above).++**Errors:** `400` a supplied value is outside its accepted range · `401` · `403` key lacks OPERATOR role or is not scoped to this session · `404` session not found+#### GET /api/sessions/:id/qrGet the QR code (PNG data URL) for session authentication.@@ -6395,6 +6453,166 @@ Partial update (any subset of the create fields). **Auth:** API key (OPERATOR)Delete a rule. **Auth:** API key (OPERATOR) · **Response** `204`.+### 6.4.17 Integration fabric (ingress & instances)++The operator surface of the Integration Fabric — **doc 25** holds the design (DLQ, ordering,+per-instance fairness); this section is the route reference. An ADMIN key provisions per-plugin+instances — one bound provider account, e.g. one Chatwoot inbox — and each instance gets one+ingress URL per route the plugin declares. Only a plugin that declares an ingress route AND the+`webhook:ingress` permission can have instances; any other plugin is rejected before persistence.++An instance's ingress `secret` and `verifyToken` are revealed **once** — in the create and+regenerate-secret responses — and masked (`***`) on every later read. `config` fields flagged+`secret` in the plugin's config schema stay masked even in those one-shot reveal responses.++Every instance route is session-scope aware: a key restricted to `allowedSessions` only sees+instances bound to one of its own sessions, and an out-of-scope instance answers `404` (identical+to a missing one), so the routes cannot probe which instances exist on other sessions. The DLQ+redrive route is documented with the administration routes in §6.4.11.++#### POST /api/integration/plugins/:pluginId/instances++Create an instance of an ingress-capable plugin.++**Auth:** API key (ADMIN)++**Path parameters**++| Name | Type | Description |+| ---------- | ------ | ---------------------------------------------------------------- |+| `pluginId` | string | Plugin to instantiate (must declare ingress + `webhook:ingress`) |++**Request body** — `CreateInstanceDto`++| Field | Type | Required | Constraints | Description |+| -------------- | ------ | -------- | ------------------------------------------- | ------------------------------------------------------------------------------------------ |+| `instanceId` | string | Yes | `^[a-zA-Z0-9_-]{1,64}$` | Operator-chosen id, unique within the plugin; namespaces the ingress URL and the secret |+| `sessionScope` | string | No | non-empty when present, ≤ 256 chars | Session id the instance is bound to. Omit for all sessions |+| `verifyToken` | string | No | ≤ 512 chars | Token echoed in the provider's verification handshake. Auto-generated when omitted |+| `secret` | string | No | 16–512 chars | Ingress HMAC secret shared with the provider. Omit to auto-generate a random 64-hex secret |+| `config` | object | No | shape defined by the plugin's config schema | Per-instance config slice passed to the adapter |++```json+{ "instanceId": "chatwoot-prod-1", "sessionScope": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a" }+```++**Response** `201` — the `InstanceView`, with the plaintext `secret` and `verifyToken` revealed+**in this response only** — store them immediately.++```json+{+ "id": "0e2f…",+ "pluginId": "chatwoot",+ "instanceId": "chatwoot-prod-1",+ "sessionScope": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a",+ "secret": "9f2c…64-hex…",+ "verifyToken": "a1b2c3d4e5f6",+ "config": { "inboxId": 42 },+ "enabled": true,+ "createdAt": "2026-08-01T10:00:00.000Z",+ "updatedAt": "2026-08-01T10:00:00.000Z",+ "ingressUrls": [+ { "route": "events/message", "url": "https://wa.example.com/api/ingress/chatwoot/chatwoot-prod-1/events/message" }+ ]+}+```++`ingressUrls[].url` is absolute when `BASE_URL` is set, otherwise a relative path to prepend with+the deployment's own host.++**Errors:** `400` validation, or the plugin is not ingress-capable · `401` · `403` key role < ADMIN, or `sessionScope` outside the key's `allowedSessions` · `404` unknown plugin · `409` instance id already exists++#### GET /api/integration/plugins/:pluginId/instances++List the plugin's instances visible to the calling key (secrets masked).++**Auth:** API key (ADMIN)++**Response** `200` — bare array of `InstanceView`. An instance whose `sessionScope` is outside the+key's `allowedSessions` is filtered out of the list.++**Errors:** `401` · `403`++#### GET /api/integration/plugins/:pluginId/instances/:instanceId++Get one instance (secret masked).++**Auth:** API key (ADMIN)++**Path parameters**++| Name | Type | Description |+| ------------ | ------ | ----------- |+| `pluginId` | string | Plugin id |+| `instanceId` | string | Instance id |++**Response** `200` — the `InstanceView`.++**Errors:** `401` · `403` · `404` unknown instance, or one outside the key's `allowedSessions`++#### PATCH /api/integration/plugins/:pluginId/instances/:instanceId++Update an instance (secret masked in the response). Any subset of:++| Field | Type | Description |+| -------------- | ------- | ------------------------------------------------------------------------------------------------------------------- |+| `enabled` | boolean | Whether ingress is accepted and dispatch is active |+| `sessionScope` | string | Re-bind to another session (must be inside the key's `allowedSessions`; the old scope's binding is torn down first) |+| `config` | object | Replace the per-instance config slice |++**Auth:** API key (ADMIN)++**Response** `200` — the updated `InstanceView`.++**Errors:** `400` validation · `401` · `403` key role < ADMIN, or the new `sessionScope` outside the key's `allowedSessions` · `404` unknown instance, or one outside the key's scope++#### DELETE /api/integration/plugins/:pluginId/instances/:instanceId++Delete the instance and tear down its session-scope binding.++**Auth:** API key (ADMIN)++**Response** `204`++**Errors:** `401` · `403` · `404` unknown instance, or one outside the key's scope++#### POST /api/integration/plugins/:pluginId/instances/:instanceId/regenerate-secret++Rotate the instance's ingress HMAC secret.++**Auth:** API key (ADMIN)++**Response** `200` — the `InstanceView` with the **new** plaintext `secret` revealed in this+response only; the `verifyToken` is also shown (unchanged).++**Errors:** `401` · `403` · `404` unknown instance, or one outside the key's scope++#### GET /api/ingress/:pluginId/:instanceId/:path++#### POST /api/ingress/:pluginId/:instanceId/:path++#### PUT /api/ingress/:pluginId/:instanceId/:path++#### PATCH /api/ingress/:pluginId/:instanceId/:path++#### DELETE /api/ingress/:pluginId/:instanceId/:path++One route, any HTTP method: the inbound webhook endpoint an external provider delivers to. The+trailing `:path` segment is the plugin-declared route (it may contain slashes, e.g.+`events/message`); a delivery to a route the plugin did not claim is a `404`.++**Auth:** **none** — `@Public` by design, because a provider cannot present an API key. What+authenticates a delivery is the per-instance HMAC signature over the exact raw body bytes (the body+is read raw, never DTO-bound, so the signed bytes reach the verifier unchanged). A `GET` here is+the provider's verification handshake and answers only when its `verifyToken` matches.++**Response** — the primary success path is `202`: the delivery is persisted and queued for async+plugin processing. `200` means the `GET` verification-challenge echo, or a duplicate delivery+already persisted (idempotent re-delivery). A route may shape the synchronous status/body/headers+the provider sees via its declarative `ack` config (doc 25); the plugin itself always runs async.++**Errors:** `401` signature verification failed (missing, stale, or wrong secret) · `403` `GET` verification challenge failed (`verifyToken` mismatch) · `404` unknown pluginId/instanceId, or no such claimed route · `413` body over the route's `maxBodyBytes` · `429` per-instance rate limit (`INGRESS_INSTANCE_LIMIT` per `INGRESS_INSTANCE_TTL`, on top of the global per-IP throttle)+## 6.5 Real-time API (WebSocket)Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 00f263179..61af20535 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -26,7 +26,7 @@ Responses are the **raw payload** — no `{ success, data }` envelope. A resourc### Sections-Sessions · Messages · Webhooks · Groups · Contacts · Chats · Labels · Channels · Catalog · Templates · Plugins · Settings · Auth (API Keys) · Health · Infrastructure · Stats · Metrics · Events (WebSocket).+Sessions · Messages · Webhooks · Groups · Contacts · Chats · Labels · Channels · Catalog · Templates · Plugins · Settings · Auth (API Keys) · Health · Infrastructure · Stats · Audit · Metrics · Profile · Search · Media conversion · Events (WebSocket).## 07.2 Endpoints@@ -171,6 +171,41 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/pairing-co-d '{ "phoneNumber": "628123456789" }'```+#### POST /api/sessions/:id/presence/subscribe++Subscribe to presence updates (online/typing) for a chat (OPERATOR). Baileys only — whatsapp-web.js+answers `501`. The subscription belongs to the connection: re-issue it after a restart or reconnect.+Updates arrive as the `presence.update` webhook/socket event.++```bash+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence/subscribe" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "chatId": "[email protected]" }'+```++#### GET /api/sessions/:id/presence/:chatId++Read the last presence report received for a chat (any role). Returns `200` with a `null` body when+nothing has been reported yet — presence is held in memory, never persisted.++```bash+curl "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence/[email protected]" \+ -H "X-API-Key: $API_KEY"+```++#### PUT /api/sessions/:id/presence++Set the account's OWN global presence — appear online or offline (OPERATOR, both engines). The+setting does not survive a restart or reconnect; re-issue it after `session.status` reports one.++```bash+curl -X PUT "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "available": false }'+```+#### POST /api/sessions/:id/chats/readMark a chat as read/seen (OPERATOR).@@ -506,6 +541,17 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/delete" \-d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "forEveryone": true }'```+#### POST /api/sessions/:sessionId/messages/edit++Edit the text of a message sent by this account (OPERATOR); the edited message keeps its original id.++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/edit" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "body": "Corrected text" }'+```+#### POST /api/sessions/:sessionId/messages/send-bulkSend to multiple recipients as an async batch (max 100 messages; exact duplicate entries — same `chatId`, `type`, `content` and `variables` — are collapsed, first occurrence wins).@@ -742,6 +788,62 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/invi-H "X-API-Key: $API_KEY"```+#### GET /api/sessions/:sessionId/groups/join-info++Preview a group from its invite code WITHOUT joining (both engines). Read-only, so it is safe to+call on a code from an untrusted source. There is no participant list — only `participantCount`,+and only when WhatsApp discloses one.++```bash+curl "$BASE/api/sessions/$SESSION_ID/groups/join-info?code=XyZ987654321" \+ -H "X-API-Key: $API_KEY"+```++#### POST /api/sessions/:sessionId/groups/join++Join a group via an invite code — the part after `https://chat.whatsapp.com/` (OPERATOR).++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/join" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "inviteCode": "XyZ987654321" }'+```++#### GET /api/sessions/:sessionId/groups/:groupId/membership-requests++List a group's pending join requests (the queue the `group.join_request` event announces). The+account must be a group admin — WhatsApp refuses the read otherwise (`403`).++```bash+curl "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/membership-requests" \+ -H "X-API-Key: $API_KEY"+```++#### POST /api/sessions/:sessionId/groups/:groupId/membership-requests/approve++Approve pending join requests (OPERATOR) — the named requesters, or EVERY pending request when the+body names none. The response carries a per-requester `results` list; a partial refusal does not+fail the batch.++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/membership-requests/approve" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "participants": ["[email protected]"] }'+```++#### POST /api/sessions/:sessionId/groups/:groupId/membership-requests/reject++Reject pending join requests (OPERATOR). Same body, response shape and batch contract as `approve`.++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/membership-requests/reject" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "participants": ["[email protected]"] }'+```+### 07.7 Message TemplatesAll template routes are nested under a session and require an OPERATOR-level key.@@ -973,6 +1075,16 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/status/send-video" \-d '{ "video": { "url": "https://example.com/clip.mp4" }, "caption": "Watch this" }'```+```bash+# Post a voice-note status (OPERATOR). WhatsApp only plays Ogg/Opus — neither engine+# transcodes, so convert first via media/convert/voice and post the base64 it returns.+# `recipients` (the viewer allow-list) is honored on Baileys only. There is no `caption`.+curl -X POST "$BASE/api/sessions/$SESSION_ID/status/send-voice" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "audio": { "base64": "T2dnUwACAAAA..." }, "recipients": ["[email protected]"] }'+```+```bash# Delete one of the session's own posted statuses (OPERATOR)curl -X DELETE "$BASE/api/sessions/$SESSION_ID/status/false_status@broadcast_3A1F" \@@ -1010,6 +1122,17 @@ curl -X GET "$BASE/api/webhooks?limit=100&offset=0" \-H "X-API-Key: $API_KEY"```+#### GET /api/webhooks/delivery-failures++List webhook deliveries that exhausted every retry, most recent first (ADMIN; results stay confined+to the key's allowed sessions). `lastStatusCode` is `null` when the failure was a+network/timeout/SSRF error rather than a non-2xx response.++```bash+curl -X GET "$BASE/api/webhooks/delivery-failures?limit=100&offset=0" \+ -H "X-API-Key: $API_KEY"+```+#### POST /api/sessions/:sessionId/webhooksCreate a webhook for the session.@@ -1149,7 +1272,7 @@ curl -X POST "$BASE/api/auth/validate" \-H "X-API-Key: $API_KEY"```-### 07.12 System (Health, Metrics, Stats, Settings)+### 07.12 System (Health, Metrics, Stats, Settings, Audit)#### GET /api/health@@ -1229,6 +1352,18 @@ curl -X PUT "$BASE/api/settings" \-H "X-API-Key: $API_KEY"```+#### GET /api/audit++List audit-log entries, newest first (ADMIN; rows stay confined to the key's allowed sessions).+Unlike the other list routes the body is `{ "data", "total" }` — the page plus the unpaginated+match count. Filters: `action`, `severity` (`info` | `warn` | `error`), `sessionId`, `apiKeyId`,+plus `limit` (default 50, max 200) and `offset`.++```bash+curl -X GET "$BASE/api/audit?action=session_started&limit=50" \+ -H "X-API-Key: $API_KEY"+```+### 07.13 Administration (Infrastructure, Plugins, MCP)ADMIN-only operations (except the public health check and the MCP transport). Assumes `BASE`, `API_KEY`, and — for MCP — that `MCP_ENABLED=true`.@@ -1523,7 +1658,116 @@ curl -X POST "$BASE/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)+### 07.14 Profile (own account)++Manage the linked account's own profile. All routes are nested under a session and require an+OPERATOR key.++#### PUT /api/sessions/:sessionId/profile/name++Set the account display name (max 25 chars).++```bash+curl -X PUT "$BASE/api/sessions/$SESSION_ID/profile/name" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "name": "ACME Support" }'+```++#### PUT /api/sessions/:sessionId/profile/status++Set the account about/status text (max 139 chars; empty string clears it).++```bash+curl -X PUT "$BASE/api/sessions/$SESSION_ID/profile/status" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "status": "We reply within one business day" }'+```++#### PUT /api/sessions/:sessionId/profile/picture++Set the account profile picture from a URL or base64 image (same media DTO conventions as message+sends).++```bash+curl -X PUT "$BASE/api/sessions/$SESSION_ID/profile/picture" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "url": "https://example.com/avatar.png" }'+```++#### DELETE /api/sessions/:sessionId/profile/picture++Remove the account profile picture (WhatsApp's default avatar takes over). Removing a picture that+is already absent is a no-op and also answers `200`.++```bash+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/profile/picture" \+ -H "X-API-Key: $API_KEY"+```++### 07.15 Search++Cross-session full-text message search (OPERATOR or higher). On by default; `SEARCH_ENABLED=false`+removes the route and module entirely. A scoped key's `allowedSessions` is applied server-side and+cannot be widened via the query. See doc 26 for the provider contract.++#### GET /api/search++Search messages across sessions. `q` is required (non-empty after trim); optional filters are+`sessionId`, `chatId`, `direction` (`incoming` | `outgoing`), `type`, `from`, `dateFrom`/`dateTo`+(epoch ms), plus `limit` (default 50, clamped to `SEARCH_LIMIT_MAX` = 100) and `offset`. Hit+`snippet` fields carry `<mark>` highlight markers — render them as text, never as HTML.++```bash+curl -X GET "$BASE/api/search?q=invoice&direction=incoming&limit=20" \+ -H "X-API-Key: $API_KEY"+```++### 07.16 Media conversion (opt-in)++Server-side transcoding into the shapes WhatsApp clients actually play. Disabled by default; set+`MEDIA_CONVERSION_ENABLED=true`, and `ffmpeg` must be runnable (the official Docker image ships it)+or the routes answer `503`. Nothing is converted implicitly — run media through here first, then+post the result.++#### GET /api/sessions/:sessionId/media/convert++Report whether conversion is switched on and runnable here (`{ "available": true }`). Any role.++```bash+curl "$BASE/api/sessions/$SESSION_ID/media/convert" \+ -H "X-API-Key: $API_KEY"+```++#### POST /api/sessions/:sessionId/media/convert/voice++Convert audio (or a video's audio track) into a WhatsApp voice note — Ogg/Opus, mono, 48 kHz+(OPERATOR). Exactly one of `url` / `base64`. Post the returned `base64` to `messages/send-audio`+with `ptt: true` (or to `status/send-voice`).++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/media/convert/voice" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "url": "https://example.com/voice-memo.mp3" }'+```++#### POST /api/sessions/:sessionId/media/convert/video++Convert video into a baseline H.264/AAC MP4 every WhatsApp client accepts (OPERATOR); same request+body and errors as the voice endpoint. Both responses are bounded by+`MEDIA_CONVERSION_MAX_OUTPUT_BYTES` (default 50 MiB).++```bash+curl -X POST "$BASE/api/sessions/$SESSION_ID/media/convert/video" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "url": "https://example.com/clip.mov" }'+```++### 07.17 Real-time (WebSocket)Events are delivered over **Socket.IO** on the `/events` namespace (not a raw WebSocket). Use the `socket.io-client` package. Set `BASE_WS` (e.g. `ws://localhost:2785`) and `API_KEY`.diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.mdindex 09511df3d..80f3f3271 100644--- a/docs/08-development-guidelines.md+++ b/docs/08-development-guidelines.md@@ -276,6 +276,32 @@ export class CreateExampleDto {}```+### Global modules — the fixed set++`@Global()` makes a module's exported providers injectable everywhere without an import, which is+convenient exactly until two modules both assume they own a name and the injector silently picks+one. The sanctioned set is therefore frozen at these ten — every one of them a cross-cutting+concern that nearly every module would otherwise have to import:++| Module | Path | Why it is global |+| ------------------ | -------------------------------------------- | ----------------------------------------------------- |+| `AuthModule` | `src/modules/auth/auth.module.ts` | API-key guard + role checks run on nearly every route |+| `AuditModule` | `src/modules/audit/audit.module.ts` | Every mutation surface writes audit entries |+| `EventsModule` | `src/modules/events/events.module.ts` | The event bus fans out from every module |+| `EngineModule` | `src/engine/engine.module.ts` | `EngineRegistry`, the narrow port to the live engines |+| `PluginsModule` | `src/core/plugins/plugins.module.ts` | Plugin services are consumed across modules |+| `HooksModule` | `src/core/hooks/hooks.module.ts` | `HookManager` is invoked from unrelated modules |+| `CacheModule` | `src/common/cache/cache.module.ts` | Shared cache service |+| `StorageModule` | `src/common/storage/storage.module.ts` | File/media storage used across modules |+| `LoggerModule` | `src/common/services/logger.module.ts` | The logger is needed literally everywhere |+| `AgentToolsModule` | `src/core/agent-tools/agent-tools.module.ts` | The tool registry is shared by MCP and the REST layer |++Do not add an eleventh. A new global needs an ADR-level justification — written down and reviewed+with the same weight as an architecture decision record — because the cost (implicit coupling,+order-dependent provider resolution, tests that pass only because the whole app booted) is paid by+every future module, not by the one that opts out of an explicit `imports` entry. The default for a+new module is the standard template above: declare `exports` and let consumers `imports` you.+## 8.4 Git Workflow### Branch Strategy@@ -891,6 +917,8 @@ npm run lint -- --fix# Debug database queries (TypeORM) — add to .env:# DATABASE_LOGGING=true# (there is no DEBUG=typeorm:query switch; both connections read DATABASE_LOGGING)+# PII warning: this logs full queries WITH bound parameters — message bodies and phone+# numbers end up in the application log. Use on a local/debug data set only, never in production.# View Docker logs (service is `openwa-api` in docker-compose.yml, `openwa` in# docker-compose.dev.yml — there is no service named `app`)diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex c6b7e6e5f..32d8b33ea 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -616,6 +616,14 @@ route requires the `ADMIN` role** (`@RequireRole(ApiKeyRole.ADMIN)` — not a bais **no** `POST :id/reload` and **no** `GET :id/config`. Install is a multipart `.zip` upload (or byURL / catalog), not an npm/github source descriptor.+> **Installed plugins are trusted code.** The worker sandbox (doc 30) is crash and heap-OOM+> _containment_, not a security boundary: plugin code runs inside the gateway's OS process and can+> reach Node built-ins (`fs`, `net`, `child_process`) directly — the capability permission model+> gates only the `ctx.*` verbs, not raw Node access. The SSRF guard and digest pin on+> `install-url` protect the _delivery_ of the package, not what the package does once loaded.+> Install only plugins you trust, and keep the OS-level containment from doc 30 (container,+> read-only rootfs, dropped capabilities) in place when you do.+| Method & path | Purpose || ------------------------------------ | ---------------------------------------------------------------------------------------------------------- || `GET /plugins` | List all plugins |diff --git a/sdk/README.md b/sdk/README.mdindex e6e979787..88725997f 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -52,6 +52,14 @@ All five SDKs expose the same fluent resource surface:> Everything else the gateway publishes is exposed. That sentence used to be an> unqualified "all user-facing resources are", which was false for the session> config routes and the two cross-session webhook reads until they were added.+>+> One entry in the list above is special: `mcp` is absent from the generated+> `openapi.json` itself, not just from the SDKs — `POST /mcp` is mounted directly+> on the Express adapter, outside the Nest `/api` routing the Swagger scanner+> sees, so the exporter cannot emit it. Do not hand-add it to `openapi.json`+> (`npm run openapi:check` regenerates the file and the diff fails); the route is+> documented by hand in `docs/06-api-specification.md`, and the docs-contract+> gate names `POST /mcp` as the one heading allowed outside the contract.## JavaScript / TypeScriptdiff --git a/src/common/openapi/docs-06-contract.spec.ts b/src/common/openapi/docs-06-contract.spec.tsindex 65d054dc2..5e3a1debf 100644--- a/src/common/openapi/docs-06-contract.spec.ts+++ b/src/common/openapi/docs-06-contract.spec.ts@@ -55,27 +55,17 @@ describe('docs/06 matches the published contract', () => {);/**- * Operations documented outside docs/06, each naming the file that documents it. The backing check- * below reads that file, so an entry cannot become a silent exemption.+ * Operations deliberately documented in another file carry an allowlist entry naming that file, and+ * the gate reads the file to confirm the path is really there — otherwise "documented in docs/25"+ * would be an unchecked claim, which is the exact failure this gate exists to prevent.+ *+ * The set is EMPTY today: every operation the contract publishes carries its own heading in+ * docs/06 (the session-config routes and the integration instance/ingress family moved in from+ * docs/05 and docs/25, which keep their design-level treatment). The mechanism stays for a future+ * deliberate exception — an entry is honored only while the named file really contains the path+ * and docs/06 has no heading for it, and the stale-entry test below retires it automatically.*/- const DOCUMENTED_ELSEWHERE = new Map<string, string>([- ['GET /api/ingress/:pluginId/:instanceId/:path', 'docs/25-integration-fabric.md'],- ['POST /api/ingress/:pluginId/:instanceId/:path', 'docs/25-integration-fabric.md'],- ['PUT /api/ingress/:pluginId/:instanceId/:path', 'docs/25-integration-fabric.md'],- ['PATCH /api/ingress/:pluginId/:instanceId/:path', 'docs/25-integration-fabric.md'],- ['DELETE /api/ingress/:pluginId/:instanceId/:path', 'docs/25-integration-fabric.md'],- ['GET /api/integration/plugins/:pluginId/instances', 'docs/25-integration-fabric.md'],- ['POST /api/integration/plugins/:pluginId/instances', 'docs/25-integration-fabric.md'],- ['GET /api/integration/plugins/:pluginId/instances/:instanceId', 'docs/25-integration-fabric.md'],- ['PATCH /api/integration/plugins/:pluginId/instances/:instanceId', 'docs/25-integration-fabric.md'],- ['DELETE /api/integration/plugins/:pluginId/instances/:instanceId', 'docs/25-integration-fabric.md'],- [- 'POST /api/integration/plugins/:pluginId/instances/:instanceId/regenerate-secret',- 'docs/25-integration-fabric.md',- ],- ['GET /api/sessions/:id/config', 'docs/05-database-design.md'],- ['PATCH /api/sessions/:id/config', 'docs/05-database-design.md'],- ]);+ const DOCUMENTED_ELSEWHERE = new Map<string, string>([]);/*** Headings with no contract operation, and why the contract cannot carry them. `POST /mcp` is@@ -104,8 +94,6 @@ describe('docs/06 matches the published contract', () => {});it('every allowlisted operation is really documented in the file it names', () => {- expect(DOCUMENTED_ELSEWHERE.size).toBeGreaterThan(5);-const unbacked = [...DOCUMENTED_ELSEWHERE].filter(([operation, file]) => !backs(file, operation)).map(([operation, file]) => `${operation} claims ${file}, which does not contain that path`);