Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat: harden runtime reliability and cross-layer contracts (#795)
Yudhi Armyndharisc00cddf9a9ed
diff --git a/.env.example b/.env.exampleindex 322b4fc22..b9533598c 100644--- a/.env.example+++ b/.env.example@@ -228,8 +228,9 @@ S3_SECRET_ACCESS_KEY=# WEBHOOK# =============================================================================WEBHOOK_TIMEOUT=10000 # Timeout in milliseconds-WEBHOOK_MAX_RETRIES=3 # Number of retry attemptsWEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms+# WEBHOOK_DISPATCH_CONCURRENCY=16 # max active inline webhook deliveries per process+# WEBHOOK_DISPATCH_MAX_QUEUED=1000 # max inline deliveries parked behind the concurrency cap# Days to keep webhook delivery-failure records before pruning them (default 90; set <= 0 to disable).# WEBHOOK_FAILURE_RETENTION_DAYS=90# Block outbound WEBHOOK deliveries to internal/reserved addresses (SSRFdiff --git a/.env.minimal b/.env.minimalindex 934e97862..d3747fa02 100644--- a/.env.minimal+++ b/.env.minimal@@ -25,7 +25,6 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage# WebhookWEBHOOK_TIMEOUT=10000-WEBHOOK_MAX_RETRIES=3WEBHOOK_RETRY_DELAY=5000# Storage (Local filesystem)diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3737406b6..ba41fdf61 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -10,6 +10,9 @@ env:NODE_VERSION: '22'DOCKER_PLATFORMS: linux/amd64,linux/arm64+permissions:+ contents: read+jobs:lint:name: Lint@@ -40,7 +43,7 @@ jobs:run: npx tsc --noEmit -p tsconfig.json- name: Check formatting- run: npm run format -- --check+ run: npm run format:check- name: Check version consistency (docs track package.json)run: npm run check:versions@@ -155,6 +158,9 @@ jobs:- name: Run ESLintrun: cd dashboard && npm run lint+ - name: Type-check dashboard tests+ run: cd dashboard && npm run typecheck+- name: Check i18n parityrun: cd dashboard && npm run i18n:checkdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 96411a46a..21f30fa54 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -9,14 +9,13 @@ env:DOCKER_PLATFORMS: linux/amd64,linux/arm64permissions:- contents: write- packages: write+ contents: readjobs:# ──── Release Gate (CI-strength) ──────────────────────────────────# Mirror the CI workflow's gate jobs so a tag can never publish an image or GitHub Release that- # lint, the spec type-check, unit + e2e tests, the Postgres migration smoke, or the dashboard- # build/lint would have rejected. Each job below matches its CI counterpart; only the tag-match+ # lint, the spec type-check, OpenAPI snapshot, unit + e2e tests, the Postgres migration smoke, or the+ # dashboard build/lint/type-check would have rejected. Each job below matches its CI counterpart; only the tag-match# guard and the publish jobs (docker, release) are release-specific.lint:name: Lint@@ -61,11 +60,14 @@ jobs:run: npx tsc --noEmit -p tsconfig.json- name: Check formatting- run: npm run format -- --check+ run: npm run format:check- name: Check version consistency (docs track package.json)run: npm run check:versions+ - name: Check OpenAPI snapshot is up to date+ run: npm run openapi:check+test:name: Testruns-on: ubuntu-latest@@ -163,6 +165,9 @@ jobs:- name: Run ESLintrun: cd dashboard && npm run lint+ - name: Type-check dashboard tests+ run: cd dashboard && npm run typecheck+- name: Check i18n parityrun: cd dashboard && npm run i18n:check@@ -195,6 +200,8 @@ jobs:release:name: GitHub Releaseruns-on: ubuntu-latest+ permissions:+ contents: write# Gate the public Release on every CI-strength job AND a successfully built+pushed image that# also boots, so a tag never produces a GitHub Release without passing the same gate CI enforces,# a matching container image, and a runtime boot check on both architectures (boot-smoke runs the@@ -208,7 +215,7 @@ jobs:- name: Extract version from tagid: version- run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT+ run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_OUTPUT"- name: Extract release notes from CHANGELOGid: changelog@@ -220,9 +227,11 @@ jobs:NOTES="Release v${VERSION}"fi# Use EOF delimiter for multi-line output- echo "NOTES<<EOF" >> $GITHUB_OUTPUT- echo "$NOTES" >> $GITHUB_OUTPUT- echo "EOF" >> $GITHUB_OUTPUT+ {+ echo "NOTES<<EOF"+ echo "$NOTES"+ echo "EOF"+ } >> "$GITHUB_OUTPUT"- name: Create GitHub Releaseuses: softprops/action-gh-release@v3@@ -242,6 +251,9 @@ jobs:docker:name: Docker Releaseruns-on: ubuntu-latest+ permissions:+ contents: read+ packages: writeneeds: [lint, test, test-postgres, dashboard, build]steps:- uses: actions/checkout@v7@@ -295,6 +307,8 @@ jobs:boot-smoke:name: Boot smoke (amd64 + arm64)runs-on: ubuntu-latest+ permissions:+ packages: readneeds: [docker]steps:- name: Set up QEMU@@ -332,7 +346,7 @@ jobs:continuefiok=""- for i in $(seq 1 40); do+ for _ in $(seq 1 40); doif curl -sf http://127.0.0.1:2785/api/health/live >/dev/null 2>&1; then ok=1; break; fisleep 5donediff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.ymlindex d52d13ac4..6f2e70685 100644--- a/.github/workflows/sdk-ci.yml+++ b/.github/workflows/sdk-ci.yml@@ -7,10 +7,29 @@ name: SDK CIon:push:branches: [main, develop]- paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/**/*.controller.ts', 'src/**/*.service.ts', 'src/engine/interfaces/whatsapp-engine.interface.ts']+ paths:+ [+ 'sdk/**',+ '.github/workflows/sdk-ci.yml',+ 'src/**/dto/**',+ 'src/**/*.controller.ts',+ 'src/**/*.service.ts',+ 'src/engine/interfaces/whatsapp-engine.interface.ts',+ ]pull_request:branches: [main, develop]- paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/**/*.controller.ts', 'src/**/*.service.ts', 'src/engine/interfaces/whatsapp-engine.interface.ts']+ paths:+ [+ 'sdk/**',+ '.github/workflows/sdk-ci.yml',+ 'src/**/dto/**',+ 'src/**/*.controller.ts',+ 'src/**/*.service.ts',+ 'src/engine/interfaces/whatsapp-engine.interface.ts',+ ]++permissions:+ contents: readjobs:javascript:@@ -35,8 +54,12 @@ jobs:- run: npm run smoke # dual CJS+ESM consumable — must run after buildpython:- name: Python SDK+ name: Python SDK (${{ matrix.python }})runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ python: ['3.9', '3.12']defaults:run:working-directory: sdk/python@@ -44,13 +67,17 @@ jobs:- uses: actions/checkout@v7- uses: actions/setup-python@v6with:- python-version: '3.12'+ python-version: ${{ matrix.python }}- run: pip install -e '.[dev]'- run: pytestphp:- name: PHP SDK+ name: PHP SDK (${{ matrix.php }})runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ php: ['8.1', '8.2']defaults:run:working-directory: sdk/php@@ -58,7 +85,7 @@ jobs:- uses: actions/checkout@v7- uses: shivammathur/setup-php@v2with:- php-version: '8.2'+ php-version: ${{ matrix.php }}- run: composer install --no-interaction --no-progress- run: ./vendor/bin/phpunitdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 886c66615..923e9a890 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,30 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [Unreleased]++### Changed++- `GET /api/settings` no longer returns the incorrect, always-zero `general.sessionTimeout` field. Clients+ reading that admin-only field should remove the read; no equivalent session timeout exists.+- Java SDK callers sending audio/voice notes now pass `SendAudioRequest` to `sendAudio`; other media sends+ continue to use `SendMediaRequest`. Bulk media uses the nested `BulkMediaRequest` type.+- The PHP SDK's configured `timeout` now applies to every request, including calls made through an injected+ Guzzle client; pass `timeout` explicitly when a different bound is required.+- PHP SDK contributor installs now remain compatible with the declared PHP 8.1 runtime floor, and CI+ exercises the suite on both PHP 8.1 and 8.2.++### Fixed++- Preserve plugin state across package updates, make data/storage backup and restore cover both engine+ auth stores plus generated secrets, and preserve message `chatName` during data import.+- Bound webhook and integration redrive work, make Redis throttling atomic, guard stale engine teardown,+ and make media precedence, data-URI normalization, limits, and omission markers consistent across engines.+- Record API-key authorization changes in administrative activity logs, protect the final usable admin,+ and align action-style POST routes with their documented HTTP `200` responses.+- Correct ingress method/verification/dedup metadata, dashboard session-state visibility and plugin config+ fallback, SDK timeout/type parity, metrics types, deployment configuration forwarding, and CI contract gates.+## [0.8.19] - 2026-07-17### Addeddiff --git a/README.md b/README.mdindex bec79091e..5038b91ab 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@**OpenWA** is a free, open-source WhatsApp API Gateway designed for developers who need full control over their messaging infrastructure—without vendor lock-in or hidden paywalls.-Built on a **pluggable architecture**, OpenWA lets you swap database engines (SQLite/PostgreSQL), storage backends (Local/S3), and cache layers (Memory/Redis) without changing a single line of application code.+Built on a **pluggable architecture**, OpenWA lets you select database engines (SQLite/PostgreSQL), backup/migration storage backends (Local/S3), and cache layers (disabled/Redis) through configuration rather than application-code changes. Message media itself is returned inline to API and webhook consumers; it is not automatically persisted to the storage backend.| | || ----------------------------- | ------------------------------------------------------------ |@@ -87,7 +87,7 @@ Built on a **pluggable architecture**, OpenWA lets you swap database engines (SQ| SQLite | ✅ | Zero-config embedded database || PostgreSQL | ✅ | Production-grade database || Redis Cache | ✅ | Optional performance caching |-| S3/MinIO Storage | ✅ | Scalable media storage |+| S3/MinIO Storage | ✅ | Media-directory backup/migration backend || Docker | ✅ | One-command deployment || Health Checks | ✅ | Kubernetes-ready probes || Data Migration | ✅ | Export/import between backends |diff --git a/dashboard/index.html b/dashboard/index.htmlindex da91bd428..c422af9a6 100644--- a/dashboard/index.html+++ b/dashboard/index.html@@ -2,6 +2,8 @@<html lang="en"><head><meta charset="UTF-8" />+ <!-- Replaced per response by the API when serving the bundled dashboard. Left inert in Vite dev. -->+ <meta name="openwa-csp-nonce" content="__OPENWA_CSP_NONCE__" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>OpenWA</title>diff --git a/dashboard/package.json b/dashboard/package.jsonindex 558a95c58..7f3c3edbb 100644--- a/dashboard/package.json+++ b/dashboard/package.json@@ -7,6 +7,7 @@"dev": "vite","build": "tsc -b && vite build","lint": "eslint .",+ "typecheck": "tsc --noEmit -p tsconfig.test.json","preview": "vite preview","i18n:check": "node scripts/check-i18n-parity.mjs","test:unit": "node --experimental-strip-types --test \"src/**/*.test.ts\""diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 023dada52..dea808b0e 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -141,6 +141,8 @@"apiKeyRequired": "مفتاح API مطلوب","connect": "اتصال","connecting": "جارٍ الاتصال...",+ "authenticating": "جارٍ التحقق...",+ "failed": "فشل","invalidKey": "مفتاح API غير صالح","connectionError": "تعذّر الاتصال بالخادم. يرجى المحاولة مرة أخرى.","help": "هل تحتاج مساعدة؟",@@ -743,6 +745,7 @@"sessionDataPath": "مسار بيانات الجلسة","browserArgs": "مُعطيات المتصفح","noOptions": "لا توجد خيارات إعداد لهذه الإضافة",+ "uiHandshakeError": "لم تتم تهيئة واجهة إعداد الإضافة. استخدم نموذج الإعدادات أدناه إن كان متاحًا.","save": "حفظ الإعدادات","addItem": "إضافة","tabConfig": "الإعدادات",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 1c0db2c93..50611eb57 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -141,6 +141,8 @@"apiKeyRequired": "API key is required","connect": "Connect","connecting": "Connecting...",+ "authenticating": "Authenticating...",+ "failed": "Failed","invalidKey": "Invalid API key","connectionError": "Unable to connect to server. Please try again.","help": "Need help?",@@ -739,6 +741,7 @@"sessionDataPath": "Session Data Path","browserArgs": "Browser Arguments","noOptions": "No configuration options available for this plugin",+ "uiHandshakeError": "The plugin configuration UI did not initialize. Use the schema form below if available.","save": "Save Configuration","addItem": "Add","tabConfig": "Configuration",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex fee3a22c9..1ad630788 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -141,6 +141,8 @@"apiKeyRequired": "La clave API es obligatoria","connect": "Conectar","connecting": "Conectando...",+ "authenticating": "Autenticando...",+ "failed": "Fallida","invalidKey": "Clave API no válida","connectionError": "No se puede conectar al servidor. Por favor, inténtalo de nuevo.","help": "¿Necesitas ayuda?",@@ -739,6 +741,7 @@"sessionDataPath": "Ruta de datos de sesión","browserArgs": "Argumentos del navegador","noOptions": "No hay opciones de configuración disponibles para este plugin",+ "uiHandshakeError": "La interfaz de configuración del plugin no se inició. Usa el formulario inferior si está disponible.","save": "Guardar configuración","addItem": "Añadir","tabConfig": "Configuración",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex d97fb32b0..3410d63f8 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -141,6 +141,8 @@"apiKeyRequired": "La clé API est requise","connect": "Connecter","connecting": "Connexion...",+ "authenticating": "Authentification...",+ "failed": "Échec","invalidKey": "Clé API invalide","connectionError": "Impossible de se connecter au serveur. Veuillez réessayer.","help": "Besoin d'aide ?",@@ -739,6 +741,7 @@"sessionDataPath": "Chemin des données de session","browserArgs": "Arguments du navigateur","noOptions": "Aucune option de configuration disponible pour ce plugin",+ "uiHandshakeError": "L’interface de configuration du plugin ne s’est pas initialisée. Utilisez le formulaire ci-dessous s’il est disponible.","save": "Enregistrer la configuration","addItem": "Ajouter","tabConfig": "Configuration",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex ee80e5972..6df0766b2 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -141,6 +141,8 @@"apiKeyRequired": "חובה להזין מפתח API","connect": "התחברות","connecting": "מתחבר...",+ "authenticating": "מאמת...",+ "failed": "נכשל","invalidKey": "מפתח API שגוי","connectionError": "לא ניתן להתחבר לשרת. יש לנסות שוב.","help": "צריך עזרה?",@@ -740,6 +742,7 @@"sessionDataPath": "נתיב נתוני Session","browserArgs": "ארגומנטים של הדפדפן","noOptions": "אין אפשרויות הגדרה זמינות עבור תוסף זה",+ "uiHandshakeError": "ממשק הגדרת התוסף לא אותחל. השתמשו בטופס שלמטה אם הוא זמין.","save": "שמירת תצורה","addItem": "הוספה","tabConfig": "הגדרות",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex d4b82c43e..526aaa70c 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -141,6 +141,8 @@"apiKeyRequired": "La chiave API è richiesta","connect": "Connetti","connecting": "Connessione in corso...",+ "authenticating": "Autenticazione...",+ "failed": "Non riuscita","invalidKey": "Chiave API non valida","connectionError": "Impossibile connettersi al server. Riprova.","help": "Serve aiuto?",@@ -739,6 +741,7 @@"sessionDataPath": "Percorso Dati Sessione","browserArgs": "Argomenti del Browser","noOptions": "Nessuna opzione di configurazione disponibile per questo plugin",+ "uiHandshakeError": "L’interfaccia di configurazione del plugin non si è inizializzata. Usa il modulo sottostante, se disponibile.","save": "Salva Configurazione","addItem": "Aggiungi","tabConfig": "Configurazione",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex c4f2b3204..8bbb10987 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -141,6 +141,8 @@"apiKeyRequired": "API 키가 필요합니다","connect": "연결","connecting": "연결하는 중...",+ "authenticating": "인증하는 중...",+ "failed": "실패","invalidKey": "잘못된 API 키입니다","connectionError": "서버에 연결할 수 없습니다. 다시 시도해 주세요.","help": "도움이 필요하신가요?",@@ -739,6 +741,7 @@"sessionDataPath": "세션 데이터 경로","browserArgs": "브라우저 인수","noOptions": "이 플러그인에 사용할 수 있는 구성 옵션이 없습니다",+ "uiHandshakeError": "플러그인 설정 UI가 초기화되지 않았습니다. 사용 가능한 경우 아래 스키마 양식을 이용하세요.","save": "설정 저장","addItem": "추가","tabConfig": "설정",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 7d6533b57..04e9841fe 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -141,6 +141,8 @@"apiKeyRequired": "A chave API é obrigatória","connect": "Conectar","connecting": "Conectando...",+ "authenticating": "Autenticando...",+ "failed": "Falhou","invalidKey": "Chave API inválida","connectionError": "Não foi possível conectar ao servidor. Por favor, tente novamente.","help": "Precisa de ajuda?",@@ -739,6 +741,7 @@"sessionDataPath": "Caminho dos dados da sessão","browserArgs": "Argumentos do navegador","noOptions": "Não há opções de configuração disponíveis para este plugin",+ "uiHandshakeError": "A interface de configuração do plugin não foi iniciada. Use o formulário abaixo, se disponível.","save": "Salvar configuração","addItem": "Adicionar","tabConfig": "Configuração",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 7d2a7164c..7695fcd86 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -141,6 +141,8 @@"apiKeyRequired": "API కీ అవసరం","connect": "కనెక్ట్ చేయి","connecting": "కనెక్ట్ అవుతోంది...",+ "authenticating": "ధృవీకరిస్తోంది...",+ "failed": "విఫలమైంది","invalidKey": "చెల్లని API కీ","connectionError": "సర్వర్కు కనెక్ట్ కాలేకపోయాము. దయచేసి మళ్లీ ప్రయత్నించండి.","help": "సహాయం కావాలా?",@@ -739,6 +741,7 @@"sessionDataPath": "సెషన్ డేటా పాత్","browserArgs": "బ్రౌజర్ ఆర్గుమెంట్స్","noOptions": "ఈ ప్లగిన్ కోసం ఎలాంటి కాన్ఫిగరేషన్ ఆప్షన్లు అందుబాటులో లేవు",+ "uiHandshakeError": "ప్లగిన్ కాన్ఫిగరేషన్ UI ప్రారంభం కాలేదు. అందుబాటులో ఉంటే దిగువ స్కీమా ఫారమ్ను ఉపయోగించండి.","save": "కాన్ఫిగరేషన్ను సేవ్ చేయి","addItem": "జోడించు","tabConfig": "కాన్ఫిగరేషన్",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex a5384f510..d96c60493 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -141,6 +141,8 @@"apiKeyRequired": "必须输入 API 密钥","connect": "连接","connecting": "正在连接...",+ "authenticating": "正在验证...",+ "failed": "失败","invalidKey": "API 密钥无效","connectionError": "无法连接到服务器。请重试。","help": "需要帮助?",@@ -739,6 +741,7 @@"sessionDataPath": "会话数据路径","browserArgs": "浏览器参数","noOptions": "此插件没有可用配置项",+ "uiHandshakeError": "插件配置界面未初始化。如有可用的架构表单,请使用下方表单。","save": "保存配置","addItem": "添加","tabConfig": "配置",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 779ee7586..d6b769363 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -141,6 +141,8 @@"apiKeyRequired": "必須輸入 API 金鑰","connect": "連線","connecting": "正在連線...",+ "authenticating": "正在驗證...",+ "failed": "失敗","invalidKey": "API 金鑰無效","connectionError": "無法連線到伺服器。請再試一次。","help": "需要協助?",@@ -739,6 +741,7 @@"sessionDataPath": "工作階段資料路徑","browserArgs": "瀏覽器參數","noOptions": "此外掛沒有可用設定選項",+ "uiHandshakeError": "外掛設定介面未初始化。如有可用的結構表單,請使用下方表單。","save": "儲存設定","addItem": "新增","tabConfig": "設定",diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsxindex d50f6f1a5..432edf87b 100644--- a/dashboard/src/pages/ApiKeys.tsx+++ b/dashboard/src/pages/ApiKeys.tsx@@ -23,8 +23,14 @@ import {} from 'lucide-react';import type { ApiKey } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { useApiKeysQuery, useCreateApiKeyMutation, useDeleteApiKeyMutation, useRevokeApiKeyMutation } from '../hooks/queries';+import {+ useApiKeysQuery,+ useCreateApiKeyMutation,+ useDeleteApiKeyMutation,+ useRevokeApiKeyMutation,+} from '../hooks/queries';import { PageHeader } from '../components/PageHeader';+import { useToast } from '../components/Toast';import { copyToClipboard } from '../utils/clipboard';import './ApiKeys.css';@@ -44,6 +50,7 @@ const columnHelper = createColumnHelper<ApiKey>();export function ApiKeys() {const { t } = useTranslation();+ const toast = useToast();useDocumentTitle(t('apiKeys.title'));const { data: apiKeys = [], isLoading: loading, isError: apiKeysError } = useApiKeysQuery();const createMutation = useCreateApiKeyMutation();@@ -75,6 +82,7 @@ export function ApiKeys() {setNewKey({ name: '', role: 'operator' });} catch (err) {console.error('Failed to create:', err);+ toast.error(t('apiKeys.createBtn'), err instanceof Error ? err.message : t('common.unknownError'));}};@@ -83,6 +91,7 @@ export function ApiKeys() {await revokeMutation.mutateAsync(id);} catch (err) {console.error('Failed to revoke:', err);+ toast.error(t('apiKeys.actions.revoke'), err instanceof Error ? err.message : t('common.unknownError'));}};@@ -91,6 +100,7 @@ export function ApiKeys() {await deleteMutation.mutateAsync(id);} catch (err) {console.error('Failed to delete:', err);+ toast.error(t('apiKeys.actions.delete'), err instanceof Error ? err.message : t('common.unknownError'));}};@@ -367,9 +377,7 @@ export function ApiKeys() {<div className="modal confirm-modal" onClick={e => e.stopPropagation()}><div className="modal-header"><h2>- {confirmAction.type === 'delete'- ? t('apiKeys.confirm.deleteTitle')- : t('apiKeys.confirm.revokeTitle')}+ {confirmAction.type === 'delete' ? t('apiKeys.confirm.deleteTitle') : t('apiKeys.confirm.revokeTitle')}</h2><button className="btn-icon" onClick={() => setConfirmAction(null)}><X size={20} />@@ -382,9 +390,7 @@ export function ApiKeys() {<p className="confirm-message"><Transi18nKey={- confirmAction.type === 'delete'- ? 'apiKeys.confirm.deleteMessage'- : 'apiKeys.confirm.revokeMessage'+ confirmAction.type === 'delete' ? 'apiKeys.confirm.deleteMessage' : 'apiKeys.confirm.revokeMessage'}values={{ name: confirmAction.name }}components={{ strong: <strong /> }}@@ -396,9 +402,7 @@ export function ApiKeys() {{t('common.cancel')}</button><button className="btn-danger" onClick={confirmAndExecute}>- {confirmAction.type === 'delete'- ? t('apiKeys.confirm.delete')- : t('apiKeys.confirm.revoke')}+ {confirmAction.type === 'delete' ? t('apiKeys.confirm.delete') : t('apiKeys.confirm.revoke')}</button></div></div>diff --git a/dashboard/src/pages/Dashboard.css b/dashboard/src/pages/Dashboard.cssindex d61a8d713..d82920a93 100644--- a/dashboard/src/pages/Dashboard.css+++ b/dashboard/src/pages/Dashboard.css@@ -198,7 +198,8 @@color: var(--primary);}-.dashboard .status-pill.connecting{+.dashboard .status-pill.connecting,+.dashboard .status-pill.authenticating{background: rgba(245, 158, 11, 0.15);color: var(--warning);}@@ -208,6 +209,11 @@color: var(--text-muted);}+.dashboard .status-pill.failed{+ background: rgba(239, 68, 68, 0.15);+ color: var(--error);+}+.dashboard .last-active{color: var(--text-secondary);font-size: 0.875rem;diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex f3b0c3ca2..bc2aa36bd 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -301,7 +301,15 @@ export function Infrastructure() {try {const payload = {database: { ...dbConfig },- redis: { enabled: redisEnabled, ...redisConfig },+ // `connected` is runtime-only status, not persisted configuration. Keep it out of the+ // whitelisted backend DTO so a valid dashboard save cannot be rejected as an unknown field.+ redis: {+ enabled: redisEnabled,+ builtIn: redisConfig.builtIn,+ host: redisConfig.host,+ port: redisConfig.port,+ password: redisConfig.password,+ },queue: { enabled: queueEnabled },storage: { ...storageConfig },// Only send `type` once we actually know it — either the radio seeded from the running enginediff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 8f4be8d97..c466142bc 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -260,9 +260,25 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: strconst iframeRef = useRef<HTMLIFrameElement>(null);const [html, setHtml] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);+ const [handshakeReceived, setHandshakeReceived] = useState(false);+ const [handshakeError, setHandshakeError] = useState<string | null>(null);++ const nonceConfigUiScripts = (source: string): string => {+ const nonce = document.querySelector<HTMLMetaElement>('meta[name="openwa-csp-nonce"]')?.content ?? '';+ if (!nonce || nonce === '__OPENWA_CSP_NONCE__') return source; // Vite development has no production CSP.+ const doc = new DOMParser().parseFromString(source, 'text/html');+ // Config UIs are required to be self-contained. Nonce only inline scripts; a plugin-supplied+ // external `src` must still satisfy the parent's host allow-list rather than bypassing it via nonce.+ for (const script of doc.querySelectorAll('script:not([src])')) script.setAttribute('nonce', nonce);+ return `<!doctype html>\n${doc.documentElement.outerHTML}`;+ };useEffect(() => {let cancelled = false;+ setHtml(null);+ setError(null);+ setHandshakeReceived(false);+ setHandshakeError(null);pluginsApi.getConfigUi(plugin.id).then(h => {@@ -276,6 +292,12 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: str};}, [plugin.id, t]);+ useEffect(() => {+ if (html === null || handshakeReceived) return;+ const timer = window.setTimeout(() => setHandshakeError(t('plugins.config.uiHandshakeError')), 5000);+ return () => window.clearTimeout(timer);+ }, [html, handshakeReceived, t]);+useEffect(() => {const onMessage = (e: MessageEvent) => {const frame = iframeRef.current?.contentWindow;@@ -283,6 +305,8 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: strconst msg = e.data as { type?: string; config?: Record<string, unknown> };const post = (m: unknown) => frame.postMessage(m, '*');if (msg?.type === 'config:get') {+ setHandshakeReceived(true);+ setHandshakeError(null);// Only expose schema-DECLARED fields (already secret-redacted by the API). An undeclared key// may hold a secret the host can't mask, so it never reaches the untrusted iframe; with no// schema there is nothing safe to send. The plugin must declare its fields to pre-fill them.@@ -332,14 +356,17 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: str</div>);return (- <iframe- ref={iframeRef}- className="plugin-config-ui-frame"- sandbox="allow-scripts"- srcDoc={html}- title={plugin.name}- style={{ height: plugin.configUi?.height ?? 600 }}- />+ <>+ {handshakeError && <div className="config-ui-status config-ui-error">{handshakeError}</div>}+ <iframe+ ref={iframeRef}+ className="plugin-config-ui-frame"+ sandbox="allow-scripts"+ srcDoc={nonceConfigUiScripts(html)}+ title={plugin.name}+ style={{ height: plugin.configUi?.height ?? 600 }}+ />+ </>);}@@ -1133,20 +1160,24 @@ export default function Plugins() {<PluginInstances pluginId={configPlugin.id} />) : showTabs && configTab === 'sessions' && configPlugin.sessionScoped !== false ? (<SessionsTab plugin={configPlugin} />- ) : configPlugin.configUi ? (- <PluginConfigUi plugin={configPlugin} />- ) : lz.configSchema && Object.keys(lz.configSchema.properties).length > 0 ? (- <form ref={schemaFormRef} className="config-form" onSubmit={e => e.preventDefault()}>- {Object.entries(lz.configSchema.properties).map(([key, field]) => (- <ConfigField- key={key}- field={field}- label={field.title || key}- value={schemaConfig[key]}- onChange={v => setSchemaConfig({ ...schemaConfig, [key]: v })}- />- ))}- </form>+ ) : configPlugin.configUi ||+ (lz.configSchema && Object.keys(lz.configSchema.properties).length > 0) ? (+ <>+ {configPlugin.configUi && <PluginConfigUi plugin={configPlugin} />}+ {lz.configSchema && Object.keys(lz.configSchema.properties).length > 0 && (+ <form ref={schemaFormRef} className="config-form" onSubmit={e => e.preventDefault()}>+ {Object.entries(lz.configSchema.properties).map(([key, field]) => (+ <ConfigField+ key={key}+ field={field}+ label={field.title || key}+ value={schemaConfig[key]}+ onChange={v => setSchemaConfig({ ...schemaConfig, [key]: v })}+ />+ ))}+ </form>+ )}+ </>) : (<div className="no-config"><Settings size={48} style={{ opacity: 0.3 }} />@@ -1160,9 +1191,7 @@ export default function Plugins() {{t('common.close')}</button>{/* The Sessions and Instances tabs have their own actions; the footer Save is config-tab only. */}- {showTabs && (configTab === 'sessions' || configTab === 'instances')- ? null- : configPlugin.configUi ? null : lz.configSchema &&+ {showTabs && (configTab === 'sessions' || configTab === 'instances') ? null : lz.configSchema &&Object.keys(lz.configSchema.properties).length > 0 ? (<button className="btn-primary" onClick={handleSaveSchemaConfig} disabled={savingConfig}>{savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.cssindex d64102dd0..982297560 100644--- a/dashboard/src/pages/Sessions.css+++ b/dashboard/src/pages/Sessions.css@@ -692,7 +692,8 @@}.sessions-page .status-pill.initializing,-.sessions-page .status-pill.connecting {+.sessions-page .status-pill.connecting,+.sessions-page .status-pill.authenticating {background: rgba(234, 179, 8, 0.1);color: var(--warning);}@@ -707,7 +708,8 @@color: var(--success);}-.sessions-page .status-pill.disconnected {+.sessions-page .status-pill.disconnected,+.sessions-page .status-pill.failed {background: rgba(239, 68, 68, 0.1);color: var(--error);}diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 44f04aa44..4192559fc 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -311,8 +311,8 @@ export function Sessions() {const matchesStatus =statusFilter === 'all' ||(statusFilter === 'active' && s.status === 'ready') ||- (statusFilter === 'inactive' && ['created', 'idle', 'disconnected'].includes(s.status)) ||- (statusFilter === 'connecting' && ['initializing', 'connecting', 'qr_ready'].includes(s.status));+ (statusFilter === 'inactive' && ['created', 'idle', 'disconnected', 'failed'].includes(s.status)) ||+ (statusFilter === 'connecting' && ['initializing', 'connecting', 'authenticating', 'qr_ready'].includes(s.status));return matchesSearch && matchesStatus;});diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex d57a29c47..e463dabfc 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -25,7 +25,16 @@ if (API_ORIGIN) warnIfInsecureHttpUrl(API_ORIGIN, 'VITE_API_URL');export interface Session {id: string;name: string;- status: 'created' | 'idle' | 'initializing' | 'connecting' | 'qr_ready' | 'ready' | 'disconnected' | 'failed';+ status:+ | 'created'+ | 'idle'+ | 'initializing'+ | 'connecting'+ | 'authenticating'+ | 'qr_ready'+ | 'ready'+ | 'disconnected'+ | 'failed';phone?: string;pushName?: string;lastActive?: string;@@ -306,7 +315,7 @@ export interface SaveConfigPayload {}export interface Settings {- general: { apiBaseUrl: string; sessionTimeout: number; autoReconnect: boolean; debugMode: boolean };+ general: { apiBaseUrl: string; autoReconnect: boolean; debugMode: boolean };api: { rateLimit: number; rateLimitWindow: number; enableDocs: boolean };notifications: { emailEnabled: boolean; notificationEmail: string; webhookAlerts: boolean };}diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 9fd4657c8..0d090d1ae 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -160,7 +160,7 @@ test('mergeOrAppend does not mutate the input array', () => {});test('replaceMessageById swaps the entry with matching id', () => {- const before = [msg({ id: 'temp-1', status: 'sending' }), msg({ id: 'm-2' })];+ const before = [msg({ id: 'temp-1', status: 'pending' }), msg({ id: 'm-2' })];const after = replaceMessageById(before, 'temp-1', msg({ id: 'real-1', status: 'sent' }));assert.equal(after.length, 2);assert.equal(after[0].id, 'real-1');@@ -174,7 +174,7 @@ test('replaceMessageById is a no-op when oldId is not present', () => {});test('updateMessageById applies a partial patch by id', () => {- const before = [msg({ id: 'm-1', status: 'sending' })];+ const before = [msg({ id: 'm-1', status: 'pending' })];const after = updateMessageById(before, 'm-1', { status: 'failed' });assert.equal(after[0].status, 'failed');assert.equal(after[0].body, 'hello'); // other fields unchangeddiff --git a/dashboard/tsconfig.test.json b/dashboard/tsconfig.test.jsonnew file mode 100644index 000000000..fbe97da98--- /dev/null+++ b/dashboard/tsconfig.test.json@@ -0,0 +1,8 @@+{+ "extends": "./tsconfig.app.json",+ "compilerOptions": {+ "types": ["node", "vite/client"]+ },+ "include": ["src/**/*.test.ts"],+ "exclude": []+}diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 99c68d6f3..30147f51e 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -69,13 +69,24 @@ services:- WWEBJS_WEB_VERSION_REMOTE_PATH=${WWEBJS_WEB_VERSION_REMOTE_PATH:-}# Raise whatsapp-web.js's first-boot init wait (default 30000ms) on slow boots. Empty = default.- WWEBJS_AUTH_TIMEOUT_MS=${WWEBJS_AUTH_TIMEOUT_MS:-}+ # Forward the plain-HTTP dashboard CSP override; unset preserves the application default.+ - CSP_UPGRADE_INSECURE_REQUESTS=${CSP_UPGRADE_INSECURE_REQUESTS:-}- STORAGE_TYPE=${STORAGE_TYPE:-local}- STORAGE_LOCAL_PATH=${STORAGE_LOCAL_PATH:-/app/data/media}# Install plugins into the writable, persistent data volume (the root FS is read-only). Matches# docker-compose.yml; without this it falls back to ./plugins on the read-only root and install fails.- PLUGINS_DIR=${PLUGINS_DIR:-/app/data/plugins}- WEBHOOK_TIMEOUT=${WEBHOOK_TIMEOUT:-10000}- - WEBHOOK_MAX_RETRIES=${WEBHOOK_MAX_RETRIES:-3}+ - WEBHOOK_RETRY_DELAY=${WEBHOOK_RETRY_DELAY:-5000}+ - WEBHOOK_DISPATCH_CONCURRENCY=${WEBHOOK_DISPATCH_CONCURRENCY:-16}+ - WEBHOOK_DISPATCH_MAX_QUEUED=${WEBHOOK_DISPATCH_MAX_QUEUED:-1000}+ - RATE_LIMIT_SHORT_TTL=${RATE_LIMIT_SHORT_TTL:-}+ - RATE_LIMIT_SHORT_LIMIT=${RATE_LIMIT_SHORT_LIMIT:-}+ - RATE_LIMIT_MEDIUM_TTL=${RATE_LIMIT_MEDIUM_TTL:-}+ - RATE_LIMIT_MEDIUM_LIMIT=${RATE_LIMIT_MEDIUM_LIMIT:-}+ - RATE_LIMIT_LONG_TTL=${RATE_LIMIT_LONG_TTL:-}+ - RATE_LIMIT_LONG_LIMIT=${RATE_LIMIT_LONG_LIMIT:-}+ - TRUSTED_PROXIES=${TRUSTED_PROXIES:-}- QUEUE_ENABLED=${QUEUE_ENABLED:-false}volumes:- ./data:/app/datadiff --git a/docker-compose.yml b/docker-compose.ymlindex 13d596258..aacb8eb4c 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -156,15 +156,23 @@ services:- REDIS_PORT=${REDIS_PORT:-}# Webhook- WEBHOOK_TIMEOUT=${WEBHOOK_TIMEOUT:-10000}- - WEBHOOK_MAX_RETRIES=${WEBHOOK_MAX_RETRIES:-3}- WEBHOOK_RETRY_DELAY=${WEBHOOK_RETRY_DELAY:-5000}- # Rate Limit- - RATE_LIMIT_TTL=${RATE_LIMIT_TTL:-60}- - RATE_LIMIT_MAX=${RATE_LIMIT_MAX:-100}+ - WEBHOOK_DISPATCH_CONCURRENCY=${WEBHOOK_DISPATCH_CONCURRENCY:-16}+ - WEBHOOK_DISPATCH_MAX_QUEUED=${WEBHOOK_DISPATCH_MAX_QUEUED:-1000}+ # Rate limits. Blank values are cleared before lower-priority generated config is loaded.+ - RATE_LIMIT_SHORT_TTL=${RATE_LIMIT_SHORT_TTL:-}+ - RATE_LIMIT_SHORT_LIMIT=${RATE_LIMIT_SHORT_LIMIT:-}+ - RATE_LIMIT_MEDIUM_TTL=${RATE_LIMIT_MEDIUM_TTL:-}+ - RATE_LIMIT_MEDIUM_LIMIT=${RATE_LIMIT_MEDIUM_LIMIT:-}+ - RATE_LIMIT_LONG_TTL=${RATE_LIMIT_LONG_TTL:-}+ - RATE_LIMIT_LONG_LIMIT=${RATE_LIMIT_LONG_LIMIT:-}# Plugins- PLUGINS_DIR=${PLUGINS_DIR:-/app/data/plugins}# Security- API_MASTER_KEY=${API_MASTER_KEY:-}+ - TRUSTED_PROXIES=${TRUSTED_PROXIES:-}+ # Forward the plain-HTTP dashboard CSP override; unset preserves the application default.+ - CSP_UPGRADE_INSECURE_REQUESTS=${CSP_UPGRADE_INSECURE_REQUESTS:-}# Docker socket proxy (openwa-api never touches /var/run/docker.sock directly)- DOCKER_HOST=tcp://docker-proxy:2375volumes:diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 0abedcffb..166d8d052 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -672,7 +672,7 @@ flowchart TBendsubgraph Storage["Shared Storage"]- S3[S3/MinIO<br/>Media Files]+ S3[S3/MinIO<br/>Media backup / migration]endI1 --> S3@@ -1251,6 +1251,9 @@ flowchart TBMedia storage is a **single service** (`src/common/storage/storage.service.ts`) that branchesinternally 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 methodset is `putFile` / `getFile` / `listFiles` / `createExportStream` (export) / `importFromStream`diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex a54dab23a..82fc7f2ba 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -443,7 +443,12 @@ app.use(helmet({### What Gets Logged-> **Reality check:** audit entries are persisted to the `audit_logs` table, but **only session-lifecycle actions are emitted today** (`session_created` / `session_started` / `session_stopped` / `session_force_killed` / `session_deleted` / `session_qr_generated`). The `AuditAction` enum also defines `api_key_auth_failed`, `message_sent`, and `webhook_*`, but **no code path emits them** (there is no global audit interceptor) — so failed auth, message sends, and webhook changes are **not** in the audit log yet (a tracked enhancement). Failed authentication currently surfaces only as a `logger.warn` in the application log. The diagram below is the intended coverage.+> **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+> 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.```mermaidflowchart TBdiff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 73d91c525..1c52d3288 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -474,7 +474,12 @@ CREATE INDEX "IDX_audit_logs_sessionId" ON audit_logs(session_id);CREATE INDEX "IDX_audit_logs_createdAt" ON audit_logs(created_at);```-**Audit actions** are an enum (`AuditAction`) spanning API-key lifecycle (`api_key_created`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`), session lifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`, `session_deleted`, `session_qr_generated`, `session_connected`, `session_disconnected`), messages (`message_sent`, `message_failed`), and webhooks (`webhook_created`, `webhook_deleted`, `webhook_triggered`, `webhook_failed`).+**Audit actions** are an enum (`AuditAction`) spanning API-key lifecycle (`api_key_created`,+`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`).> [!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.@@ -735,6 +740,7 @@ async cleanup(olderThanDays = 30): Promise<number> {> [!NOTE]> This section is **operational guidance**, not a built-in feature. OpenWA ships no scheduler, encryption step, or S3 uploader for backups — the diagram and script below are a recommended setup you wire up externally (cron, your host's backup tooling, etc.). For SQLite, back up the `./data/*.sqlite` files (including `./data/main.sqlite`); for PostgreSQL, use `pg_dump`. The JSON export/import endpoints in §5.1 are a portability path, not a backup mechanism.+> The authoritative full-system backup is [`scripts/backup.sh`](../scripts/backup.sh), documented in the [operational runbook](./11-operational-runbooks.md#runbook-database-backup); it also captures engine auth state, including `BAILEYS_AUTH_DIR` for Baileys.### Backup Componentsdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 6039e5c0e..f376b7efe 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -447,7 +447,7 @@ Start a session and initialize the WhatsApp connection.No request body.-**Response** `201`+**Response** `200````json{@@ -464,7 +464,7 @@ No request body.}```-Returned via `transformSession`. Status typically transitions to `initializing` / `qr_ready`. Note: Swagger declares `200`, but with no `@HttpCode` override the runtime status is **`201`** (NestJS POST default).+Returned via `transformSession`. Status typically transitions to `initializing` / `qr_ready`.**Errors:** `400` session already started / already starting · `401` · `403` · `404` not found@@ -482,7 +482,7 @@ Stop a session and disconnect WhatsApp.No request body.-**Response** `201`+**Response** `200````json{@@ -499,7 +499,7 @@ No request body.}```-Returned via `transformSession`; status typically becomes `disconnected`. Swagger declares `200`; runtime status is **`201`**.+Returned via `transformSession`; status typically becomes `disconnected`.**Errors:** `401` · `403` · `404` not found@@ -517,7 +517,7 @@ Force-kill a stuck session (SIGKILL the wedged engine, then tear it down).No request body.-**Response** `201`+**Response** `200````json{@@ -534,7 +534,7 @@ No request body.}```-Returned via `transformSession`. Swagger declares `200`; runtime status is **`201`**.+Returned via `transformSession`.**Errors:** `401` · `403` · `404` not found@@ -592,13 +592,13 @@ Mark a chat as read/seen.{ "chatId": "[email protected]" }```-**Response** `201`+**Response** `200````json{ "success": true }```-Swagger declares `200`; runtime status is **`201`**.+Returns HTTP `200`, matching the OpenAPI contract.**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found@@ -624,13 +624,13 @@ Mark a chat as unread.{ "chatId": "[email protected]" }```-**Response** `201`+**Response** `200````json{ "success": true }```-Swagger declares `200`; runtime status is **`201`**.+Returns HTTP `200`, matching the OpenAPI contract.**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found@@ -656,13 +656,13 @@ Delete a chat from the chat list (e.g. a group you have left).{ "chatId": "[email protected]" }```-**Response** `201`+**Response** `200````json{ "success": true }```-Swagger declares `200`; runtime status is **`201`**.+Returns HTTP `200`, matching the OpenAPI contract.**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found@@ -689,13 +689,13 @@ Send a typing/recording presence indicator to a chat (or clear it with `paused`){ "chatId": "[email protected]", "state": "typing" }```-**Response** `201`+**Response** `200````json{ "success": true }```-Always returns `{ "success": true }` (the service returns void; the controller hardcodes `true`). Swagger declares `200`; runtime status is **`201`**.+Always returns `{ "success": true }` (the service returns void; the controller hardcodes `true`).**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found@@ -2664,13 +2664,13 @@ Add a label to a chat.{ "labelId": "5" }```-**Response** `201`+**Response** `200````json{ "success": true }```-The handler always returns the literal `{ "success": true }`. NestJS POST default status is `201` (the Swagger doc says `200`; the runtime code is `201`).+The handler always returns the literal `{ "success": true }`.**Errors:** `400` validation failure (missing/empty/non-string `labelId`, or any unknown body field — strict whitelist), or session is not started · `401` missing/invalid API key · `403` key lacks `OPERATOR` role@@ -3362,7 +3362,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+**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#### POST /api/auth/api-keys/:id/revoke@@ -3378,7 +3378,7 @@ Revoke (deactivate) an API key without deleting it. No request body required.**Response** `200` — `ApiKeyResponseDto`-Sets `isActive` to `false` and returns the key. Default POST status `200` (no `@HttpCode` override). After revoke, the key fails validation with `401 "API key is revoked"`.+Sets `isActive` to `false` and returns the key with explicit HTTP `200`. After revoke, the key fails validation with `401 "API key is revoked"`.```json{@@ -3392,7 +3392,7 @@ Sets `isActive` to `false` and returns the key. Default POST status `200` (no `@}```-**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` not found+**Errors:** `401` missing/invalid key · `403` key role below ADMIN · `404` not found · `409` target is the last usable admin key#### DELETE /api/auth/api-keys/:id@@ -3410,7 +3410,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"`+**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#### POST /api/auth/validate@@ -3522,10 +3522,10 @@ openwa_sessions_active 2# TYPE openwa_sessions gaugeopenwa_sessions{status="ready"} 2openwa_sessions{status="disconnected"} 1-# TYPE openwa_messages_total counter+# TYPE openwa_messages_total gaugeopenwa_messages_total{direction="outgoing"} 1280openwa_messages_total{direction="incoming"} 940-# TYPE openwa_messages_failed_total counter+# TYPE openwa_messages_failed_total gaugeopenwa_messages_failed_total 4```@@ -3639,8 +3639,7 @@ Get application settings (environment-derived; `general`/`api`/`notifications` g{"general": {"apiBaseUrl": "http://localhost:2785",- "sessionTimeout": 0,- "autoReconnect": false,+ "autoReconnect": true,"debugMode": false},"api": {@@ -3656,7 +3655,7 @@ Get application settings (environment-derived; `general`/`api`/`notifications` g}```-Notes: raw return of an in-memory `Settings` object built once in the controller constructor from `ConfigService` (snapshotted at construction, not re-read per request). `general.sessionTimeout` is `floor(webhook.timeout / 60000)` minutes; `api.rateLimitWindow` is in ms; `enableDocs`/`notifications.*` are partly hardcoded (`enableDocs: true`, `emailEnabled: false`, `notificationEmail: ''`, `webhookAlerts: true`).+Notes: raw return of an in-memory `Settings` object built once in the controller constructor from `ConfigService` (snapshotted at construction, not re-read per request). `api.rateLimitWindow` is in ms. `enableDocs` reflects the `ENABLE_SWAGGER` gate (enabled by default outside production; disabled by default in production unless explicitly enabled). Only `notifications.*` is currently hardcoded (`emailEnabled: false`, `notificationEmail: ''`, `webhookAlerts: true`).**Errors:** `401` — missing/invalid `X-API-Key` · `403` — API key lacks the ADMIN role.@@ -3818,12 +3817,12 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)**Auth:** API key (ADMIN)-**Request body** — `SaveConfigDto` (plain interface, **not** class-validated; only `engine.type` and CR/LF safety are enforced)+**Request body** — `SaveConfigDto` (recursively class-validated; unknown or mistyped fields are rejected)| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- || `database` | object | No | — | DB section (see nested) |-| `database.type` | `'sqlite' \| 'postgres'` | No | — | `sqlite` drops stale postgres keys; `postgres` writes connection keys |+| `database.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.password` | string | No | secret | Empty/omitted keeps the existing stored secret |@@ -3832,10 +3831,9 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)| `database.sslRejectUnauthorized` | boolean | No | — | Only written when `sslEnabled` is true; default true || `redis.enabled` / `.builtIn` | boolean | No | — | `builtIn`+enabled forces `redis` container + profile || `redis.host` / `.port` | string | No | `port` is a string | Defaults `localhost`/`6379` |-| `redis.username` | string | No | — | Redis ACL username || `redis.password` | string | No | secret | Empty keeps existing || `queue.enabled` | boolean | No | — | Writes `QUEUE_ENABLED` |-| `storage.type` | `'local' \| 's3'` | No | — | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH` |+| `storage.type` | `'local' \| 's3'` | If `storage` is present | enum | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH` || `storage.builtIn` | boolean | No | — | `true`+s3 uses bundled MinIO defaults + pushes `minio` profile || `storage.localPath` | string | No | — | Default `./data/media` || `storage.s3Bucket` / `.s3Region` / `.s3Endpoint` | string | No | — | External S3 |@@ -3861,9 +3859,10 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file){ "message": "Configuration saved. Server restart required.", "saved": true, "envPath": "data/.env.generated", "profiles": ["postgres", "redis"] }```-This route **always returns HTTP 200**, even on failure: write/IO errors are caught and returned as `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. The only true `400` cases are an unknown `engine.type` or any value containing `\r`/`\n`. `profiles` lists newly-required Docker profiles.+Write/IO errors are caught and returned as HTTP `200` with `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. DTO validation, an unknown engine type, and CR/LF injection are real HTTP `400` responses. `profiles` lists newly-required Docker profiles.-**Errors:** `400` unknown `engine.type` / CR-LF in a value · `401` · `403`+**Errors:** `400` unknown/mistyped body field, missing nested `database.type`/`storage.type`, unknown+`engine.type`, or CR-LF in a value · `401` · `403`---@@ -3873,7 +3872,7 @@ Request a graceful server restart, optionally orchestrating Docker profiles (add**Auth:** API key (ADMIN)-**Request body** — optional inline type (plain interface, not class-validated)+**Request body** — optional `RestartDto` (class-validated; unknown fields and non-string array members reject)| Field | Type | Required | Default | Description || --- | --- | --- | --- | --- |@@ -4015,7 +4014,7 @@ Import storage files from a `tar.gz` located inside the `data/` directory.**Auth:** API key (ADMIN)-**Request body** — inline `{ filePath: string }` (plain interface, not class-validated; path-safety enforced manually)+**Request body** — `ImportStorageDto` (class-validated; path-safety is additionally enforced manually)| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- |@@ -4121,7 +4120,8 @@ Get a single plugin by id.#### GET /api/plugins/:id/config-ui-Serve a plugin's sandboxed config-UI entry HTML (for an iframe `srcdoc`).+Serve a plugin's sandboxed config-UI entry HTML (for an opaque-origin iframe `srcdoc`; the dashboard+applies its document-specific CSP nonce to inline scripts and keeps any declared schema form available as fallback).**Auth:** API key (ADMIN)diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 1ff873768..9bda465af 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -1096,9 +1096,7 @@ Always returns `501` — settings are read-only at runtime. ADMIN key required (```bashcurl -X PUT "$BASE/api/settings" \- -H "X-API-Key: $API_KEY" \- -H "Content-Type: application/json" \- -d '{ "general": { "sessionTimeout": 10 } }'+ -H "X-API-Key: $API_KEY"```### 07.13 Administration (Infrastructure, Plugins, MCP)@@ -1260,7 +1258,8 @@ curl "$BASE/api/plugins/chat-flow" \#### GET /api/plugins/:id/config-ui-Fetch a plugin's sandboxed config-UI HTML (for an iframe srcdoc).+Fetch a plugin's sandboxed config-UI HTML. The dashboard renders it in an opaque-origin iframe,+uses a `postMessage` bridge for config, and retains any schema form as a fallback.```bashcurl "$BASE/api/plugins/chat-flow/config-ui" \diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex c8620d2a3..65c563dc2 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -8,10 +8,10 @@ test layout and the expected testing workflow for contributors.| Area | Current state || ------------------ | ----------------------------------------------------------------------------------------------------------- |-| Backend unit tests | 158 source-controlled `*.spec.ts` files under `src/` |-| E2E smoke tests | 8 source-controlled `*.e2e-spec.ts` files under `test/` |-| Dashboard checks | ESLint, i18n parity, React/Vite build, and 10 source-controlled Node test files |-| SDK checks | Path-filtered JavaScript, Python, PHP, and Java SDK CI with 28 source-controlled SDK test files |+| Backend unit tests | Source-controlled `*.spec.ts` files under `src/`; use the inventory commands below |+| E2E smoke tests | Source-controlled `*.e2e-spec.ts` files under `test/`; use the inventory commands below |+| Dashboard checks | ESLint, test type-check, i18n parity, React/Vite build, and source-controlled Node tests |+| SDK checks | Path-filtered JavaScript, Python, PHP, Java, and Go SDK CI || PostgreSQL checks | Dedicated CI job builds migrations and runs `npm run test:pg-smoke` against PostgreSQL 16 || Coverage gate | Jest global thresholds plus stricter thresholds for security, auth, engine-adapter, and integration modules |@@ -22,8 +22,8 @@ the test inventory, and use the test commands in the next section for pass/failrg --files -g '*.spec.ts' src | wc -lrg --files -g '*.e2e-spec.ts' test | wc -lrg --files -g '*.test.ts' dashboard/src | wc -l-rg --files sdk/javascript/test sdk/python/tests sdk/php/tests sdk/java/src/test \- | rg '(\.test\.ts$|test_.*\.py$|Test\.php$|Test\.java$)' \+rg --files sdk/javascript/test sdk/python/tests sdk/php/tests sdk/java/src/test sdk/go \+ | rg '(\.test\.ts$|test_.*\.py$|Test\.php$|Test\.java$|_test\.go$)' \| wc -lnpm test -- --runInBandnpm run test:e2e -- --runInBand@@ -40,8 +40,11 @@ npm --prefix dashboard run test:unit| `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 lint` | Run backend ESLint with type-aware rules |+| `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 || `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 |@@ -49,6 +52,7 @@ npm --prefix dashboard run test:unit| `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 |## 9.3 Backend Unit Tests@@ -161,12 +165,12 @@ Main CI is defined in `.github/workflows/ci.yml`.| Job | Checks || --------------- | ----------------------------------------------------------------------------------------------- |-| `lint` | `npm audit --audit-level=critical`, backend ESLint, formatting check, version consistency check |+| `lint` | security audit, backend ESLint, full-program TypeScript check, formatting, version consistency, OpenAPI snapshot || `test` | backend coverage run, e2e smoke tests, Codecov upload |-| `test-postgres` | real PostgreSQL 16 service, backend build, `npm run test:pg-smoke` |-| `dashboard` | dashboard install, lint, unit tests, i18n parity, build |+| `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 || `build` | backend build after lint/test/dashboard jobs pass |-| `docker` | multi-arch Docker build and push on branch pushes |+| `docker` | multi-arch Docker build on pushes and pull requests; publish only where workflow permissions allow |SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus servercontract surfaces that SDKs mirror (`src/**/dto/**` and the engine interface). It runs:@@ -175,6 +179,7 @@ contract surfaces that SDKs mirror (`src/**/dto/**` and the engine interface). I- Python SDK tests with `pytest`.- PHP SDK tests with PHPUnit.- Java SDK tests with Maven.+- Go SDK formatting, `go vet`, and race-enabled tests at the declared Go floor.Release tags run `.github/workflows/release.yml`. The release gate verifies the tag matches`package.json`, checks documented version consistency, runs backend tests with coverage, builds the@@ -249,7 +254,8 @@ 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.-- No default CI job exercises real PostgreSQL, Redis, S3/MinIO, or Docker socket proxy integration.+- 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.- 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`.diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex 2f6b749ca..de197dfed 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -517,9 +517,11 @@ API_KEY_PEPPER=optional-key-hashing-pepper# ===========================================# WEBHOOK# ===========================================-WEBHOOK_TIMEOUT=30000-WEBHOOK_RETRY_COUNT=3+WEBHOOK_TIMEOUT=10000WEBHOOK_RETRY_DELAY=5000+WEBHOOK_DISPATCH_CONCURRENCY=16+WEBHOOK_DISPATCH_MAX_QUEUED=1000+# Retry attempts are configured per webhook with the retryCount API field (default 3, range 0-5).# ===========================================# RATE LIMITING@@ -548,9 +550,10 @@ export default () => ({dataPath: process.env.SESSION_DATA_PATH || './.wwebjs_auth',},webhook: {- timeout: parseInt(process.env.WEBHOOK_TIMEOUT, 10) || 30000,- retryCount: parseInt(process.env.WEBHOOK_RETRY_COUNT, 10) || 3,- retryDelay: parseInt(process.env.WEBHOOK_RETRY_DELAY, 10) || 5000,+ timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),+ retryDelay: parseInt(process.env.WEBHOOK_RETRY_DELAY || '5000', 10),+ 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,@@ -748,15 +751,15 @@ groups:summary: "WhatsApp session disconnected"description: "{{ $value }} session(s) in disconnected state"- # Failed messages climbing- - alert: FailedMessagesRising- expr: rate(openwa_messages_failed_total[5m]) > 0+ # Failed messages currently stored+ - alert: FailedMessagesPresent+ expr: openwa_messages_failed_total > 0for: 5mlabels:severity: warningannotations:summary: "Messages are failing"- description: "openwa_messages_failed_total is increasing over the last 5 minutes"+ description: "{{ $value }} message(s) are currently in FAILED state"# Process memory growth (app-exported RSS; ~2GB example threshold)- alert: HighProcessMemory@@ -921,8 +924,8 @@ export class MetricsService {| `openwa_sessions_total` | gauge | — | Configured sessions || `openwa_sessions_active` | gauge | — | READY (active) sessions || `openwa_sessions` | gauge | `status` | Session count per status |-| `openwa_messages_total` | counter | `direction` (`incoming`/`outgoing`) | Messages by direction |-| `openwa_messages_failed_total` | counter | — | Messages in FAILED state |+| `openwa_messages_total` | gauge | `direction` (`incoming`/`outgoing`) | Current stored messages by direction |+| `openwa_messages_failed_total` | gauge | — | Current messages in FAILED state |### Grafana Dashboard Definition@@ -941,11 +944,11 @@ export class MetricsService {]},{- "title": "Messages Sent (24h)",+ "title": "Stored Outgoing Messages","type": "stat","gridPos": { "x": 6, "y": 0, "w": 6, "h": 4 },"targets": [- { "expr": "increase(openwa_messages_total{direction=\"outgoing\"}[24h])" }+ { "expr": "openwa_messages_total{direction=\"outgoing\"}" }]},{@@ -965,11 +968,11 @@ export class MetricsService {]},{- "title": "Message Rate by Direction",+ "title": "Stored Messages by Direction","type": "timeseries","gridPos": { "x": 12, "y": 4, "w": 12, "h": 8 },"targets": [- { "expr": "rate(openwa_messages_total[5m])", "legendFormat": "{{direction}}" }+ { "expr": "openwa_messages_total", "legendFormat": "{{direction}}" }]},{@@ -1063,9 +1066,9 @@ These are the metrics OpenWA actually exports at `GET /api/metrics`:| **Sessions** | `openwa_sessions_total` | Configured sessions | Near your expected session count || **Sessions** | `openwa_sessions_active` | READY (active) sessions | Drops below expected || **Sessions** | `openwa_sessions{status="..."}` | Per-status counts (e.g. `disconnected`, `failed`) | `disconnected`/`failed` > 0 |-| **Messages** | `openwa_messages_total{direction="outgoing"}` | Outgoing messages | Sudden drop |-| **Messages** | `openwa_messages_total{direction="incoming"}` | Incoming messages | Sudden drop |-| **Messages** | `openwa_messages_failed_total` | Messages in FAILED state | Rising rate |+| **Messages** | `openwa_messages_total{direction="outgoing"}` | Current stored outgoing messages | Unexpected change |+| **Messages** | `openwa_messages_total{direction="incoming"}` | Current stored incoming messages | Unexpected change |+| **Messages** | `openwa_messages_failed_total` | Current messages in FAILED state | Above acceptable threshold || **System** | `openwa_process_resident_memory_bytes` | RSS | Growth / near limit || **System** | `openwa_process_heap_used_bytes` | V8 heap used | Growth || **System** | `openwa_process_uptime_seconds` | Process uptime | Frequent restarts (resets) |@@ -1098,59 +1101,17 @@ flowchart TB### Backup Script-```bash-#!/bin/bash-# scripts/backup.sh--set -e--DATE=$(date +%Y%m%d_%H%M%S)-BACKUP_DIR="/backups"-S3_BUCKET="s3://openwa-backups"--# Database backup-echo "Backing up database..."-pg_dump -Fc $DATABASE_URL > $BACKUP_DIR/db_$DATE.dump-gzip $BACKUP_DIR/db_$DATE.dump--# Session data backup-echo "Backing up session data..."-tar -czf $BACKUP_DIR/sessions_$DATE.tar.gz /app/.wwebjs_auth--# Upload to S3-echo "Uploading to S3..."-aws s3 cp $BACKUP_DIR/db_$DATE.dump.gz $S3_BUCKET/database/-aws s3 cp $BACKUP_DIR/sessions_$DATE.tar.gz $S3_BUCKET/sessions/--# Cleanup local files older than 7 days-find $BACKUP_DIR -mtime +7 -delete--echo "Backup completed: $DATE"-```+Use the shipped [`scripts/backup.sh`](../scripts/backup.sh); do not maintain a second inline copy.+It captures the always-SQLite `main.sqlite`, the configured data database, whatsapp-web.js session+state (`SESSION_DATA_PATH`), Baileys auth state (`BAILEYS_AUTH_DIR`, default `./data/baileys`), local+media, installed plugin packages, plugin registry/state, and generated secret/config files. See the+authoritative [backup runbook](./11-operational-runbooks.md#runbook-database-backup).### Recovery Procedure-```bash-#!/bin/bash-# scripts/restore.sh--set -e--BACKUP_DATE=$1--# Download from S3-aws s3 cp s3://openwa-backups/database/db_$BACKUP_DATE.dump.gz /tmp/-aws s3 cp s3://openwa-backups/sessions/sessions_$BACKUP_DATE.tar.gz /tmp/--# Restore database-gunzip /tmp/db_$BACKUP_DATE.dump.gz-pg_restore -d $DATABASE_URL /tmp/db_$BACKUP_DATE.dump--# Restore sessions-tar -xzf /tmp/sessions_$BACKUP_DATE.tar.gz -C /--echo "Restore completed"-```+Use the matching [`scripts/restore.sh`](../scripts/restore.sh) and follow the+[restore runbook](./11-operational-runbooks.md#runbook-restore-from-backup). Stop the application+before restoring; PostgreSQL dumps still require the explicit `psql` step described there.## 10.8 Scaling Guidelinesdiff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.mdindex 20d953572..b5e830fcd 100644--- a/docs/11-operational-runbooks.md+++ b/docs/11-operational-runbooks.md@@ -225,6 +225,10 @@ curl -H "X-API-Key: $API_KEY" \**Trigger:** Webhook success rate < 95%, alert from monitoring+For sustained/high-volume webhook traffic, enable Redis-backed dispatch with `QUEUE_ENABLED=true`.+The inline fallback deliberately has bounded concurrency and a bounded waiter queue; overflow is recorded+as a delivery failure rather than retaining payloads without limit.+**Impact:** External systems not receiving events**Prerequisites:**@@ -483,17 +487,20 @@ curl -H "X-API-Key: $API_KEY" http://localhost:2785/api/health**Steps:**-Use the repo's `scripts/backup.sh`. It captures **everything** required to restore a-working install — critically including `main.sqlite`, the auth (API-key) + audit DB,-which an earlier version of this runbook omitted (a "successful" backup that could not-restore authentication):+Use the repo's `scripts/backup.sh`. Its explicit scope covers the load-bearing state below — critically+including `main.sqlite`, the auth (API-key) + audit DB, which an earlier version of this runbook omitted.+User-managed files outside that list (for example the project-level `.env`) must be protected separately:```bash# scripts/backup.sh captures:# - main.sqlite — auth (API keys) + audit log (ALWAYS SQLite)# - openwa.sqlite — user data (or a pg_dump when DATABASE_TYPE=postgres)-# - sessions/ — WhatsApp LocalAuth session data+# - sessions/ — whatsapp-web.js state (SESSION_DATA_PATH)+# - baileys/ — Baileys credentials (BAILEYS_AUTH_DIR)# - media/ — local media (skipped automatically when STORAGE_TYPE=s3)+# - plugin-packages/ — installed plugin code from PLUGINS_DIR+# - plugin-state/ — registry + ctx.storage state under OPENWA_DATA_DIR+# - .env.generated / .api-key — generated configuration and bootstrap secret# Run from the repo root (operates on the data dir, default ./data):./scripts/backup.sh@@ -507,15 +514,21 @@ OPENWA_DATA_DIR=/srv/openwa/data \> The data directory is a Docker **named volume** (`openwa-data`) in the production> compose. Run the script where that volume is mounted — e.g. point `OPENWA_DATA_DIR`-> at the volume's mountpoint, or run it inside a container with `/app/data` mounted.+> at the volume's mountpoint, or run it inside a container with `/app/data` mounted. When operating+> directly on the host mount, also set any path that does not use its default below `OPENWA_DATA_DIR`+> (notably compose's colocated `PLUGINS_DIR`) to the corresponding host-visible path.**Verification:**```bash-# The archive MUST contain main.sqlite (auth/audit), the data store, and sessions/+# The archive MUST contain main.sqlite, the configured data store, and the auth directory for the+# selected engine (sessions/ for whatsapp-web.js or baileys/ for Baileys).tar -tzf ./backups/openwa-backup-*.tar.gz```+> Backup archives contain API keys, provider credentials, WhatsApp auth state, and plugin secrets.+> Encrypt them at rest, restrict access, and never publish or attach them to support tickets.+---### Runbook: Restore from Backup@@ -531,9 +544,10 @@ tar -tzf ./backups/openwa-backup-*.tar.gz**Steps:**-Use the repo's `scripts/restore.sh`. It restores **both** databases (`main.sqlite`-auth/audit + the data store) and the WhatsApp `sessions/`, and snapshots the current-data dir first so a bad restore can be undone:+Use the repo's `scripts/restore.sh`. It restores `main.sqlite` (auth/audit) and a SQLite data store;+for PostgreSQL it stages `database.sql` for the explicit import below. It also restores+whatsapp-web.js/Baileys auth state, local media, plugins, and generated secret/config files. It snapshots+the current data dir first so a bad restore can be undone:```bash# 1. Stop the app (so files are quiescent)@@ -551,9 +565,11 @@ docker compose up -dcurl -s -X POST -H "X-API-Key: <an-existing-key>" http://localhost:2785/api/auth/validate```-> Restoring `main.sqlite` is the whole point: it carries the API keys and audit log.-> If a restore leaves you unable to authenticate, the backup that produced the archive-> did not capture `main.sqlite` — re-run `scripts/backup.sh` (which always does).+> `main.sqlite` carries the hashed API keys and audit log; `.api-key`, when retained by the original+> installation, carries the plaintext bootstrap admin key. After restore, verify that both expected files+> were present in the archive and that the client is using the original plaintext key. Re-running backup+> after the source state or key has already been lost cannot recover it; use an older valid archive or the+> documented credential-recovery procedure instead.**Verification:**diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 0318d59c8..8924c0f7e 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -969,34 +969,14 @@ Remember OpenWA is **single-port**: the Dashboard, REST API, and Socket.IO all s**Q: How to backup sessions automatically?**```bash-#!/bin/bash-# backup-cron.sh - Add to crontab: 0 */6 * * * /path/to/backup-cron.sh--BACKUP_DIR="/backups/openwa"-DATE=$(date +%Y%m%d-%H%M%S)--# Create backup directory-mkdir -p "$BACKUP_DIR/$DATE"--# Backup database-if [ "$DATABASE_ADAPTER" = "postgresql" ]; then- pg_dump $DATABASE_URL > "$BACKUP_DIR/$DATE/database.sql"-else- cp ./data/openwa.db "$BACKUP_DIR/$DATE/"-fi--# Backup auth sessions-# whatsapp-web.js engine:-cp -r ./data/.wwebjs_auth "$BACKUP_DIR/$DATE/"-# Baileys engine (ENGINE_TYPE=baileys): back up BAILEYS_AUTH_DIR (default: ./data/baileys)-# cp -r ./data/baileys "$BACKUP_DIR/$DATE/"--# Keep only last 7 days-find "$BACKUP_DIR" -type d -mtime +7 -exec rm -rf {} \;--echo "Backup completed: $BACKUP_DIR/$DATE"+# Add to crontab, for example: 0 */6 * * * cd /path/to/openwa && ./scripts/backup.sh+BACKUP_DIR=/backups/openwa ./scripts/backup.sh```+The shipped script also covers `main.sqlite`, the selected data store, whatsapp-web.js state,+`BAILEYS_AUTH_DIR` (default `./data/baileys`), media, plugin packages/state, and generated secrets. Apply+retention/encryption to completed archives externally; see the [backup and restore runbooks](./11-operational-runbooks.md#runbook-database-backup).+### Webhook Questions**Q: What events can I subscribe to?**diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex fb6fea84f..dd33822e4 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -163,8 +163,8 @@ a host version. The config schema is the top-level `configSchema` (note: not nes| `sessions` | — | Session ids this plugin may act on, or `['*']`. Absent = `['*']`. Static — editing config can't widen it || `sessionScoped` | — | Default `true`. A scoped plugin only sees events for the sessions it's activated for; `false` = always runs || `net.allow` | — | Outbound-HTTP host allowlist for `ctx.net.fetch` (`host`, `host:port`, or `'*'`). Absent = deny all |-| `configSchema` | — | Declarative config schema the dashboard renders into a form |-| `configUi` | — | Optional self-contained HTML config editor served into a sandboxed iframe (preferred over `configSchema` when present) |+| `configSchema` | — | Declarative config schema the dashboard renders as an always-available form fallback |+| `configUi` | — | Optional self-contained HTML config editor served into a sandboxed iframe alongside `configSchema` when both exist || `hooks` | — | Hook events this plugin listens to (informational) || `provides` / `requires` | — | Features this plugin provides / depends on || `i18n` | — | Localized dashboard text per locale (dashboard-only) |@@ -531,8 +531,9 @@ URL / catalog), not an npm/github source descriptor.> `GET /plugins/:id/config-ui` returns untrusted HTML served with `Content-Security-Policy: sandbox`> and `X-Content-Type-Options: nosniff`. The dashboard fetches it **with** the API key and injects the-> body as an iframe `srcdoc` (opaque origin); the editor exchanges config over a `postMessage` bridge,-> so the API key never reaches the iframe.+> body as an iframe `srcdoc` (opaque origin), applying the current document's CSP nonce to inline scripts;+> the editor exchanges config over a `postMessage` bridge, so the API key never reaches the iframe. If+> the bridge does not initialize, the dashboard shows an error and keeps a declared `configSchema` form usable.## 19.9 Plugin Securitydiff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex 09bce60a7..7a12f6613 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -143,14 +143,20 @@ Four tables live on the data connection, each created by a hand-authored dual-diguard still applies, and the payload is intentionally not bound to a DTO so strict validation cannotreject 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 collapses- at-least-once delivery to exactly-once processing.-- **Tenancy scoping.** Every ingress artifact — secret, dedup store, ordering lane, dead-letter row — is+ `(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.+- **Tenancy scoping.** Every durable ingress artifact — secret, dedup store, and dead-letter row — ispartitioned by instance, and downstream capability calls carry the instance's resolved session scope, soa cross-tenant send is blocked host-side.-- **Fail-closed by construction.** A missing, wrong, or stale signature, or an empty raw body, all reject.- The only unconditional-accept path is an explicit `scheme: "none"` an adapter must declare in its- manifest.+- **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.+- **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.- **Egress.** The only outbound path remains the existing SSRF-guarded `ctx.net.fetch`, scoped to themanifest's allowed hosts.- **Re-entrancy.** A reply issued *inside* an ingress handler seeds the in-flight hook set, so an adapter's@@ -158,13 +164,13 @@ Four tables live on the data connection, each created by a hand-authored dual-di## 25.7 Scale and durability-Persist-before-acknowledge; at-least-once collapsed to exactly-once via deduplication and the queue job-id; best-effort per-conversation ordering via an advisory lock (P1) — strict FIFO is not preserved across a queue retry or a redrive (inbound arrives over unordered HTTP and is a reconcile trigger, not an ordered source of truth); per-instance fairness via a token bucket-that sheds a noisy tenant at the edge (P1); a dead-letter record with a redrive endpoint (P1). All shared-state lives in Redis and PostgreSQL rather than in per-plugin files or the in-memory hook bus, so the-design can scale to multiple nodes later without re-plumbing (the initial implementation runs on a single-node). When the queue is disabled, ingress degrades to inline dispatch after persisting, mirroring the-existing outbound webhook fallback.+Persist-before-acknowledge; best-effort de-duplication keyed by a stable provider delivery id and queue+job id; per-instance fairness via a token bucket; and a dead-letter record with bounded redrive. On the+queued worker path, an **in-process** per-conversation lock prevents concurrent starts for the same lane;+strict FIFO is not preserved across retry/redrive, and the lock is single-node state rather than Redis or+PostgreSQL state. When the queue is disabled, ingress dispatches inline after persisting and does not+serialize concurrent same-conversation deliveries. Providers already deliver over unordered,+at-least-once HTTP, so plugin handlers must be idempotent and treat ingress as a reconciliation trigger.## 25.8 The Integration SDK (v1)diff --git a/docs/engine-capability-matrix.md b/docs/engine-capability-matrix.mdindex 6ca007569..19f416b7f 100644--- a/docs/engine-capability-matrix.md+++ b/docs/engine-capability-matrix.md@@ -12,7 +12,7 @@ Each row also cites an **evidence** string (the exact library file:symbol inspec## How the matrix stays honest-`src/engine/engine-parity.spec.ts` is a **drift gate**: it reads every adapter method body via `Class.prototype.method.toString()`, classifies it as supported/not-available by whether it throws `EngineNotSupportedError` / `ChannelMediaNotSupportedError`, and fails the build if the committed matrix drifts. No engine is instantiated and no Chromium/socket is opened — it is a fast, hermetic structural check. A parity change cannot land without deliberately updating this matrix and this doc.+`src/engine/engine-parity.spec.ts` is a **structural gate**: it verifies the matrix keys correspond exactly to `IWhatsAppEngine` methods and checks the adapter throw-invariants it can observe through `Class.prototype.method.toString()`. No engine is instantiated and no Chromium/socket is opened. The gate does not read this document and cannot detect a non-throwing phantom stub becoming real (or regressing), so status/evidence changes still require source review and a deliberate documentation update.The `rootCause`/`evidence` fields are hand-curated from source traces of the installed libraries (`node_modules/@whiskeysockets/baileys`, `node_modules/whatsapp-web.js`); they are not regenerated by the spec and are updated by hand as adapters are wired or libraries change.diff --git a/openapi.json b/openapi.jsonindex b9d512928..af927c857 100644--- a/openapi.json+++ b/openapi.json@@ -12,6 +12,7 @@"schema": {"enum": ["api_key_created",+ "api_key_updated","api_key_used","api_key_revoked","api_key_deleted",@@ -212,6 +213,9 @@}}}+ },+ "409": {+ "description": "The change would remove the last usable admin key."}},"summary": "Update API key (admin only)",@@ -234,6 +238,9 @@"responses": {"204": {"description": "API key deleted"+ },+ "409": {+ "description": "The key is the last usable admin key."}},"summary": "Delete API key (admin only)",@@ -265,6 +272,9 @@}}}+ },+ "409": {+ "description": "The key is the last usable admin key."}},"summary": "Revoke API key (admin only)",@@ -2481,7 +2491,7 @@"content": {"application/json": {"schema": {- "type": "string"+ "$ref": "#/components/schemas/SaveConfigDto"}}}@@ -2501,6 +2511,16 @@"post": {"operationId": "InfraController_requestRestart","parameters": [],+ "requestBody": {+ "required": false,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RestartDto"+ }+ }+ }+ },"responses": {"200": {"description": "Server will restart with new profiles"@@ -3892,6 +3912,9 @@"responses": {"201": {"description": "Image status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."+ },+ "413": {+ "description": "Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES."}},"summary": "Post an image status",@@ -3926,6 +3949,9 @@"responses": {"201": {"description": "Video status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."+ },+ "413": {+ "description": "Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES."}},"summary": "Post a video status",@@ -4962,7 +4988,7 @@],"responses": {"201": {- "description": "Dead-lettered ingress deliveries for the instance re-dispatched. Returns the count redriven."+ "description": "One bounded batch of dead-lettered ingress deliveries re-dispatched, with remaining depth."}},"tags": [@@ -6679,6 +6705,169 @@}}},+ "DatabaseConfigDto": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "sqlite",+ "postgres"+ ]+ },+ "builtIn": {+ "type": "boolean"+ },+ "host": {+ "type": "string"+ },+ "port": {+ "type": "string"+ },+ "username": {+ "type": "string"+ },+ "password": {+ "type": "string"+ },+ "database": {+ "type": "string"+ },+ "schema": {+ "type": "string"+ },+ "poolSize": {+ "type": "number"+ },+ "sslEnabled": {+ "type": "boolean"+ },+ "sslRejectUnauthorized": {+ "type": "boolean"+ }+ },+ "required": [+ "type"+ ]+ },+ "RedisConfigDto": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ },+ "builtIn": {+ "type": "boolean"+ },+ "host": {+ "type": "string"+ },+ "port": {+ "type": "string"+ },+ "password": {+ "type": "string"+ }+ }+ },+ "QueueConfigDto": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ }+ }+ },+ "StorageConfigDto": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "local",+ "s3"+ ]+ },+ "builtIn": {+ "type": "boolean"+ },+ "localPath": {+ "type": "string"+ },+ "s3Bucket": {+ "type": "string"+ },+ "s3Region": {+ "type": "string"+ },+ "s3AccessKey": {+ "type": "string"+ },+ "s3SecretKey": {+ "type": "string"+ },+ "s3Endpoint": {+ "type": "string"+ }+ },+ "required": [+ "type"+ ]+ },+ "EngineConfigDto": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string"+ },+ "headless": {+ "type": "boolean"+ },+ "sessionDataPath": {+ "type": "string"+ },+ "browserArgs": {+ "type": "string"+ }+ }+ },+ "SaveConfigDto": {+ "type": "object",+ "properties": {+ "database": {+ "$ref": "#/components/schemas/DatabaseConfigDto"+ },+ "redis": {+ "$ref": "#/components/schemas/RedisConfigDto"+ },+ "queue": {+ "$ref": "#/components/schemas/QueueConfigDto"+ },+ "storage": {+ "$ref": "#/components/schemas/StorageConfigDto"+ },+ "engine": {+ "$ref": "#/components/schemas/EngineConfigDto"+ }+ }+ },+ "RestartDto": {+ "type": "object",+ "properties": {+ "profiles": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "profilesToRemove": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },"CreateGroupDto": {"type": "object","properties": {@@ -6791,7 +6980,7 @@"base64": {"type": "string","description": "Base64-encoded media. Requires mimetype.",- "example": "data:image/jpeg;base64,..."+ "example": "/9j/4AAQSkZJRg..."},"mimetype": {"type": "string",diff --git a/package-lock.json b/package-lock.jsonindex 842043b29..a1d087d07 100644--- a/package-lock.json+++ b/package-lock.json@@ -80,7 +80,7 @@"typescript-eslint": "^8.63.0"},"engines": {- "node": ">=22"+ "node": ">=22.12"}},"node_modules/@angular-devkit/core": {diff --git a/package.json b/package.jsonindex 054c119cb..a5cc4bac1 100644--- a/package.json+++ b/package.json@@ -6,7 +6,7 @@"private": true,"license": "MIT","engines": {- "node": ">=22"+ "node": ">=22.12"},"scarfSettings": {"enabled": false@@ -15,6 +15,7 @@"build": "nest build","build:all": "nest build && npm run dashboard:build","format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",+ "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"","start": "nest start","start:dev": "nest start --watch","start:debug": "nest start --debug --watch",@@ -25,7 +26,7 @@"dashboard:ci": "cd dashboard && npm ci","dashboard:dev": "cd dashboard && npm run dev","dashboard:build": "cd dashboard && npm run build",- "postinstall": "node -e \"const fs=require('fs'),cp=require('child_process'); if (fs.existsSync('dashboard')) cp.spawnSync('npm run dashboard:install', { stdio: 'inherit', shell: true }); if (fs.existsSync('scripts/patch-wwebjs-201832.js')) cp.spawnSync(process.execPath, ['scripts/patch-wwebjs-201832.js', '--best-effort'], { stdio: 'inherit' });\"",+ "postinstall": "node -e \"const fs=require('fs'),cp=require('child_process'); if (fs.existsSync('dashboard')) cp.spawnSync('npm run dashboard:ci', { stdio: 'inherit', shell: true }); if (fs.existsSync('scripts/patch-wwebjs-201832.js')) cp.spawnSync(process.execPath, ['scripts/patch-wwebjs-201832.js', '--best-effort'], { stdio: 'inherit' });\"","check:versions": "node scripts/check-doc-versions.mjs","openapi:export": "ts-node scripts/export-openapi.ts openapi.json","openapi:check": "ts-node scripts/export-openapi.ts /tmp/openapi.generated.json && diff -u openapi.json /tmp/openapi.generated.json",diff --git a/scripts/backup.sh b/scripts/backup.shindex 79d6fa9bf..7fc9f20fd 100755--- a/scripts/backup.sh+++ b/scripts/backup.sh@@ -2,11 +2,15 @@## OpenWA backup.#-# Captures EVERYTHING needed to restore a working install:+# Captures the load-bearing state needed to restore a working install:# - main.sqlite — auth (API keys) + audit log, ALWAYS SQLite (see app.module.ts)# - data store — openwa.sqlite (SQLite) OR a pg_dump (when DATABASE_TYPE=postgres)-# - sessions/ — WhatsApp LocalAuth session data+# - sessions/ — whatsapp-web.js LocalAuth session data+# - baileys/ — Baileys engine authentication state# - media/ — locally-stored media (skipped automatically when using S3)+# - plugin-packages/ — installed plugin packages from PLUGINS_DIR+# - plugin-state/ — registry and persisted ctx.storage state under OPENWA_DATA_DIR+# - .env.generated and .api-key — dashboard config and plaintext bootstrap admin key## The previous runbook backed up the wrong file (openwa.db) and omitted main.sqlite,# so a "successful" backup silently lost every API key and all audit history.@@ -17,9 +21,14 @@# OPENWA_DATA_DIR data directory (default: ./data)# BACKUP_DIR where archives are written (default: ./backups)# DATABASE_TYPE sqlite (default) | postgres+# SESSION_DATA_PATH, BAILEYS_AUTH_DIR, STORAGE_LOCAL_PATH, PLUGINS_DIR+# override the corresponding state directories# For postgres: DATABASE_URL, or DATABASE_HOST/PORT/USERNAME/PASSWORD/NAME#set -euo pipefail+# The archive now contains bootstrap credentials and generated database secrets. Never inherit a+# permissive operator umask for newly-created backup artifacts.+umask 077DATA_DIR="${OPENWA_DATA_DIR:-./data}"BACKUP_DIR="${BACKUP_DIR:-./backups}"@@ -28,8 +37,13 @@ TIMESTAMP="$(date +%Y%m%d-%H%M%S)"MAIN_DB="$DATA_DIR/main.sqlite"DATA_DB="$DATA_DIR/openwa.sqlite"-SESSIONS_DIR="$DATA_DIR/sessions"-MEDIA_DIR="$DATA_DIR/media"+SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"+BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"+MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"+PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-./plugins}"+PLUGIN_STATE_DIR="$DATA_DIR/plugins"+GENERATED_ENV="$DATA_DIR/.env.generated"+ADMIN_KEY_FILE="$DATA_DIR/.api-key"log() { echo "[backup] $*"; }@@ -77,15 +91,42 @@ elsefiif [ -d "$SESSIONS_DIR" ]; then- log "Backing up WhatsApp sessions"- cp -r "$SESSIONS_DIR" "$STAGE/sessions"+ log "Backing up whatsapp-web.js sessions"+ cp -pR "$SESSIONS_DIR" "$STAGE/sessions"elselog "WARN: $SESSIONS_DIR not found — skipping sessions"fi+if [ -d "$BAILEYS_DIR" ]; then+ log "Backing up Baileys authentication state"+ cp -pR "$BAILEYS_DIR" "$STAGE/baileys"+elif [ "${ENGINE_TYPE:-}" = "baileys" ]; then+ log "WARN: ENGINE_TYPE=baileys but $BAILEYS_DIR was not found — restored sessions will require pairing"+fi+if [ -d "$MEDIA_DIR" ]; thenlog "Backing up local media"- cp -r "$MEDIA_DIR" "$STAGE/media"+ cp -pR "$MEDIA_DIR" "$STAGE/media"+fi++if [ -d "$PLUGIN_PACKAGES_DIR" ]; then+ log "Backing up installed plugin packages"+ cp -pR "$PLUGIN_PACKAGES_DIR" "$STAGE/plugin-packages"+fi++if [ -d "$PLUGIN_STATE_DIR" ]; then+ log "Backing up plugin registry and persisted state"+ cp -pR "$PLUGIN_STATE_DIR" "$STAGE/plugin-state"+fi++if [ -f "$GENERATED_ENV" ]; then+ log "Backing up dashboard-generated configuration"+ cp -p "$GENERATED_ENV" "$STAGE/.env.generated"+fi++if [ -f "$ADMIN_KEY_FILE" ]; then+ log "Backing up plaintext admin key"+ cp -p "$ADMIN_KEY_FILE" "$STAGE/.api-key"fimkdir -p "$BACKUP_DIR"@@ -93,5 +134,6 @@ ARCHIVE="$BACKUP_DIR/openwa-backup-$TIMESTAMP.tar.gz"tar -czf "$ARCHIVE" -C "$STAGE" .log "Backup complete: $ARCHIVE"+log "SECURITY: this archive can contain database passwords, plugin secrets, and an admin API key; restrict and encrypt it"log "Contents:"tar -tzf "$ARCHIVE" | sed 's/^/[backup] /'diff --git a/scripts/restore.sh b/scripts/restore.shindex 0545ee3f1..96fcf7314 100755--- a/scripts/restore.sh+++ b/scripts/restore.sh@@ -2,24 +2,121 @@## OpenWA restore.#-# Restores BOTH databases (auth/audit + data) and the WhatsApp sessions from an-# archive produced by scripts/backup.sh, so API keys and audit history survive.+# Restores the always-SQLite auth/audit database, a SQLite data store, engine authentication, local+# media, installed plugins, and bootstrap configuration from an archive produced by scripts/backup.sh.+# PostgreSQL dumps are staged for the explicit psql import printed at the end of the restore.## Usage:# ./scripts/restore.sh <backup-archive.tar.gz># Environment:# OPENWA_DATA_DIR data directory to restore into (default: ./data)+# SESSION_DATA_PATH, BAILEYS_AUTH_DIR, STORAGE_LOCAL_PATH, PLUGINS_DIR+# override the corresponding state directories## Stop the OpenWA app before restoring. A snapshot of the current data dir is taken# first so a bad restore can be undone.#set -euo pipefail+# Restored databases, credentials, and snapshots must not inherit a permissive operator umask.+umask 077ARCHIVE="${1:-}"DATA_DIR="${OPENWA_DATA_DIR:-./data}"+SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"+BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"+MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"+PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-./plugins}"+PLUGIN_STATE_DIR="$DATA_DIR/plugins"+RESTORE_TIMESTAMP="$(date +%Y%m%d-%H%M%S)"+RESOLVED_CWD="$(pwd -P)"++# Resolve symlinks in the nearest existing ancestor as well as lexical '..' segments. This matters for+# destructive targets such as /mount-link/sessions: path.resolve alone would not reveal that mount-link+# points at the workspace, home directory, or another broad protected target.+resolve_path() {+ node -e '+ const fs = require("fs");+ const path = require("path");+ let current = path.resolve(process.argv[1]);+ const missing = [];+ while (!fs.existsSync(current)) {+ const parent = path.dirname(current);+ if (parent === current) break;+ missing.unshift(path.basename(current));+ current = parent;+ }+ const physical = fs.existsSync(current) ? fs.realpathSync(current) : current;+ console.log(path.join(physical, ...missing));+ ' "$1"+}++RESOLVED_DATA_DIR="$(resolve_path "$DATA_DIR")"+RESOLVED_USER_HOME="$(resolve_path "${HOME:-/nonexistent-openwa-home}")"log() { echo "[restore] $*"; }+case "$DATA_DIR" in+ '' | / | . | ./ | .. | ../)+ log "ERROR: refusing unsafe OPENWA_DATA_DIR target: ${DATA_DIR:-<empty>}"+ exit 1+ ;;+esac+case "$RESOLVED_CWD/" in+ "$RESOLVED_DATA_DIR"/*)+ log "ERROR: OPENWA_DATA_DIR must not be the workspace or one of its parent directories: $DATA_DIR"+ exit 1+ ;;+esac+if [ "$RESOLVED_DATA_DIR" = "$RESOLVED_USER_HOME" ]; then+ log "ERROR: OPENWA_DATA_DIR must not be the user home directory: $DATA_DIR"+ exit 1+fi++replace_tree() {+ source_dir="$1"+ target_dir="$2"+ label="$3"+ case "$target_dir" in+ '' | / | . | ./ | .. | ../)+ log "ERROR: refusing to replace unsafe $label target: ${target_dir:-<empty>}"+ exit 1+ ;;+ esac+ resolved_target="$(resolve_path "$target_dir")"+ if [ "$resolved_target" = "/" ] || [ "$resolved_target" = "$RESOLVED_CWD" ] || [ "$resolved_target" = "$RESOLVED_DATA_DIR" ] || [ "$resolved_target" = "$RESOLVED_USER_HOME" ]; then+ log "ERROR: refusing to replace broad $label target: $target_dir"+ exit 1+ fi+ case "$RESOLVED_CWD/" in+ "$resolved_target"/*)+ log "ERROR: refusing to replace $label target that contains the workspace: $target_dir"+ exit 1+ ;;+ esac+ case "$RESOLVED_DATA_DIR/" in+ "$resolved_target"/*)+ log "ERROR: refusing to replace $label target that contains the data directory: $target_dir"+ exit 1+ ;;+ esac+ # The initial data-dir snapshot already covers normal nested targets. Preserve any custom target+ # outside data/ separately before replacing it, so a custom PLUGINS_DIR/auth path remains recoverable.+ case "$resolved_target" in+ "$RESOLVED_DATA_DIR"/*) ;;+ *)+ if [ -e "$target_dir" ]; then+ external_snapshot="${target_dir%/}.pre-restore-$RESTORE_TIMESTAMP"+ log "Snapshotting current $label -> $external_snapshot"+ cp -pR "$target_dir" "$external_snapshot"+ fi+ ;;+ esac+ log "Restoring $label"+ rm -rf -- "$target_dir"+ mkdir -p "$(dirname "$target_dir")"+ cp -pR "$source_dir" "$target_dir"+}+if [ -z "$ARCHIVE" ] || [ ! -f "$ARCHIVE" ]; thenecho "Usage: $0 <backup-archive.tar.gz>" >&2exit 1@@ -29,13 +126,23 @@ STAGE="$(mktemp -d)"trap 'rm -rf "$STAGE"' EXITlog "Extracting $ARCHIVE"+# Refuse archive path names that could escape STAGE. This restore command accepts archives produced by+# backup.sh; path validation is an additional traversal guard, not a general untrusted-tar verifier.+while IFS= read -r entry; do+ case "$entry" in+ /* | ../* | */../* | */..)+ log "ERROR: unsafe path in backup archive: $entry"+ exit 1+ ;;+ esac+done < <(tar -tzf "$ARCHIVE")tar -xzf "$ARCHIVE" -C "$STAGE"# Safety snapshot of whatever is there now.if [ -d "$DATA_DIR" ] && [ -n "$(ls -A "$DATA_DIR" 2>/dev/null || true)" ]; then- SAFETY="${DATA_DIR%/}.pre-restore-$(date +%Y%m%d-%H%M%S)"+ SAFETY="${DATA_DIR%/}.pre-restore-$RESTORE_TIMESTAMP"log "Snapshotting current data dir -> $SAFETY"- cp -r "$DATA_DIR" "$SAFETY"+ cp -pR "$DATA_DIR" "$SAFETY"fimkdir -p "$DATA_DIR"@@ -53,15 +160,48 @@ if [ -f "$STAGE/openwa.sqlite" ]; thenfiif [ -d "$STAGE/sessions" ]; then- log "Restoring WhatsApp sessions"- rm -rf "$DATA_DIR/sessions"- cp -r "$STAGE/sessions" "$DATA_DIR/sessions"+ replace_tree "$STAGE/sessions" "$SESSIONS_DIR" "whatsapp-web.js sessions"+fi++if [ -d "$STAGE/baileys" ]; then+ replace_tree "$STAGE/baileys" "$BAILEYS_DIR" "Baileys authentication state"fiif [ -d "$STAGE/media" ]; then- log "Restoring local media"- rm -rf "$DATA_DIR/media"- cp -r "$STAGE/media" "$DATA_DIR/media"+ replace_tree "$STAGE/media" "$MEDIA_DIR" "local media"+fi++if [ -d "$STAGE/plugin-packages" ] && [ -d "$STAGE/plugin-state" ]; then+ RESOLVED_PLUGIN_PACKAGES_DIR="$(resolve_path "$PLUGIN_PACKAGES_DIR")"+ RESOLVED_PLUGIN_STATE_DIR="$(resolve_path "$PLUGIN_STATE_DIR")"+ if [ "$RESOLVED_PLUGIN_PACKAGES_DIR" = "$RESOLVED_PLUGIN_STATE_DIR" ]; then+ # Docker deployments deliberately colocate package and state files. Build the complete target in+ # staging and replace it once, so neither half can erase the other during restore.+ MERGED_PLUGINS_DIR="$STAGE/plugin-merged"+ mkdir -p "$MERGED_PLUGINS_DIR"+ cp -pR "$STAGE/plugin-packages/." "$MERGED_PLUGINS_DIR"+ cp -pR "$STAGE/plugin-state/." "$MERGED_PLUGINS_DIR"+ replace_tree "$MERGED_PLUGINS_DIR" "$PLUGIN_PACKAGES_DIR" "installed plugins and plugin state"+ else+ replace_tree "$STAGE/plugin-packages" "$PLUGIN_PACKAGES_DIR" "installed plugin packages"+ replace_tree "$STAGE/plugin-state" "$PLUGIN_STATE_DIR" "plugin registry and persisted state"+ fi+elif [ -d "$STAGE/plugin-packages" ]; then+ replace_tree "$STAGE/plugin-packages" "$PLUGIN_PACKAGES_DIR" "installed plugin packages"+elif [ -d "$STAGE/plugin-state" ]; then+ replace_tree "$STAGE/plugin-state" "$PLUGIN_STATE_DIR" "plugin registry and persisted state"+fi++if [ -f "$STAGE/.env.generated" ]; then+ log "Restoring dashboard-generated configuration"+ cp "$STAGE/.env.generated" "$DATA_DIR/.env.generated"+ chmod 0600 "$DATA_DIR/.env.generated"+fi++if [ -f "$STAGE/.api-key" ]; then+ log "Restoring plaintext admin key"+ cp "$STAGE/.api-key" "$DATA_DIR/.api-key"+ chmod 0600 "$DATA_DIR/.api-key"fiif [ -f "$STAGE/database.sql" ]; thendiff --git a/sdk/README.md b/sdk/README.mdindex 7a5c22998..009b3345d 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -34,6 +34,7 @@ All five SDKs expose the same fluent resource surface:| `channels` | list, get, messages, subscribe, unsubscribe _(Newsletters)_ || `catalog` | info, products, product, sendProduct, sendCatalog _(WhatsApp Business)_ || `status` | list, fromContact, sendText, sendImage, sendVideo, delete _(Stories)_ |+| `search` | search _(Operator)_ || `templates`| list, get, create, update, delete || `health` | check, live, ready |diff --git a/sdk/go/client.go b/sdk/go/client.goindex 689f08e48..62ffb285d 100644--- a/sdk/go/client.go+++ b/sdk/go/client.go@@ -122,14 +122,10 @@ func New(baseURL, apiKey string, opts ...Option) (*Client, error) {}if cfg.httpClient != nil {hc.Jar = cfg.httpClient.Jar- if cfg.httpClient.Timeout > 0 {+ if cfg.httpClient.Timeout > 0 && !cfg.timeoutSet {hc.Timeout = cfg.httpClient.Timeout}}- // An explicit WithTimeout always wins.- if cfg.timeout > 0 {- hc.Timeout = cfg.timeout- }c := &Client{baseURL: cfg.baseURL,diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 8011c76f5..c1ee0e0da 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -536,6 +536,25 @@ func TestWithTimeoutZeroUsesDefault(t *testing.T) {}}+func TestInjectedHTTPClientTimeoutIsHonoredUnlessWithTimeoutIsExplicit(t *testing.T) {+ injected := &http.Client{Timeout: 45 * time.Second}+ c, err := New("http://localhost:2785", "k", WithHTTPClient(injected))+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ if c.timeout != 45*time.Second {+ t.Fatalf("injected timeout = %s, want 45s", c.timeout)+ }++ c, err = New("http://localhost:2785", "k", WithHTTPClient(injected), WithTimeout(5*time.Second))+ if err != nil {+ t.Fatalf("New explicit: %v", err)+ }+ if c.timeout != 5*time.Second {+ t.Fatalf("explicit timeout = %s, want 5s", c.timeout)+ }+}+func TestBulkMediaContentOmitsChatID(t *testing.T) {// The bulk media block must not emit a chatId key — the outer item carries// it, and BulkMediaDto rejects a stray empty one via forbidNonWhitelisted.diff --git a/sdk/go/options.go b/sdk/go/options.goindex da4383600..33192e565 100644--- a/sdk/go/options.go+++ b/sdk/go/options.go@@ -17,6 +17,7 @@ type config struct {baseURL stringapiKey stringtimeout time.Duration+ timeoutSet boolhttpClient *http.ClientbaseTransport http.RoundTripperlogger Logger@@ -35,7 +36,10 @@ type Option func(*config)// WithTimeout sets the per-request timeout. Zero uses DefaultTimeout. The// timeout also bounds retries, since it is enforced via the request context.func WithTimeout(d time.Duration) Option {- return func(c *config) { c.timeout = d }+ return func(c *config) {+ c.timeout = d+ c.timeoutSet = true+ }}// WithHTTPClient injects a fully-configured *http.Client (connection pool,diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMediaRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMediaRequest.javanew file mode 100644index 000000000..73a037360--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMediaRequest.java@@ -0,0 +1,32 @@+package com.rmyndharis.openwa.model;++/** Nested bulk media payload. The server consumes {@code ptt} only for the audio member. */+public record BulkMediaRequest(+ String url,+ String base64,+ String mimetype,+ String filename,+ Boolean ptt) {++ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String url;+ private String base64;+ private String mimetype;+ private String filename;+ private Boolean ptt;++ public Builder url(String v) { this.url = v; return this; }+ public Builder base64(String v) { this.base64 = v; return this; }+ public Builder mimetype(String v) { this.mimetype = v; return this; }+ public Builder filename(String v) { this.filename = v; return this; }+ public Builder ptt(Boolean v) { this.ptt = v; return this; }++ public BulkMediaRequest build() {+ return new BulkMediaRequest(url, base64, mimetype, filename, ptt);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.javaindex 97c0d8e35..80855ba3f 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java@@ -3,10 +3,10 @@ package com.rmyndharis.openwa.model;/** Content payload for one bulk-send item. Populate the field matching the item's {@link BulkMessageType}. */public record BulkMessageContent(String text,- SendMediaRequest image,- SendMediaRequest video,- SendMediaRequest audio,- SendMediaRequest document,+ BulkMediaRequest image,+ BulkMediaRequest video,+ BulkMediaRequest audio,+ BulkMediaRequest document,String caption) {public static Builder builder() {@@ -15,10 +15,10 @@ public record BulkMessageContent(public static final class Builder {private String text;- private SendMediaRequest image;- private SendMediaRequest video;- private SendMediaRequest audio;- private SendMediaRequest document;+ private BulkMediaRequest image;+ private BulkMediaRequest video;+ private BulkMediaRequest audio;+ private BulkMediaRequest document;private String caption;public Builder text(String v) {@@ -26,22 +26,22 @@ public record BulkMessageContent(return this;}- public Builder image(SendMediaRequest v) {+ public Builder image(BulkMediaRequest v) {this.image = v;return this;}- public Builder video(SendMediaRequest v) {+ public Builder video(BulkMediaRequest v) {this.video = v;return this;}- public Builder audio(SendMediaRequest v) {+ public Builder audio(BulkMediaRequest v) {this.audio = v;return this;}- public Builder document(SendMediaRequest v) {+ public Builder document(BulkMediaRequest v) {this.document = v;return this;}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendAudioRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendAudioRequest.javanew file mode 100644index 000000000..3d410de07--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendAudioRequest.java@@ -0,0 +1,38 @@+package com.rmyndharis.openwa.model;++/** Request body for sending audio, including the audio-only voice-note (PTT) flag. */+public record SendAudioRequest(+ String chatId,+ String url,+ String base64,+ String mimetype,+ String filename,+ String caption,+ Boolean ptt) {++ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String chatId;+ private String url;+ private String base64;+ private String mimetype;+ private String filename;+ private String caption;+ private Boolean ptt;++ public Builder chatId(String v) { this.chatId = v; return this; }+ public Builder url(String v) { this.url = v; return this; }+ public Builder base64(String v) { this.base64 = v; return this; }+ public Builder mimetype(String v) { this.mimetype = v; return this; }+ public Builder filename(String v) { this.filename = v; return this; }+ public Builder caption(String v) { this.caption = v; return this; }+ public Builder ptt(Boolean v) { this.ptt = v; return this; }++ public SendAudioRequest build() {+ return new SendAudioRequest(chatId, url, base64, mimetype, filename, caption, ptt);+ }+ }+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendMediaRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendMediaRequest.javaindex d2c56ab45..612c932e9 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendMediaRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendMediaRequest.java@@ -1,14 +1,13 @@package com.rmyndharis.openwa.model;-/** Request body for sending media (image/video/audio/document/sticker). Provide {@code url} or {@code base64}. */+/** Request body for sending image/video/document/sticker media. Provide {@code url} or {@code base64}. */public record SendMediaRequest(String chatId,String url,String base64,String mimetype,String filename,- String caption,- Boolean ptt) {+ String caption) {public static Builder builder() {return new Builder();@@ -21,7 +20,6 @@ public record SendMediaRequest(private String mimetype;private String filename;private String caption;- private Boolean ptt;public Builder chatId(String v) {this.chatId = v;@@ -57,14 +55,8 @@ public record SendMediaRequest(return this;}- /** Audio only: send as a WhatsApp voice note (PTT). */- public Builder ptt(Boolean v) {- this.ptt = v;- return this;- }-public SendMediaRequest build() {- return new SendMediaRequest(chatId, url, base64, mimetype, filename, caption, ptt);+ return new SendMediaRequest(chatId, url, base64, mimetype, filename, caption);}}}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex a476b0749..22f3ac640 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -20,6 +20,7 @@ import com.rmyndharis.openwa.model.SendBulkRequest;import com.rmyndharis.openwa.model.SendContactRequest;import com.rmyndharis.openwa.model.SendLocationRequest;import com.rmyndharis.openwa.model.SendMediaRequest;+import com.rmyndharis.openwa.model.SendAudioRequest;import com.rmyndharis.openwa.model.SendTemplateRequest;import com.rmyndharis.openwa.model.SendTextRequest;import com.rmyndharis.openwa.model.SuccessResult;@@ -68,7 +69,7 @@ public final class MessagesResource {}/** Send an audio file (url or base64). */- public MessageResponse sendAudio(String sessionId, SendMediaRequest body) {+ public MessageResponse sendAudio(String sessionId, SendAudioRequest body) {return sendMedia(sessionId, "send-audio", body);}@@ -214,7 +215,7 @@ public final class MessagesResource {// ── Internal ───────────────────────────────────────────────────────/** POST {@code /messages/send-<kind>} for the five media send helpers. */- private MessageResponse sendMedia(String sessionId, String kind, SendMediaRequest body) {+ private MessageResponse sendMedia(String sessionId, String kind, Object body) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/" + kind,diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.javaindex ac96c28b4..1d5eb6efd 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java@@ -19,6 +19,7 @@ import com.rmyndharis.openwa.model.SendBulkRequest;import com.rmyndharis.openwa.model.SendContactRequest;import com.rmyndharis.openwa.model.SendLocationRequest;import com.rmyndharis.openwa.model.SendMediaRequest;+import com.rmyndharis.openwa.model.SendAudioRequest;import com.rmyndharis.openwa.model.SendTemplateRequest;import com.rmyndharis.openwa.model.SendTextRequest;import com.rmyndharis.openwa.support.MockTransport;@@ -78,7 +79,7 @@ class MessagesResourceTest {void sendAudioResolvesToSendAudioPath() {tx.respond(200, MSG);client.messages.sendAudio(- "s", SendMediaRequest.builder().chatId("[email protected]").url("http://audio-url").ptt(true).build());+ "s", SendAudioRequest.builder().chatId("[email protected]").url("http://audio-url").ptt(true).build());assertEquals("http://h/api/sessions/s/messages/send-audio", tx.lastRequest().url());assertTrue(tx.lastRequest().body().contains("audio-url"));}diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex 884b306aa..067f0df82 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -101,9 +101,8 @@ export class OpenWAClient {}/**- * Shared media-send helper used by the image/video/audio/document/sticker- * methods, which all share the {@link SendMediaRequest} shape and only differ- * by their path segment.+ * Shared transport helper for image/video/audio/document/sticker sends. Public resource methods+ * expose the narrower per-route request types (including audio-only `ptt`).*/sendMedia(sessionId: string, segment: string, body: SendMediaRequest): Promise<MessageResponse> {return this.request<MessageResponse>({diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex f67f8a2b5..db1438278 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -92,9 +92,8 @@ export async function request<T>('X-API-Key': config.apiKey,};- let res: Response;try {- res = await config.fetch(url, {+ const res = await config.fetch(url, {method: options.method,headers,body: options.body !== undefined ? JSON.stringify(options.body) : undefined,@@ -104,30 +103,30 @@ export async function request<T>(// as a non-2xx error instead.redirect: 'manual',});++ if (!res.ok) {+ const context = `${options.method} ${options.path}`;+ const apiError = await OpenWAApiError.fromResponse(res, context);+ throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind);+ }++ if (res.status === 204) {+ return null as T;+ }+ const text = await res.text();+ if (!text) return null as T;+ try {+ return JSON.parse(text) as T;+ } catch {+ return text as unknown as T;+ }} catch (err) {- clearTimeout(timer);if (err instanceof Error && err.name === 'AbortError') {throw new OpenWATimeoutError(timeoutMs);}throw err;- }- clearTimeout(timer);-- if (!res.ok) {- const context = `${options.method} ${options.path}`;- const apiError = await OpenWAApiError.fromResponse(res, context);- throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind);- }-- if (res.status === 204) {- return null as T;- }- const text = await res.text();- if (!text) return null as T;- try {- return JSON.parse(text) as T;- } catch {- return text as unknown as T;+ } finally {+ clearTimeout(timer);}}diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex 4818a43a4..46f902a88 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -24,6 +24,7 @@ import type {SendBulkRequest,SendContactRequest,SendLocationRequest,+ SendAudioRequest,SendMediaRequest,SendTemplateRequest,SendTextRequest,@@ -62,7 +63,7 @@ export class MessagesResource {}/** Send an audio file (url or base64). */- sendAudio(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {+ sendAudio(sessionId: string, body: SendAudioRequest): Promise<MessageResponse> {return this.client.sendMedia(sessionId, 'send-audio', body);}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 224f57978..05eb13783 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -18,13 +18,7 @@ export type Jid = string;/** Session lifecycle status. */export type SessionStatus =- | 'created'- | 'initializing'- | 'qr_ready'- | 'authenticating'- | 'ready'- | 'disconnected'- | 'failed';+ 'created' | 'initializing' | 'qr_ready' | 'authenticating' | 'ready' | 'disconnected' | 'failed';/** Minimal success envelope returned by some state-changing endpoints. */export interface SuccessResult {@@ -108,10 +102,23 @@ export interface SendMediaRequest {filename?: string;/** Max 1024 chars. */caption?: string;+}++export interface SendAudioRequest extends SendMediaRequest {/** Audio only: send as a WhatsApp voice note (PTT). Server defaults mimetype to audio/ogg; codecs=opus. */ptt?: boolean;}+/** Nested media payload accepted by bulk sends; chatId lives on the parent and caption on content. */+export interface BulkMediaRequest {+ url?: string;+ base64?: string;+ mimetype?: string;+ filename?: string;+ /** Only the audio member consumes this flag. */+ ptt?: boolean;+}+export interface SendLocationRequest {chatId: Jid;latitude: number;@@ -258,10 +265,10 @@ export type BulkMessageType = 'text' | 'image' | 'video' | 'audio' | 'document';export interface BulkMessageContent {text?: string;- image?: SendMediaRequest;- video?: SendMediaRequest;- audio?: SendMediaRequest;- document?: SendMediaRequest;+ image?: BulkMediaRequest;+ video?: BulkMediaRequest;+ audio?: BulkMediaRequest;+ document?: BulkMediaRequest;caption?: string;}diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 1514ba0d8..2daa20ad6 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -159,6 +159,25 @@ describe('OpenWAClient', () => {await expect(c.sessions.list()).rejects.toBeInstanceOf(OpenWATimeoutError);});+ it('keeps the timeout armed while reading a stalled response body', async () => {+ const stalledBodyFetch: FetchLike = async (_url, init) => {+ const signal = init?.signal;+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ signal?.addEventListener('abort', () => {+ const error = new Error('body aborted');+ error.name = 'AbortError';+ controller.error(error);+ });+ },+ });+ return new Response(body, { status: 200 });+ };+ const c = new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', timeoutMs: 5, fetch: stalledBodyFetch });++ await expect(c.sessions.list()).rejects.toBeInstanceOf(OpenWATimeoutError);+ });+it('keeps X-API-Key winning over defaultHeaders', async () => {const t = new MockTransport().on('GET', '/api/sessions', { body: [] });const c = new OpenWAClient({diff --git a/sdk/php/composer.json b/sdk/php/composer.jsonindex b527b0e4b..d556e3894 100644--- a/sdk/php/composer.json+++ b/sdk/php/composer.json@@ -20,7 +20,7 @@"guzzlehttp/guzzle": "^7.9"},"require-dev": {- "phpunit/phpunit": "^10.0 || ^11.0"+ "phpunit/phpunit": "^10.0"},"autoload": {"psr-4": {@@ -40,4 +40,4 @@"dev-main": "0.1.x-dev"}}-}\ No newline at end of file+}diff --git a/sdk/php/composer.lock b/sdk/php/composer.lockindex 56319454d..225e729a5 100644--- a/sdk/php/composer.lock+++ b/sdk/php/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "9b83387ddd5fcd1d393e7ea4fc954ea0",+ "content-hash": "a96d9bf108617a01cfb38a346c242222","packages": [{"name": "guzzlehttp/guzzle",@@ -760,20 +760,19 @@},{"name": "nikic/php-parser",- "version": "v5.7.0",+ "version": "v5.8.0","source": {"type": "git","url": "https://github.com/nikic/PHP-Parser.git",- "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82"+ "reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/dca41cd15c2ac9d055ad70dbfd011130757d1f82",- "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82",+ "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/044a6a392ff8ad0d61f14370a5fbbd0a0107152f",+ "reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f","shasum": ""},"require": {- "ext-ctype": "*","ext-json": "*","ext-tokenizer": "*","php": ">=7.4"@@ -812,9 +811,9 @@],"support": {"issues": "https://github.com/nikic/PHP-Parser/issues",- "source": "https://github.com/nikic/PHP-Parser/tree/v5.7.0"+ "source": "https://github.com/nikic/PHP-Parser/tree/v5.8.0"},- "time": "2025-12-06T11:56:16+00:00"+ "time": "2026-07-04T14:30:18+00:00"},{"name": "phar-io/manifest",@@ -936,35 +935,35 @@},{"name": "phpunit/php-code-coverage",- "version": "11.0.12",+ "version": "10.1.16","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-code-coverage.git",- "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56"+ "reference": "7e308268858ed6baedc8704a304727d20bc07c77"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2c1ed04922802c15e1de5d7447b4856de949cf56",- "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56",+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7e308268858ed6baedc8704a304727d20bc07c77",+ "reference": "7e308268858ed6baedc8704a304727d20bc07c77","shasum": ""},"require": {"ext-dom": "*","ext-libxml": "*","ext-xmlwriter": "*",- "nikic/php-parser": "^5.7.0",- "php": ">=8.2",- "phpunit/php-file-iterator": "^5.1.0",- "phpunit/php-text-template": "^4.0.1",- "sebastian/code-unit-reverse-lookup": "^4.0.1",- "sebastian/complexity": "^4.0.1",- "sebastian/environment": "^7.2.1",- "sebastian/lines-of-code": "^3.0.1",- "sebastian/version": "^5.0.2",- "theseer/tokenizer": "^1.3.1"+ "nikic/php-parser": "^4.19.1 || ^5.1.0",+ "php": ">=8.1",+ "phpunit/php-file-iterator": "^4.1.0",+ "phpunit/php-text-template": "^3.0.1",+ "sebastian/code-unit-reverse-lookup": "^3.0.0",+ "sebastian/complexity": "^3.2.0",+ "sebastian/environment": "^6.1.0",+ "sebastian/lines-of-code": "^2.0.2",+ "sebastian/version": "^4.0.1",+ "theseer/tokenizer": "^1.2.3"},"require-dev": {- "phpunit/phpunit": "^11.5.46"+ "phpunit/phpunit": "^10.1"},"suggest": {"ext-pcov": "PHP extension that provides line coverage",@@ -973,7 +972,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "11.0.x-dev"+ "dev-main": "10.1.x-dev"}},"autoload": {@@ -1002,52 +1001,40 @@"support": {"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues","security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/11.0.12"+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/10.1.16"},"funding": [{"url": "https://github.com/sebastianbergmann","type": "github"- },- {- "url": "https://liberapay.com/sebastianbergmann",- "type": "liberapay"- },- {- "url": "https://thanks.dev/u/gh/sebastianbergmann",- "type": "thanks_dev"- },- {- "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage",- "type": "tidelift"}],- "time": "2025-12-24T07:01:01+00:00"+ "time": "2024-08-22T04:31:57+00:00"},{"name": "phpunit/php-file-iterator",- "version": "5.1.1",+ "version": "4.1.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-file-iterator.git",- "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903"+ "reference": "a95037b6d9e608ba092da1b23931e537cadc3c3c"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/2f3a64888c814fc235386b7387dd5b5ed92ad903",- "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903",+ "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/a95037b6d9e608ba092da1b23931e537cadc3c3c",+ "reference": "a95037b6d9e608ba092da1b23931e537cadc3c3c","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.3"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "5.1-dev"+ "dev-main": "4.0-dev"}},"autoload": {@@ -1075,48 +1062,36 @@"support": {"issues": "https://github.com/sebastianbergmann/php-file-iterator/issues","security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy",- "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.1.1"+ "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/4.1.0"},"funding": [{"url": "https://github.com/sebastianbergmann","type": "github"- },- {- "url": "https://liberapay.com/sebastianbergmann",- "type": "liberapay"- },- {- "url": "https://thanks.dev/u/gh/sebastianbergmann",- "type": "thanks_dev"- },- {- "url": "https://tidelift.com/funding/github/packagist/phpunit/php-file-iterator",- "type": "tidelift"}],- "time": "2026-02-02T13:52:54+00:00"+ "time": "2023-08-31T06:24:48+00:00"},{"name": "phpunit/php-invoker",- "version": "5.0.1",+ "version": "4.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-invoker.git",- "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2"+ "reference": "f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/c1ca3814734c07492b3d4c5f794f4b0995333da2",- "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2",+ "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7",+ "reference": "f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {"ext-pcntl": "*",- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"suggest": {"ext-pcntl": "*"@@ -1124,7 +1099,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "5.0-dev"+ "dev-main": "4.0-dev"}},"autoload": {@@ -1150,8 +1125,7 @@],"support": {"issues": "https://github.com/sebastianbergmann/php-invoker/issues",- "security": "https://github.com/sebastianbergmann/php-invoker/security/policy",- "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.1"+ "source": "https://github.com/sebastianbergmann/php-invoker/tree/4.0.0"},"funding": [{@@ -1159,32 +1133,32 @@"type": "github"}],- "time": "2024-07-03T05:07:44+00:00"+ "time": "2023-02-03T06:56:09+00:00"},{"name": "phpunit/php-text-template",- "version": "4.0.1",+ "version": "3.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-text-template.git",- "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964"+ "reference": "0c7b06ff49e3d5072f057eb1fa59258bf287a748"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/3e0404dc6b300e6bf56415467ebcb3fe4f33e964",- "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964",+ "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/0c7b06ff49e3d5072f057eb1fa59258bf287a748",+ "reference": "0c7b06ff49e3d5072f057eb1fa59258bf287a748","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "4.0-dev"+ "dev-main": "3.0-dev"}},"autoload": {@@ -1211,7 +1185,7 @@"support": {"issues": "https://github.com/sebastianbergmann/php-text-template/issues","security": "https://github.com/sebastianbergmann/php-text-template/security/policy",- "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.1"+ "source": "https://github.com/sebastianbergmann/php-text-template/tree/3.0.1"},"funding": [{@@ -1219,32 +1193,32 @@"type": "github"}],- "time": "2024-07-03T05:08:43+00:00"+ "time": "2023-08-31T14:07:24+00:00"},{"name": "phpunit/php-timer",- "version": "7.0.1",+ "version": "6.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-timer.git",- "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3"+ "reference": "e2a2d67966e740530f4a3343fe2e030ffdc1161d"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3b415def83fbcb41f991d9ebf16ae4ad8b7837b3",- "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3",+ "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/e2a2d67966e740530f4a3343fe2e030ffdc1161d",+ "reference": "e2a2d67966e740530f4a3343fe2e030ffdc1161d","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "7.0-dev"+ "dev-main": "6.0-dev"}},"autoload": {@@ -1270,8 +1244,7 @@],"support": {"issues": "https://github.com/sebastianbergmann/php-timer/issues",- "security": "https://github.com/sebastianbergmann/php-timer/security/policy",- "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.1"+ "source": "https://github.com/sebastianbergmann/php-timer/tree/6.0.0"},"funding": [{@@ -1279,50 +1252,49 @@"type": "github"}],- "time": "2024-07-03T05:09:35+00:00"+ "time": "2023-02-03T06:57:52+00:00"},{"name": "phpunit/phpunit",- "version": "11.5.55",+ "version": "10.5.64","source": {"type": "git","url": "https://github.com/sebastianbergmann/phpunit.git",- "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00"+ "reference": "0e8c1d19cea35ad97d4887f363d07c78e30fbf06"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/adc7262fccc12de2b30f12a8aa0b33775d814f00",- "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00",+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/0e8c1d19cea35ad97d4887f363d07c78e30fbf06",+ "reference": "0e8c1d19cea35ad97d4887f363d07c78e30fbf06","shasum": ""},"require": {"ext-dom": "*",+ "ext-filter": "*","ext-json": "*","ext-libxml": "*","ext-mbstring": "*",- "ext-xml": "*","ext-xmlwriter": "*","myclabs/deep-copy": "^1.13.4","phar-io/manifest": "^2.0.4","phar-io/version": "^3.2.1",- "php": ">=8.2",- "phpunit/php-code-coverage": "^11.0.12",- "phpunit/php-file-iterator": "^5.1.1",- "phpunit/php-invoker": "^5.0.1",- "phpunit/php-text-template": "^4.0.1",- "phpunit/php-timer": "^7.0.1",- "sebastian/cli-parser": "^3.0.2",- "sebastian/code-unit": "^3.0.3",- "sebastian/comparator": "^6.3.3",- "sebastian/diff": "^6.0.2",- "sebastian/environment": "^7.2.1",- "sebastian/exporter": "^6.3.2",- "sebastian/global-state": "^7.0.2",- "sebastian/object-enumerator": "^6.0.1",- "sebastian/recursion-context": "^6.0.3",- "sebastian/type": "^5.1.3",- "sebastian/version": "^5.0.2",- "staabm/side-effects-detector": "^1.0.5"+ "php": ">=8.1",+ "phpunit/php-code-coverage": "^10.1.16",+ "phpunit/php-file-iterator": "^4.1.0",+ "phpunit/php-invoker": "^4.0.0",+ "phpunit/php-text-template": "^3.0.1",+ "phpunit/php-timer": "^6.0.0",+ "sebastian/cli-parser": "^2.0.1",+ "sebastian/code-unit": "^2.0.0",+ "sebastian/comparator": "^5.0.5",+ "sebastian/diff": "^5.1.1",+ "sebastian/environment": "^6.1.0",+ "sebastian/exporter": "^5.1.4",+ "sebastian/global-state": "^6.0.2",+ "sebastian/object-enumerator": "^5.0.0",+ "sebastian/recursion-context": "^5.0.1",+ "sebastian/type": "^4.0.0",+ "sebastian/version": "^4.0.1"},"suggest": {"ext-soap": "To be able to generate mocks based on WSDL files"@@ -1333,7 +1305,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "11.5-dev"+ "dev-main": "10.5-dev"}},"autoload": {@@ -1365,56 +1337,40 @@"support": {"issues": "https://github.com/sebastianbergmann/phpunit/issues","security": "https://github.com/sebastianbergmann/phpunit/security/policy",- "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.55"+ "source": "https://github.com/sebastianbergmann/phpunit/tree/10.5.64"},"funding": [{- "url": "https://phpunit.de/sponsors.html",- "type": "custom"- },- {- "url": "https://github.com/sebastianbergmann",- "type": "github"- },- {- "url": "https://liberapay.com/sebastianbergmann",- "type": "liberapay"- },- {- "url": "https://thanks.dev/u/gh/sebastianbergmann",- "type": "thanks_dev"- },- {- "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit",- "type": "tidelift"+ "url": "https://phpunit.de/sponsoring.html",+ "type": "other"}],- "time": "2026-02-18T12:37:06+00:00"+ "time": "2026-07-06T14:50:35+00:00"},{"name": "sebastian/cli-parser",- "version": "3.0.2",+ "version": "2.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/cli-parser.git",- "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180"+ "reference": "c34583b87e7b7a8055bf6c450c2c77ce32a24084"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/15c5dd40dc4f38794d383bb95465193f5e0ae180",- "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180",+ "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/c34583b87e7b7a8055bf6c450c2c77ce32a24084",+ "reference": "c34583b87e7b7a8055bf6c450c2c77ce32a24084","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "3.0-dev"+ "dev-main": "2.0-dev"}},"autoload": {@@ -1438,7 +1394,7 @@"support": {"issues": "https://github.com/sebastianbergmann/cli-parser/issues","security": "https://github.com/sebastianbergmann/cli-parser/security/policy",- "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.2"+ "source": "https://github.com/sebastianbergmann/cli-parser/tree/2.0.1"},"funding": [{@@ -1446,32 +1402,32 @@"type": "github"}],- "time": "2024-07-03T04:41:36+00:00"+ "time": "2024-03-02T07:12:49+00:00"},{"name": "sebastian/code-unit",- "version": "3.0.3",+ "version": "2.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/code-unit.git",- "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64"+ "reference": "a81fee9eef0b7a76af11d121767abc44c104e503"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/54391c61e4af8078e5b276ab082b6d3c54c9ad64",- "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64",+ "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/a81fee9eef0b7a76af11d121767abc44c104e503",+ "reference": "a81fee9eef0b7a76af11d121767abc44c104e503","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.5"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "3.0-dev"+ "dev-main": "2.0-dev"}},"autoload": {@@ -1494,8 +1450,7 @@"homepage": "https://github.com/sebastianbergmann/code-unit","support": {"issues": "https://github.com/sebastianbergmann/code-unit/issues",- "security": "https://github.com/sebastianbergmann/code-unit/security/policy",- "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.3"+ "source": "https://github.com/sebastianbergmann/code-unit/tree/2.0.0"},"funding": [{@@ -1503,32 +1458,32 @@"type": "github"}],- "time": "2025-03-19T07:56:08+00:00"+ "time": "2023-02-03T06:58:43+00:00"},{"name": "sebastian/code-unit-reverse-lookup",- "version": "4.0.1",+ "version": "3.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",- "reference": "183a9b2632194febd219bb9246eee421dad8d45e"+ "reference": "5e3a687f7d8ae33fb362c5c0743794bbb2420a1d"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/183a9b2632194febd219bb9246eee421dad8d45e",- "reference": "183a9b2632194febd219bb9246eee421dad8d45e",+ "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/5e3a687f7d8ae33fb362c5c0743794bbb2420a1d",+ "reference": "5e3a687f7d8ae33fb362c5c0743794bbb2420a1d","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "4.0-dev"+ "dev-main": "3.0-dev"}},"autoload": {@@ -1550,8 +1505,7 @@"homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/","support": {"issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",- "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy",- "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.1"+ "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/3.0.0"},"funding": [{@@ -1559,39 +1513,36 @@"type": "github"}],- "time": "2024-07-03T04:45:54+00:00"+ "time": "2023-02-03T06:59:15+00:00"},{"name": "sebastian/comparator",- "version": "6.3.3",+ "version": "5.0.5","source": {"type": "git","url": "https://github.com/sebastianbergmann/comparator.git",- "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9"+ "reference": "55dfef806eb7dfeb6e7a6935601fef866f8ca48d"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2c95e1e86cb8dd41beb8d502057d1081ccc8eca9",- "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9",+ "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/55dfef806eb7dfeb6e7a6935601fef866f8ca48d",+ "reference": "55dfef806eb7dfeb6e7a6935601fef866f8ca48d","shasum": ""},"require": {"ext-dom": "*","ext-mbstring": "*",- "php": ">=8.2",- "sebastian/diff": "^6.0",- "sebastian/exporter": "^6.0"+ "php": ">=8.1",+ "sebastian/diff": "^5.0",+ "sebastian/exporter": "^5.0"},"require-dev": {- "phpunit/phpunit": "^11.4"- },- "suggest": {- "ext-bcmath": "For comparing BcMath\\Number objects"+ "phpunit/phpunit": "^10.5"},"type": "library","extra": {"branch-alias": {- "dev-main": "6.3-dev"+ "dev-main": "5.0-dev"}},"autoload": {@@ -1631,7 +1582,7 @@"support": {"issues": "https://github.com/sebastianbergmann/comparator/issues","security": "https://github.com/sebastianbergmann/comparator/security/policy",- "source": "https://github.com/sebastianbergmann/comparator/tree/6.3.3"+ "source": "https://github.com/sebastianbergmann/comparator/tree/5.0.5"},"funding": [{@@ -1651,33 +1602,33 @@"type": "tidelift"}],- "time": "2026-01-24T09:26:40+00:00"+ "time": "2026-01-24T09:25:16+00:00"},{"name": "sebastian/complexity",- "version": "4.0.1",+ "version": "3.2.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/complexity.git",- "reference": "ee41d384ab1906c68852636b6de493846e13e5a0"+ "reference": "68ff824baeae169ec9f2137158ee529584553799"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/ee41d384ab1906c68852636b6de493846e13e5a0",- "reference": "ee41d384ab1906c68852636b6de493846e13e5a0",+ "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/68ff824baeae169ec9f2137158ee529584553799",+ "reference": "68ff824baeae169ec9f2137158ee529584553799","shasum": ""},"require": {- "nikic/php-parser": "^5.0",- "php": ">=8.2"+ "nikic/php-parser": "^4.18 || ^5.0",+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "4.0-dev"+ "dev-main": "3.2-dev"}},"autoload": {@@ -1701,7 +1652,7 @@"support": {"issues": "https://github.com/sebastianbergmann/complexity/issues","security": "https://github.com/sebastianbergmann/complexity/security/policy",- "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.1"+ "source": "https://github.com/sebastianbergmann/complexity/tree/3.2.0"},"funding": [{@@ -1709,33 +1660,33 @@"type": "github"}],- "time": "2024-07-03T04:49:50+00:00"+ "time": "2023-12-21T08:37:17+00:00"},{"name": "sebastian/diff",- "version": "6.0.2",+ "version": "5.1.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/diff.git",- "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544"+ "reference": "c41e007b4b62af48218231d6c2275e4c9b975b2e"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/b4ccd857127db5d41a5b676f24b51371d76d8544",- "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544",+ "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/c41e007b4b62af48218231d6c2275e4c9b975b2e",+ "reference": "c41e007b4b62af48218231d6c2275e4c9b975b2e","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0",- "symfony/process": "^4.2 || ^5"+ "phpunit/phpunit": "^10.0",+ "symfony/process": "^6.4"},"type": "library","extra": {"branch-alias": {- "dev-main": "6.0-dev"+ "dev-main": "5.1-dev"}},"autoload": {@@ -1768,7 +1719,7 @@"support": {"issues": "https://github.com/sebastianbergmann/diff/issues","security": "https://github.com/sebastianbergmann/diff/security/policy",- "source": "https://github.com/sebastianbergmann/diff/tree/6.0.2"+ "source": "https://github.com/sebastianbergmann/diff/tree/5.1.1"},"funding": [{@@ -1776,27 +1727,27 @@"type": "github"}],- "time": "2024-07-03T04:53:05+00:00"+ "time": "2024-03-02T07:15:17+00:00"},{"name": "sebastian/environment",- "version": "7.2.1",+ "version": "6.1.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/environment.git",- "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4"+ "reference": "8074dbcd93529b357029f5cc5058fd3e43666984"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/a5c75038693ad2e8d4b6c15ba2403532647830c4",- "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4",+ "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/8074dbcd93529b357029f5cc5058fd3e43666984",+ "reference": "8074dbcd93529b357029f5cc5058fd3e43666984","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.3"+ "phpunit/phpunit": "^10.0"},"suggest": {"ext-posix": "*"@@ -1804,7 +1755,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "7.2-dev"+ "dev-main": "6.1-dev"}},"autoload": {@@ -1832,54 +1783,42 @@"support": {"issues": "https://github.com/sebastianbergmann/environment/issues","security": "https://github.com/sebastianbergmann/environment/security/policy",- "source": "https://github.com/sebastianbergmann/environment/tree/7.2.1"+ "source": "https://github.com/sebastianbergmann/environment/tree/6.1.0"},"funding": [{"url": "https://github.com/sebastianbergmann","type": "github"- },- {- "url": "https://liberapay.com/sebastianbergmann",- "type": "liberapay"- },- {- "url": "https://thanks.dev/u/gh/sebastianbergmann",- "type": "thanks_dev"- },- {- "url": "https://tidelift.com/funding/github/packagist/sebastian/environment",- "type": "tidelift"}],- "time": "2025-05-21T11:55:47+00:00"+ "time": "2024-03-23T08:47:14+00:00"},{"name": "sebastian/exporter",- "version": "6.3.2",+ "version": "5.1.4","source": {"type": "git","url": "https://github.com/sebastianbergmann/exporter.git",- "reference": "70a298763b40b213ec087c51c739efcaa90bcd74"+ "reference": "0735b90f4da94969541dac1da743446e276defa6"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/70a298763b40b213ec087c51c739efcaa90bcd74",- "reference": "70a298763b40b213ec087c51c739efcaa90bcd74",+ "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/0735b90f4da94969541dac1da743446e276defa6",+ "reference": "0735b90f4da94969541dac1da743446e276defa6","shasum": ""},"require": {"ext-mbstring": "*",- "php": ">=8.2",- "sebastian/recursion-context": "^6.0"+ "php": ">=8.1",+ "sebastian/recursion-context": "^5.0"},"require-dev": {- "phpunit/phpunit": "^11.3"+ "phpunit/phpunit": "^10.5"},"type": "library","extra": {"branch-alias": {- "dev-main": "6.3-dev"+ "dev-main": "5.1-dev"}},"autoload": {@@ -1922,7 +1861,7 @@"support": {"issues": "https://github.com/sebastianbergmann/exporter/issues","security": "https://github.com/sebastianbergmann/exporter/security/policy",- "source": "https://github.com/sebastianbergmann/exporter/tree/6.3.2"+ "source": "https://github.com/sebastianbergmann/exporter/tree/5.1.4"},"funding": [{@@ -1942,35 +1881,35 @@"type": "tidelift"}],- "time": "2025-09-24T06:12:51+00:00"+ "time": "2025-09-24T06:09:11+00:00"},{"name": "sebastian/global-state",- "version": "7.0.2",+ "version": "6.0.2","source": {"type": "git","url": "https://github.com/sebastianbergmann/global-state.git",- "reference": "3be331570a721f9a4b5917f4209773de17f747d7"+ "reference": "987bafff24ecc4c9ac418cab1145b96dd6e9cbd9"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/3be331570a721f9a4b5917f4209773de17f747d7",- "reference": "3be331570a721f9a4b5917f4209773de17f747d7",+ "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/987bafff24ecc4c9ac418cab1145b96dd6e9cbd9",+ "reference": "987bafff24ecc4c9ac418cab1145b96dd6e9cbd9","shasum": ""},"require": {- "php": ">=8.2",- "sebastian/object-reflector": "^4.0",- "sebastian/recursion-context": "^6.0"+ "php": ">=8.1",+ "sebastian/object-reflector": "^3.0",+ "sebastian/recursion-context": "^5.0"},"require-dev": {"ext-dom": "*",- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "7.0-dev"+ "dev-main": "6.0-dev"}},"autoload": {@@ -1996,7 +1935,7 @@"support": {"issues": "https://github.com/sebastianbergmann/global-state/issues","security": "https://github.com/sebastianbergmann/global-state/security/policy",- "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.2"+ "source": "https://github.com/sebastianbergmann/global-state/tree/6.0.2"},"funding": [{@@ -2004,33 +1943,33 @@"type": "github"}],- "time": "2024-07-03T04:57:36+00:00"+ "time": "2024-03-02T07:19:19+00:00"},{"name": "sebastian/lines-of-code",- "version": "3.0.1",+ "version": "2.0.2","source": {"type": "git","url": "https://github.com/sebastianbergmann/lines-of-code.git",- "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a"+ "reference": "856e7f6a75a84e339195d48c556f23be2ebf75d0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d36ad0d782e5756913e42ad87cb2890f4ffe467a",- "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a",+ "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/856e7f6a75a84e339195d48c556f23be2ebf75d0",+ "reference": "856e7f6a75a84e339195d48c556f23be2ebf75d0","shasum": ""},"require": {- "nikic/php-parser": "^5.0",- "php": ">=8.2"+ "nikic/php-parser": "^4.18 || ^5.0",+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "3.0-dev"+ "dev-main": "2.0-dev"}},"autoload": {@@ -2054,7 +1993,7 @@"support": {"issues": "https://github.com/sebastianbergmann/lines-of-code/issues","security": "https://github.com/sebastianbergmann/lines-of-code/security/policy",- "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.1"+ "source": "https://github.com/sebastianbergmann/lines-of-code/tree/2.0.2"},"funding": [{@@ -2062,34 +2001,34 @@"type": "github"}],- "time": "2024-07-03T04:58:38+00:00"+ "time": "2023-12-21T08:38:20+00:00"},{"name": "sebastian/object-enumerator",- "version": "6.0.1",+ "version": "5.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/object-enumerator.git",- "reference": "f5b498e631a74204185071eb41f33f38d64608aa"+ "reference": "202d0e344a580d7f7d04b3fafce6933e59dae906"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f5b498e631a74204185071eb41f33f38d64608aa",- "reference": "f5b498e631a74204185071eb41f33f38d64608aa",+ "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/202d0e344a580d7f7d04b3fafce6933e59dae906",+ "reference": "202d0e344a580d7f7d04b3fafce6933e59dae906","shasum": ""},"require": {- "php": ">=8.2",- "sebastian/object-reflector": "^4.0",- "sebastian/recursion-context": "^6.0"+ "php": ">=8.1",+ "sebastian/object-reflector": "^3.0",+ "sebastian/recursion-context": "^5.0"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "6.0-dev"+ "dev-main": "5.0-dev"}},"autoload": {@@ -2111,8 +2050,7 @@"homepage": "https://github.com/sebastianbergmann/object-enumerator/","support": {"issues": "https://github.com/sebastianbergmann/object-enumerator/issues",- "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy",- "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.1"+ "source": "https://github.com/sebastianbergmann/object-enumerator/tree/5.0.0"},"funding": [{@@ -2120,32 +2058,32 @@"type": "github"}],- "time": "2024-07-03T05:00:13+00:00"+ "time": "2023-02-03T07:08:32+00:00"},{"name": "sebastian/object-reflector",- "version": "4.0.1",+ "version": "3.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/object-reflector.git",- "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9"+ "reference": "24ed13d98130f0e7122df55d06c5c4942a577957"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/6e1a43b411b2ad34146dee7524cb13a068bb35f9",- "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9",+ "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/24ed13d98130f0e7122df55d06c5c4942a577957",+ "reference": "24ed13d98130f0e7122df55d06c5c4942a577957","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.0"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "4.0-dev"+ "dev-main": "3.0-dev"}},"autoload": {@@ -2167,8 +2105,7 @@"homepage": "https://github.com/sebastianbergmann/object-reflector/","support": {"issues": "https://github.com/sebastianbergmann/object-reflector/issues",- "security": "https://github.com/sebastianbergmann/object-reflector/security/policy",- "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.1"+ "source": "https://github.com/sebastianbergmann/object-reflector/tree/3.0.0"},"funding": [{@@ -2176,32 +2113,32 @@"type": "github"}],- "time": "2024-07-03T05:01:32+00:00"+ "time": "2023-02-03T07:06:18+00:00"},{"name": "sebastian/recursion-context",- "version": "6.0.3",+ "version": "5.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/recursion-context.git",- "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc"+ "reference": "47e34210757a2f37a97dcd207d032e1b01e64c7a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/f6458abbf32a6c8174f8f26261475dc133b3d9dc",- "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc",+ "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/47e34210757a2f37a97dcd207d032e1b01e64c7a",+ "reference": "47e34210757a2f37a97dcd207d032e1b01e64c7a","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.3"+ "phpunit/phpunit": "^10.5"},"type": "library","extra": {"branch-alias": {- "dev-main": "6.0-dev"+ "dev-main": "5.0-dev"}},"autoload": {@@ -2232,7 +2169,7 @@"support": {"issues": "https://github.com/sebastianbergmann/recursion-context/issues","security": "https://github.com/sebastianbergmann/recursion-context/security/policy",- "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.3"+ "source": "https://github.com/sebastianbergmann/recursion-context/tree/5.0.1"},"funding": [{@@ -2252,32 +2189,32 @@"type": "tidelift"}],- "time": "2025-08-13T04:42:22+00:00"+ "time": "2025-08-10T07:50:56+00:00"},{"name": "sebastian/type",- "version": "5.1.3",+ "version": "4.0.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/type.git",- "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449"+ "reference": "462699a16464c3944eefc02ebdd77882bd3925bf"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/f77d2d4e78738c98d9a68d2596fe5e8fa380f449",- "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449",+ "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/462699a16464c3944eefc02ebdd77882bd3925bf",+ "reference": "462699a16464c3944eefc02ebdd77882bd3925bf","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"require-dev": {- "phpunit/phpunit": "^11.3"+ "phpunit/phpunit": "^10.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "5.1-dev"+ "dev-main": "4.0-dev"}},"autoload": {@@ -2300,50 +2237,37 @@"homepage": "https://github.com/sebastianbergmann/type","support": {"issues": "https://github.com/sebastianbergmann/type/issues",- "security": "https://github.com/sebastianbergmann/type/security/policy",- "source": "https://github.com/sebastianbergmann/type/tree/5.1.3"+ "source": "https://github.com/sebastianbergmann/type/tree/4.0.0"},"funding": [{"url": "https://github.com/sebastianbergmann","type": "github"- },- {- "url": "https://liberapay.com/sebastianbergmann",- "type": "liberapay"- },- {- "url": "https://thanks.dev/u/gh/sebastianbergmann",- "type": "thanks_dev"- },- {- "url": "https://tidelift.com/funding/github/packagist/sebastian/type",- "type": "tidelift"}],- "time": "2025-08-09T06:55:48+00:00"+ "time": "2023-02-03T07:10:45+00:00"},{"name": "sebastian/version",- "version": "5.0.2",+ "version": "4.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/version.git",- "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874"+ "reference": "c51fa83a5d8f43f1402e3f32a005e6262244ef17"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c687e3387b99f5b03b6caa64c74b63e2936ff874",- "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874",+ "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c51fa83a5d8f43f1402e3f32a005e6262244ef17",+ "reference": "c51fa83a5d8f43f1402e3f32a005e6262244ef17","shasum": ""},"require": {- "php": ">=8.2"+ "php": ">=8.1"},"type": "library","extra": {"branch-alias": {- "dev-main": "5.0-dev"+ "dev-main": "4.0-dev"}},"autoload": {@@ -2366,8 +2290,7 @@"homepage": "https://github.com/sebastianbergmann/version","support": {"issues": "https://github.com/sebastianbergmann/version/issues",- "security": "https://github.com/sebastianbergmann/version/security/policy",- "source": "https://github.com/sebastianbergmann/version/tree/5.0.2"+ "source": "https://github.com/sebastianbergmann/version/tree/4.0.1"},"funding": [{@@ -2375,59 +2298,7 @@"type": "github"}],- "time": "2024-10-09T05:16:32+00:00"- },- {- "name": "staabm/side-effects-detector",- "version": "1.0.5",- "source": {- "type": "git",- "url": "https://github.com/staabm/side-effects-detector.git",- "reference": "d8334211a140ce329c13726d4a715adbddd0a163"- },- "dist": {- "type": "zip",- "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163",- "reference": "d8334211a140ce329c13726d4a715adbddd0a163",- "shasum": ""- },- "require": {- "ext-tokenizer": "*",- "php": "^7.4 || ^8.0"- },- "require-dev": {- "phpstan/extension-installer": "^1.4.3",- "phpstan/phpstan": "^1.12.6",- "phpunit/phpunit": "^9.6.21",- "symfony/var-dumper": "^5.4.43",- "tomasvotruba/type-coverage": "1.0.0",- "tomasvotruba/unused-public": "1.0.0"- },- "type": "library",- "autoload": {- "classmap": [- "lib/"- ]- },- "notification-url": "https://packagist.org/downloads/",- "license": [- "MIT"- ],- "description": "A static analysis tool to detect side effects in PHP code",- "keywords": [- "static analysis"- ],- "support": {- "issues": "https://github.com/staabm/side-effects-detector/issues",- "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5"- },- "funding": [- {- "url": "https://github.com/staabm",- "type": "github"- }- ],- "time": "2024-10-20T05:08:20+00:00"+ "time": "2023-02-07T11:34:05+00:00"},{"name": "theseer/tokenizer",diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex 7e99bd644..1547e1c21 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -81,6 +81,9 @@ class HttpExecutor// http_errors disabled so we translate status into typed SDK exceptions).$options = ['http_errors' => false,+ // Per-request options override injected Guzzle client defaults, so the SDK's configured+ // timeout is enforced consistently on both default and caller-supplied clients.+ 'timeout' => $this->timeout,// Never auto-follow redirects: doing so would re-send the X-API-Key// header to the redirect target (potentially a different origin).'allow_redirects' => false,diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex b04070de9..9dcd1a2f0 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -25,6 +25,7 @@ from ..types import (SendBulkRequest,SendContactRequest,SendLocationRequest,+ SendAudioRequest,SendMediaRequest,SendTemplateRequest,SendTextRequest,@@ -51,7 +52,7 @@ class MessagesResource:def send_video(self, session_id: str, body: SendMediaRequest) -> MessageResponse:return self._send_media(session_id, "send-video", body)- def send_audio(self, session_id: str, body: SendMediaRequest) -> MessageResponse:+ def send_audio(self, session_id: str, body: SendAudioRequest) -> MessageResponse:return self._send_media(session_id, "send-audio", body)def send_document(self, session_id: str, body: SendMediaRequest) -> MessageResponse:diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex a015c6e44..ab39e1973 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -107,9 +107,22 @@ class SendMediaRequest(TypedDict, total=False):mimetype: strfilename: strcaption: str+++class SendAudioRequest(SendMediaRequest, total=False):ptt: bool # audio only: send as a WhatsApp voice note (PTT)+class BulkMediaRequest(TypedDict, total=False):+ """Nested bulk media; chatId lives on the parent and caption on content."""++ url: str+ base64: str+ mimetype: str+ filename: str+ ptt: bool++class SendLocationRequest(TypedDict, total=False):# chatId/latitude/longitude required; description/address optional.chatId: Jid@@ -269,10 +282,10 @@ class ReactionRecord(TypedDict, total=False):class BulkMessageContent(TypedDict, total=False):text: str- image: SendMediaRequest- video: SendMediaRequest- audio: SendMediaRequest- document: SendMediaRequest+ image: BulkMediaRequest+ video: BulkMediaRequest+ audio: BulkMediaRequest+ document: BulkMediaRequestcaption: strdiff --git a/src/common/throttler/redis-throttler.storage.spec.ts b/src/common/throttler/redis-throttler.storage.spec.tsindex 79ae7b3f1..ab6ad8bb5 100644--- a/src/common/throttler/redis-throttler.storage.spec.ts+++ b/src/common/throttler/redis-throttler.storage.spec.ts@@ -1,16 +1,14 @@import { RedisThrottlerStorage } from './redis-throttler.storage';import type { Redis } from 'ioredis';-type MockRedis = { incr: jest.Mock; pexpire: jest.Mock; pttl: jest.Mock };+type MockRedis = { eval: jest.Mock };const makeRedis = (opts: { hits: number; ttlMs: number }): MockRedis => ({- incr: jest.fn().mockResolvedValue(opts.hits),- pexpire: jest.fn().mockResolvedValue(1),- pttl: jest.fn().mockResolvedValue(opts.ttlMs),+ eval: jest.fn().mockResolvedValue([opts.hits, opts.ttlMs]),});describe('RedisThrottlerStorage', () => {- it('first hit (incr=1): sets the TTL once, reports totalHits + remaining time in seconds, not blocked', async () => {+ it('atomically increments, arms/repairs the TTL, and reports remaining seconds', async () => {const redis = makeRedis({ hits: 1, ttlMs: 1500 });const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment('1.2.3.4',@@ -19,15 +17,25 @@ describe('RedisThrottlerStorage', () => {60000,'short',);- expect(redis.incr).toHaveBeenCalledWith('openwa:throttle:short:1.2.3.4');- expect(redis.pexpire).toHaveBeenCalledWith('openwa:throttle:short:1.2.3.4', 1000);+ expect(redis.eval).toHaveBeenCalledWith(+ expect.stringContaining("redis.call('INCR', KEYS[1])"),+ 1,+ 'openwa:throttle:short:1.2.3.4',+ '1000',+ );expect(rec).toEqual({ totalHits: 1, timeToExpire: 2, isBlocked: false, timeToBlockExpire: 0 });});- it('subsequent hit (incr>1) does NOT re-set the TTL (inherits the window from the first hit)', async () => {- const redis = makeRedis({ hits: 3, ttlMs: 800 });- await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');- expect(redis.pexpire).not.toHaveBeenCalled();+ it('treats a repaired legacy TTL-less counter as a fresh first hit', async () => {+ const redis = makeRedis({ hits: 1, ttlMs: 1000 });+ const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');+ expect(redis.eval).toHaveBeenCalledWith(+ expect.stringContaining("redis.call('SET', KEYS[1], 1, 'PX'"),+ 1,+ expect.any(String),+ '1000',+ );+ expect(rec).toEqual({ totalHits: 1, timeToExpire: 1, isBlocked: false, timeToBlockExpire: 0 });});it('over the limit (incr>limit) is blocked with blockDuration in seconds', async () => {@@ -40,7 +48,7 @@ describe('RedisThrottlerStorage', () => {it('fails OPEN on a Redis error (returns a non-blocking record so the limiter never self-DoSes)', async () => {const redis = makeRedis({ hits: 1, ttlMs: 1000 });- redis.incr.mockRejectedValue(new Error('ECONNREFUSED'));+ redis.eval.mockRejectedValue(new Error('ECONNREFUSED'));const rec = await new RedisThrottlerStorage(redis as unknown as Redis).increment('k', 1000, 10, 60000, 'short');expect(rec).toEqual({ totalHits: 0, timeToExpire: 0, isBlocked: false, timeToBlockExpire: 0 });});diff --git a/src/common/throttler/redis-throttler.storage.ts b/src/common/throttler/redis-throttler.storage.tsindex 139330980..eec6072a8 100644--- a/src/common/throttler/redis-throttler.storage.ts+++ b/src/common/throttler/redis-throttler.storage.ts@@ -11,6 +11,24 @@ interface ThrottlerRecord {timeToBlockExpire: number;}+// Increment, arm (or repair) the fixed-window TTL, and read it in one Redis operation. Re-arming+// PTTL<0 also heals counters stranded by older non-atomic implementations.+const INCREMENT_WITH_TTL_LUA = `+local hits = redis.call('INCR', KEYS[1])+local ttl = redis.call('PTTL', KEYS[1])+if hits == 1 then+ redis.call('PEXPIRE', KEYS[1], ARGV[1])+ ttl = redis.call('PTTL', KEYS[1])+elseif ttl < 0 then+ -- A TTL-less key can only be legacy/corrupt state. Treat its accumulated count as void so an old+ -- stranded over-limit value cannot impose a fresh full-window block when it is repaired.+ redis.call('SET', KEYS[1], 1, 'PX', ARGV[1])+ hits = 1+ ttl = redis.call('PTTL', KEYS[1])+end+return {hits, ttl}+`;+/*** Redis-backed ThrottlerStorage for @nestjs/throttler v6 — persists hit counts to Redis so rate* limits aggregate across replicas (behind a load balancer) instead of being per-process.@@ -35,16 +53,14 @@ export class RedisThrottlerStorage implements ThrottlerStorage {): Promise<ThrottlerRecord> {const redisKey = `openwa:throttle:${throttlerName}:${key}`;try {- const hits = await this.redis.incr(redisKey);- if (hits === 1) {- // First hit in the window sets the TTL; subsequent hits inherit it (fixed window from first hit).- await this.redis.pexpire(redisKey, ttl);- }- const ttlMs = await this.redis.pttl(redisKey);+ const [hits, ttlMs] = (await this.redis.eval(INCREMENT_WITH_TTL_LUA, 1, redisKey, String(ttl))) as [+ number,+ number,+ ];const isBlocked = hits > limit;return {totalHits: hits,- timeToExpire: Math.ceil(ttlMs / 1000),+ timeToExpire: ttlMs > 0 ? Math.ceil(ttlMs / 1000) : 0,isBlocked,timeToBlockExpire: isBlocked ? Math.ceil(blockDuration / 1000) : 0,};diff --git a/src/config/app-validation.ts b/src/config/app-validation.tsnew file mode 100644index 000000000..276303e42--- /dev/null+++ b/src/config/app-validation.ts@@ -0,0 +1,16 @@+import { INestApplication, ValidationPipe } from '@nestjs/common';+import { isValidationErrorDetailEnabled } from './bootstrap-security';++/** Apply the HTTP prefix and DTO validation contract shared by production and e2e applications. */+export function applyGlobalValidation(app: INestApplication): void {+ app.setGlobalPrefix('api');+ app.useGlobalPipes(+ new ValidationPipe({+ whitelist: true,+ forbidNonWhitelisted: true,+ transform: true,+ transformOptions: { enableImplicitConversion: true },+ disableErrorMessages: !isValidationErrorDetailEnabled(process.env.VALIDATION_ERROR_DETAIL, process.env.NODE_ENV),+ }),+ );+}diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsindex ce7540450..a14f9ac3a 100644--- a/src/config/bootstrap-security.spec.ts+++ b/src/config/bootstrap-security.spec.ts@@ -176,10 +176,23 @@ describe('assertNoDefaultSecretsInProduction', () => {s3AccessKey: 'minioadmin',s3SecretKey: 'minioadmin',minioBuiltIn: 'true',+ s3Endpoint: 'http://minio:9000',}),).not.toThrow();});+ it('does not treat an unset S3 endpoint as the bundled MinIO endpoint', () => {+ expect(() =>+ assertNoDefaultSecretsInProduction({+ nodeEnv: 'production',+ storageType: 's3',+ s3AccessKey: 'minioadmin',+ s3SecretKey: 'minioadmin',+ minioBuiltIn: 'true',+ }),+ ).toThrow(/S3_ACCESS_KEY, S3_SECRET_KEY/);+ });+it('still refuses an EXTERNAL Postgres with a default password even when MinIO is built-in', () => {expect(() =>assertNoDefaultSecretsInProduction({diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex 14b743be0..03f606c52 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -128,11 +128,11 @@ export function isApiKeyPepperMissingInProduction(nodeEnv?: string, apiKeyPepperreturn nodeEnv === 'production' && !apiKeyPepper?.trim();}-/** A built-in S3 endpoint is the bundled MinIO (host `minio`) — or unset (the built-in default). An- * external endpoint (e.g. s3.amazonaws.com) is reachable, so its credentials are never exempted. */+/** A built-in S3 endpoint is the bundled MinIO (host `minio`). An unset endpoint means the standard+ * AWS regional endpoint, so it is external and its credentials must never be exempted. */function isInternalS3Endpoint(endpoint?: string): boolean {const e = endpoint?.trim();- if (!e) return true;+ if (!e) return false;try {return new URL(e).hostname === 'minio';} catch {diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 8292d477f..2b8d83b8d 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -131,11 +131,13 @@ export default () => ({// Webhook configurationwebhook: {timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),- maxRetries: parseInt(process.env.WEBHOOK_MAX_RETRIES || '3', 10),retryDelay: parseInt(process.env.WEBHOOK_RETRY_DELAY || '5000', 10),// Cap on how many matching webhooks are delivered CONCURRENTLY for one event. Without it, an event// matching N webhooks opens N outbound sockets at once (no per-event bound). Default 16.dispatchConcurrency: parseInt(process.env.WEBHOOK_DISPATCH_CONCURRENCY || '16', 10),+ // Bound parked inline deliveries as well as active sockets. Queue-full dispatches are recorded in+ // webhook_delivery_failures instead of retaining payload closures without limit.+ dispatchMaxQueued: parseInt(process.env.WEBHOOK_DISPATCH_MAX_QUEUED || '1000', 10),},// API configurationdiff --git a/src/config/dashboard-csp.spec.ts b/src/config/dashboard-csp.spec.tsnew file mode 100644index 000000000..d5203e937--- /dev/null+++ b/src/config/dashboard-csp.spec.ts@@ -0,0 +1,9 @@+import { DASHBOARD_CSP_NONCE_PLACEHOLDER, injectDashboardCspNonce } from './dashboard-csp';++describe('injectDashboardCspNonce', () => {+ it('keeps each dashboard document nonce isolated (multi-tab safe)', () => {+ const template = `<meta name="openwa-csp-nonce" content="${DASHBOARD_CSP_NONCE_PLACEHOLDER}">`;+ expect(injectDashboardCspNonce(template, 'tab-a')).toContain('content="tab-a"');+ expect(injectDashboardCspNonce(template, 'tab-b')).toContain('content="tab-b"');+ });+});diff --git a/src/config/dashboard-csp.ts b/src/config/dashboard-csp.tsnew file mode 100644index 000000000..5f5937e71--- /dev/null+++ b/src/config/dashboard-csp.ts@@ -0,0 +1,6 @@+export const DASHBOARD_CSP_NONCE_PLACEHOLDER = '__OPENWA_CSP_NONCE__';++/** Inject the response-specific CSP nonce into the bundled dashboard document. */+export function injectDashboardCspNonce(html: string, nonce: string): string {+ return html.replace(DASHBOARD_CSP_NONCE_PLACEHOLDER, nonce);+}diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex c17f11f09..064cdb1ac 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -50,6 +50,14 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['PUPPETEER_HEADLESS','SESSION_DATA_PATH','PUPPETEER_ARGS',+ // Rate-limit values are blank-forwarded by Compose so a host value can take precedence without an+ // empty forward masking the lower-priority loaded .env / data/.env.generated value.+ 'RATE_LIMIT_SHORT_TTL',+ 'RATE_LIMIT_SHORT_LIMIT',+ 'RATE_LIMIT_MEDIUM_TTL',+ 'RATE_LIMIT_MEDIUM_LIMIT',+ 'RATE_LIMIT_LONG_TTL',+ 'RATE_LIMIT_LONG_LIMIT',];export function clearBlankEnv(env: NodeJS.ProcessEnv, keys: string[]): void {diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex bc199dac6..ba6951eb2 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -87,9 +87,7 @@ describe('validateEnv', () => {expect(() => validateEnv({ RATE_LIMIT_LONG_LIMIT: '0' })).toThrow(/RATE_LIMIT_LONG_LIMIT/);expect(() => validateEnv({ WEBHOOK_TIMEOUT: '0' })).toThrow(/WEBHOOK_TIMEOUT/);// 0 stays valid where it has a real meaning: unlimited sessions, no webhook retries, a TTL.- expect(() =>- validateEnv({ MAX_CONCURRENT_SESSIONS: '0', WEBHOOK_MAX_RETRIES: '0', RATE_LIMIT_SHORT_TTL: '0' }),- ).not.toThrow();+ expect(() => validateEnv({ MAX_CONCURRENT_SESSIONS: '0', RATE_LIMIT_SHORT_TTL: '0' })).not.toThrow();// a positive value still passesexpect(() => validateEnv({ RATE_LIMIT_SHORT_LIMIT: '10', WEBHOOK_TIMEOUT: '10000' })).not.toThrow();});diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 2cab759af..1dffe48b0 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -118,7 +118,6 @@ export function validateEnv(config: EnvConfig): EnvConfig {'RATE_LIMIT_SHORT_TTL','RATE_LIMIT_MEDIUM_TTL','RATE_LIMIT_LONG_TTL',- 'WEBHOOK_MAX_RETRIES','WEBHOOK_RETRY_DELAY','DATABASE_POOL_SIZE','DATABASE_STATEMENT_TIMEOUT_MS',@@ -127,6 +126,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {'REDIS_CONNECT_TIMEOUT_MS','MAX_CONCURRENT_SESSIONS', // 0 = unlimited'INGRESS_INSTANCE_TTL',+ 'WEBHOOK_DISPATCH_MAX_QUEUED',]) {checkNonNegativeInt(key);}diff --git a/src/core/agent-tools/tools/group.tools.ts b/src/core/agent-tools/tools/group.tools.tsindex 702171a69..0ec9d9d58 100644--- a/src/core/agent-tools/tools/group.tools.ts+++ b/src/core/agent-tools/tools/group.tools.ts@@ -79,6 +79,7 @@ export function groupTools(group: GroupService): ToolDescriptor[] {name: 'GroupSetSubject',description: 'Change the group name/subject. Requires OPERATOR role.',tier: 'write',+ destructive: true,requiredRole: ApiKeyRole.OPERATOR,sessionScoped: true,inputSchema: z.object({@@ -95,6 +96,7 @@ export function groupTools(group: GroupService): ToolDescriptor[] {name: 'GroupSetDescription',description: 'Change the group description. Pass empty string to clear it. Requires OPERATOR role.',tier: 'write',+ destructive: true,requiredRole: ApiKeyRole.OPERATOR,sessionScoped: true,inputSchema: z.object({diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex a9d9f859d..6a6581ceb 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -552,7 +552,11 @@ describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () =>sandboxHosts: Map<string, { dispatchWebhook: jest.Mock }>;};internals.plugins.set('chatwoot-adapter', {- manifest: { id: 'chatwoot-adapter', sessionScoped: true },+ manifest: {+ id: 'chatwoot-adapter',+ sessionScoped: true,+ ingress: [{ route: 'chatwoot', signature: { scheme: 'none' } }],+ },config: { baseUrl: 'base', accountId: 1 },sessionConfig: { 'sess-1': { baseUrl: 'https://tenant1' } },});@@ -563,6 +567,7 @@ describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () =>pluginId: 'chatwoot-adapter',instanceId: 'acct1',route: 'chatwoot',+ method: 'PATCH',deliveryId: 'd1',sessionId: 'sess-1',payload: { headers: {}, query: {}, body: '', rawBody: '' },@@ -572,7 +577,11 @@ describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () =>expect(dispatchWebhook).toHaveBeenCalledTimes(1);// Session override (tenant1) merged over the base — this is what makes an instance multi-tenant.expect(dispatchWebhook).toHaveBeenCalledWith(- expect.objectContaining({ config: { baseUrl: 'https://tenant1', accountId: 1 } }),+ expect.objectContaining({+ config: { baseUrl: 'https://tenant1', accountId: 1 },+ method: 'PATCH',+ verified: false,+ }),);});});diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 1c644f9a0..fdb7bc7ee 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -624,6 +624,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// provisioning wrote) so the ingress handler reads it as ctx.config — this is what makes a minted// instance multi-tenant. Best-effort: an unresolved plugin just yields undefined (base config only).const plugin = this.plugins.get(d.pluginId);+ const route = plugin?.manifest.ingress?.find(candidate => candidate.route === d.route);+ // Reaching dispatch means every authenticating scheme already passed host verification. A route+ // explicitly configured with scheme:none is unauthenticated and must never be labelled verified.+ // Missing/hot-swapped route metadata fails closed.+ const verified = route ? route.signature.scheme !== 'none' : false;const instance = await this.getPluginInstanceService().resolve(d.pluginId, d.instanceId);const config = plugin? resolvePluginConfig(@@ -636,12 +641,12 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {const result = await host.dispatchWebhook({instanceId: d.instanceId,route: d.route,- method: 'POST',+ method: d.method ?? 'POST',headers: d.payload.headers,query: d.payload.query,body: d.payload.body,rawBody: d.payload.rawBody,- verified: true,+ verified,deliveryId: d.deliveryId,sessionId: d.sessionId,config,diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.tsindex 188d1779b..c0788a1b2 100644--- a/src/core/plugins/plugin-storage.service.spec.ts+++ b/src/core/plugins/plugin-storage.service.spec.ts@@ -91,17 +91,17 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>expect(await storage.list()).toContain('legacy');});- it('migrates a legacy plain-key file off on the next set (no stale shadow copy)', async () => {+ it('keeps a legacy plain-key file on set but reads the encoded value first', async () => {const pluginDataDir = path.join(dataDir, 'plugins', pluginId);const legacyFile = path.join(pluginDataDir, 'legacy.json');fs.writeFileSync(legacyFile, JSON.stringify({ old: true }));await storage.set('legacy', { fresh: true });- expect(fs.existsSync(legacyFile)).toBe(false); // stale legacy copy removed+ expect(fs.existsSync(legacyFile)).toBe(true); // never unlink outside the service-owned key-* namespaceexpect(await storage.get('legacy')).toEqual({ fresh: true });const jsonFiles = fs.readdirSync(pluginDataDir).filter(f => f.endsWith('.json'));- expect(jsonFiles).toHaveLength(1); // only the encoded file remains+ expect(jsonFiles).toHaveLength(2);});it('deletes a legacy plain-key file', async () => {@@ -114,6 +114,21 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>expect(await storage.get('legacy')).toBeNull();});+ it('never treats manifest.json or package.json as legacy storage files', async () => {+ const pluginDataDir = path.join(dataDir, 'plugins', pluginId);+ const manifestPath = path.join(pluginDataDir, 'manifest.json');+ const packagePath = path.join(pluginDataDir, 'package.json');+ fs.writeFileSync(manifestPath, JSON.stringify({ id: pluginId }));+ fs.writeFileSync(packagePath, JSON.stringify({ name: pluginId }));++ expect(await storage.get('manifest')).toBeNull();+ await storage.set('manifest', { pluginState: true });+ await storage.delete('manifest');++ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))).toEqual({ id: pluginId });+ expect(JSON.parse(fs.readFileSync(packagePath, 'utf8'))).toEqual({ name: pluginId });+ });+it('does not mangle a literal legacy filename that happens to start with "key-"', async () => {const pluginDataDir = path.join(dataDir, 'plugins', pluginId);// A pre-encoding plugin could have stored a key literally named "key-zzz" -> key-zzz.json.diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.tsindex ec10c5806..ea7a22b1d 100644--- a/src/core/plugins/plugin-storage.service.ts+++ b/src/core/plugins/plugin-storage.service.ts@@ -220,6 +220,9 @@ export class PluginStorageService {// but new writes always use the encoded filename above.const resolveLegacyKeyPath = (key: string): string | null => {if (!isSafeStorageKey(key)) return null;+ // These are package-owned files when package code and state share a directory. They must never+ // be treated as legacy plugin storage (or get/delete/set migration can read or remove code).+ if (key === 'manifest' || key === 'package') return null;const fileName = `${key}.json`;return isPathWithin(pluginDataDir, fileName) ? path.join(pluginDataDir, fileName) : null;};@@ -257,11 +260,8 @@ export class PluginStorageService {// pre-existed (writeFileSync mode only applies on create). Mirrors saveRegistry's hardening.atomicWriteFileSync(filePath, JSON.stringify(value, null, 2), { mode: 0o600 });fs.chmodSync(filePath, 0o600);- // Migrate off any pre-encoding legacy file for this key so a stale copy can't shadow reads/lists.- const legacyPath = resolveLegacyKeyPath(key);- if (legacyPath && legacyPath !== filePath && fs.existsSync(legacyPath)) {- fs.unlinkSync(legacyPath);- }+ // Keep any legacy file in place. Encoded-first reads and de-duplicated lists ensure it cannot+ // shadow this write, while avoiding an unlink outside the service-owned key-* namespace.return Promise.resolve();} catch (error) {logger.error(`Failed to write plugin data: ${pluginId}/${key}`, String(error));diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 366a286b7..a63aa621e 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -243,6 +243,8 @@ export interface PluginIngressRoute {mode: 'async' | 'sync-reply';signature: IngressSignatureSpec;challenge?: IngressChallengeSpec;+ /** Reserved/advisory compatibility field. Authenticity is currently verified by the host according+ * to `signature`; the worker does not perform an additional `self` verification pass. */verify: 'core' | 'self';maxBodyBytes: number;// Optional: where the provider's conversation id lives, so the host can compute a per-conversationdiff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.tsindex 9b3d0ab9c..673639735 100644--- a/src/core/plugins/sandbox/protocol.ts+++ b/src/core/plugins/sandbox/protocol.ts@@ -43,10 +43,11 @@ export type HostToWorkerMessage =| { kind: 'config-change'; config: Record<string, unknown> }// Ask the worker plugin to run its healthCheck(); it replies with health-result.| { kind: 'health-check'; id: number }- // Dispatch a verified inbound webhook to the worker for a route it subscribed to (webhook-subscribe).+ // Dispatch an inbound webhook to the worker for a route it subscribed to (webhook-subscribe).// `body`/`rawBody` are buffered host-side to a string, like PluginNetResponse.body. `verified`- // reflects the host's signature check (see PluginIngressRoute.verify); the worker still re-checks- // when `verify: 'self'`. The worker replies with webhook-result.+ // reflects whether the host authenticated the delivery via the route's signature scheme; it is+ // false for scheme:none. PluginIngressRoute.verify:'self' is reserved and does not trigger a second+ // worker-side verification pass. The worker replies with webhook-result.| {kind: 'webhook';id: number;diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex d3497d5ac..0c8c57301 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -708,9 +708,10 @@ describe('WhatsAppWebJsAdapter.forceDestroy (recover a wedged session, #351)', (expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);});- it('is a no-op when there is no client', async () => {+ it('records teardown intent even when startup has not assigned a client yet', async () => {const adapter = newAdapter();await expect(adapter.forceDestroy()).resolves.toBeUndefined();+ expect((adapter as unknown as { tearingDown: boolean }).tearingDown).toBe(true);});});@@ -2006,7 +2007,7 @@ describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the re// Time out BOTH callers' wall-clock deadline while the real download is still pending. With the old// coupling this freed the slot and admitted download2 (inFlight 2); the fix holds the slot.await jest.advanceTimersByTimeAsync(25);- expect(await r1).toBeUndefined(); // caller unblocked on the timeout race+ expect(await r1).toEqual(expect.objectContaining({ mimetype: 'image/png', omitted: true, sizeBytes: 100 }));expect(downloads.length).toBe(1); // download2 still not started — slot held by the pending real download1expect(maxInFlight).toBe(1);@@ -2018,7 +2019,7 @@ describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the re// Settle the rest so nothing dangles.await jest.advanceTimersByTimeAsync(25);- expect(await r2).toBeUndefined();+ expect(await r2).toEqual(expect.objectContaining({ mimetype: 'image/png', omitted: true, sizeBytes: 100 }));downloads[1].resolve({ mimetype: 'image/png', data: Buffer.from('b').toString('base64') });await jest.advanceTimersByTimeAsync(0);expect(maxInFlight).toBe(1);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 3938a3d0f..7ea1db1f2 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -347,7 +347,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginresolveBounded(null);});const media = await boundedReady;- if (!media) return undefined;+ if (!media) {+ return {+ mimetype: data?.mimetype ?? '',+ filename: data?.filename || undefined,+ omitted: true,+ sizeBytes: declared,+ };+ }const capped = capInboundMedia({mimetype: media.mimetype,filename: media.filename || undefined,@@ -404,6 +411,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Pin the WA-Web version when configured (fixes the 1.34.x "stuck at authenticating"// hang on some setups, #251). Opt-in: unset leaves whatsapp-web.js to auto-select.const versionPin = await resolveWebVersionPin();+ if (this.tearingDown) {+ this.setStatus(EngineStatus.DISCONNECTED);+ return;+ }if (versionPin) {this.logger.log(`Pinning WhatsApp Web version ${versionPin.webVersion}`);}@@ -441,6 +452,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin});this.setupEventHandlers();+ if (this.tearingDown) {+ this.client = null;+ this.setStatus(EngineStatus.DISCONNECTED);+ return;+ }await this.client.initialize();} catch (error) {this.setStatus(EngineStatus.FAILED);@@ -822,10 +838,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}private beginClientTeardown(): Client | null {+ this.tearingDown = true;const client = this.client;if (!client) return null;- this.tearingDown = true;this.clearReadyReconcile();if (this.status !== EngineStatus.DISCONNECTED) {this.setStatus(EngineStatus.DISCONNECTED);diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 965bc354c..e0ef3c209 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -21,12 +21,11 @@* `evidence` (present only when at least one adapter is `not-available`) cites the library symbol(s)* that were inspected, so an engineer can open the exact file and start wiring immediately.*- * This is a SNAPSHOT. `engine-parity.spec.ts` regenerates the supported/not-available *classification*- * from the live adapter method bodies (a method is "not-available" if it throws- * EngineNotSupportedError / ChannelMediaNotSupportedError) and fails on drift, so a parity change- * cannot land without deliberately updating this matrix (and docs/engine-capability-matrix.md). The- * `rootCause`/`evidence` fields are hand-curated, source-traced annotations; they are NOT regenerated- * by the spec and are updated by hand as adapters are wired or libraries change.+ * This is a SNAPSHOT. `engine-parity.spec.ts` enforces exact matrix-key↔interface-method correspondence+ * and the throw-invariants it can observe in live adapter method bodies. It does not read the operator+ * documentation and cannot classify non-throwing phantom stubs. The `status`, `rootCause`, and+ * `evidence` fields therefore remain hand-curated, source-traced annotations that must be reviewed as+ * adapters are wired or libraries change.** NOTE on phantom support: the drift gate's throw-heuristic cannot see adapter methods that silently* stub (return null/[] + a warn log) without throwing. The matrix BELOW is the source-of-truth: threediff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 5dfc0c516..4f054a1a8 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -106,7 +106,7 @@ export interface IncomingMessage {mimetype: string;filename?: string;data?: string; // base64; absent when the payload was omitted (see `omitted`)- /** True when the media exceeded the inbound size cap and the blob was dropped (envelope kept). */+ /** True when the media blob was dropped due to a size cap, timeout, or concurrency saturation. */omitted?: boolean;/** Decoded byte size of the media; always set when `omitted` is true. */sizeBytes?: number;diff --git a/src/main.ts b/src/main.tsindex 165477057..47100d1c7 100644--- a/src/main.ts+++ b/src/main.ts@@ -3,7 +3,7 @@// webhook Worker's @Processor connection) see the configured values rather than pre-dotenv defaults.import './config/load-env';import { NestFactory } from '@nestjs/core';-import { ValidationPipe, ShutdownSignal } from '@nestjs/common';+import { ShutdownSignal } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { SwaggerModule } from '@nestjs/swagger';import helmet from 'helmet';@@ -13,11 +13,12 @@ import { LoggerService, LogLevel, createLogger } from './common/services/logger.import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';+import { applyGlobalValidation } from './config/app-validation';import { requestContextMiddleware } from './common/middleware/request-context.middleware';+import { injectDashboardCspNonce } from './config/dashboard-csp';import {resolveCorsPolicy,isSwaggerEnabled,- isValidationErrorDetailEnabled,isUpgradeInsecureRequestsEnabled,isDashboardCspUpgradeTrapLikely,resolveBodyLimit,@@ -27,6 +28,9 @@ import {import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';import { AuthService } from './modules/auth/auth.service';import { Request, Response, NextFunction, json, urlencoded } from 'express';+import { randomBytes } from 'crypto';+import { readFileSync } from 'fs';+import { extname, join } from 'path';async function bootstrap() {// Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset/invalid → INFO.@@ -93,7 +97,17 @@ async function bootstrap() {},}),);- app.use(urlencoded({ extended: true, limit: bodyLimit }));+ app.use(+ urlencoded({+ extended: true,+ limit: bodyLimit,+ // Form-encoded webhook providers also sign the exact wire bytes. Use the same capture contract+ // as json(); other content types remain unsupported rather than installing a global catch-all.+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );// Assign a request id to every inbound request (X-Request-ID), echo it on the response, and run// the whole downstream chain inside its scope so every log line + audit row carries it.@@ -131,6 +145,13 @@ async function bootstrap() {});}+ // Give every response a CSP nonce. A bundled dashboard document receives its own value in a meta+ // element below; plugin config UIs copy it only onto inline scripts in their opaque sandboxed iframe.+ app.use((req: Request, res: Response, next: NextFunction) => {+ res.locals.cspNonce = randomBytes(18).toString('base64url');+ next();+ });+// Enhanced Security Headersapp.use(helmet({@@ -141,7 +162,7 @@ async function bootstrap() {// font files from fonts.gstatic.com). Now that NestJS serves the dashboard under this CSP,// allow those origins or the @import'd fonts are blocked and the UI falls back to system fonts.styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],- scriptSrc: ["'self'"],+ scriptSrc: ["'self'", (_req, res) => `'nonce-${(res as Response).locals.cspNonce as string}'`],// `blob:` is needed for the outgoing image-attachment preview, which the dashboard renders// from a URL.createObjectURL(file) blob before the message is sent (Chats.tsx).imgSrc: ["'self'", 'data:', 'blob:', 'https:'],@@ -174,6 +195,31 @@ async function bootstrap() {}),);+ // Serve SPA documents dynamically so the nonce embedded in this exact document matches its CSP+ // response header. A shared cookie is deliberately avoided: a second dashboard tab could overwrite+ // it and make the first tab's srcdoc scripts fail CSP. Assets and Nest-owned routes fall through.+ if (dashboardServingEnabled && dashboardBuildPresent) {+ const dashboardIndex = readFileSync(join(DASHBOARD_DIST, 'index.html'), 'utf8');+ app.use((req: Request, res: Response, next: NextFunction) => {+ const excluded =+ req.path.startsWith('/api/') ||+ req.path === '/api' ||+ req.path.startsWith('/socket.io/') ||+ req.path === '/socket.io' ||+ req.path.startsWith('/mcp/') ||+ req.path === '/mcp' ||+ req.path.startsWith('/assets/');+ const documentRequest =+ req.method === 'GET' &&+ !excluded &&+ ((req.headers.accept ?? '').includes('text/html') || extname(req.path) === '');+ if (!documentRequest) return next();++ res.setHeader('Cache-Control', 'no-store');+ res.type('html').send(injectDashboardCspNonce(dashboardIndex, res.locals.cspNonce as string));+ });+ }+// CORS Configuration (#221 hardening)const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);if (process.env.NODE_ENV === 'production' && corsPolicy.origins.length === 0 && !corsPolicy.allowAnyOrigin) {@@ -205,23 +251,8 @@ async function bootstrap() {maxAge: 86400, // 24 hours});- // Global prefix- app.setGlobalPrefix('api');-- // Enhanced Validation pipe with security options- app.useGlobalPipes(- new ValidationPipe({- whitelist: true, // Strip properties not in DTO- forbidNonWhitelisted: true, // Throw error on unknown properties- transform: true,- transformOptions: {- enableImplicitConversion: true,- },- // Hide field-level validation messages by default in production (so a 400 doesn't reflect the DTO- // shape back); opt in with VALIDATION_ERROR_DETAIL=true to debug an SDK/integration against prod.- disableErrorMessages: !isValidationErrorDetailEnabled(process.env.VALIDATION_ERROR_DETAIL, process.env.NODE_ENV),- }),- );+ // Shared production/e2e prefix and DTO validation contract.+ applyGlobalValidation(app);// Swagger documentation. ENABLE_SWAGGER wins; otherwise default on outside production, off in// production (the API schema is reconnaissance surface — production opts in with ENABLE_SWAGGER=true).@@ -303,4 +334,7 @@ async function bootstrap() {}}-void bootstrap();+bootstrap().catch((err: unknown) => {+ createLogger('Bootstrap').error('Fatal error during bootstrap', err instanceof Error ? err.stack : String(err));+ process.exitCode = 1;+});diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex d44118693..4a2084966 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -3,6 +3,7 @@ import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, Index } fromexport enum AuditAction {// API Key eventsAPI_KEY_CREATED = 'api_key_created',+ API_KEY_UPDATED = 'api_key_updated',API_KEY_USED = 'api_key_used',API_KEY_REVOKED = 'api_key_revoked',API_KEY_DELETED = 'api_key_deleted',diff --git a/src/modules/auth/auth.controller.spec.ts b/src/modules/auth/auth.controller.spec.tsindex 2036952d3..f3995f6e0 100644--- a/src/modules/auth/auth.controller.spec.ts+++ b/src/modules/auth/auth.controller.spec.ts@@ -13,7 +13,13 @@ describe('AuthController — API-key lifecycle audit logging', () => {const makeReq = (): Request =>({ method: 'POST', path: '/auth/api-keys', clientIp: '203.0.113.7' }) as unknown as Request;- let authService: { createApiKey: jest.Mock; findOne: jest.Mock; delete: jest.Mock; revoke: jest.Mock };+ let authService: {+ createApiKey: jest.Mock;+ findOne: jest.Mock;+ update: jest.Mock;+ delete: jest.Mock;+ revoke: jest.Mock;+ };let auditService: { logInfo: jest.Mock };let controller: AuthController;@@ -29,7 +35,15 @@ describe('AuthController — API-key lifecycle audit logging', () => {};authService = {createApiKey: jest.fn().mockResolvedValue({ apiKey: createdKey, rawKey: 'raw-secret' }),- findOne: jest.fn().mockResolvedValue({ id: 'k1', name: 'target-key' }),+ findOne: jest.fn().mockResolvedValue({+ id: 'k1',+ name: 'target-key',+ role: 'viewer',+ allowedIps: null,+ allowedSessions: null,+ expiresAt: null,+ }),+ update: jest.fn().mockResolvedValue({ ...createdKey, role: 'admin' }),delete: jest.fn().mockResolvedValue(undefined),revoke: jest.fn().mockResolvedValue({ ...createdKey, isActive: false }),};@@ -39,9 +53,22 @@ describe('AuthController — API-key lifecycle audit logging', () => {const lastContextFor = (action: AuditAction,- ): { apiKey?: ApiKey; ipAddress?: string; metadata?: { targetKeyId?: string } } | undefined => {+ ):+ | {+ apiKey?: ApiKey;+ ipAddress?: string;+ metadata?: { targetKeyId?: string; before?: { role?: string }; after?: { role?: string } };+ }+ | undefined => {const calls = auditService.logInfo.mock.calls as Array<- [AuditAction, { apiKey?: ApiKey; ipAddress?: string; metadata?: { targetKeyId?: string } }]+ [+ AuditAction,+ {+ apiKey?: ApiKey;+ ipAddress?: string;+ metadata?: { targetKeyId?: string; before?: { role?: string }; after?: { role?: string } };+ },+ ]>;return calls.find(c => c[0] === action)?.[1];};@@ -53,6 +80,7 @@ describe('AuthController — API-key lifecycle audit logging', () => {expect(ctx?.apiKey).toBe(actor);expect(ctx?.ipAddress).toBe('203.0.113.7');expect(ctx?.metadata?.targetKeyId).toBe('k1');+ expect(JSON.stringify(auditService.logInfo.mock.calls)).not.toContain('raw-secret');});it('logs API_KEY_DELETED on delete', async () => {@@ -61,6 +89,15 @@ describe('AuthController — API-key lifecycle audit logging', () => {expect(lastContextFor(AuditAction.API_KEY_DELETED)?.metadata?.targetKeyId).toBe('k1');});+ it('logs API_KEY_UPDATED with before/after authorization state', async () => {+ await controller.update('k1', { role: 'admin' } as never, makeReq(), actor);+ const ctx = lastContextFor(AuditAction.API_KEY_UPDATED);+ expect(ctx?.apiKey).toBe(actor);+ expect(ctx?.metadata?.targetKeyId).toBe('k1');+ expect(ctx?.metadata?.before?.role).toBe('viewer');+ expect(ctx?.metadata?.after?.role).toBe('admin');+ });+it('logs API_KEY_REVOKED on revoke', async () => {await controller.revoke('k1', makeReq(), actor);expect(lastContextFor(AuditAction.API_KEY_REVOKED)?.metadata?.targetKeyId).toBe('k1');diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.tsindex aba764ccd..414d50673 100644--- a/src/modules/auth/auth.controller.ts+++ b/src/modules/auth/auth.controller.ts@@ -118,8 +118,30 @@ export class AuthController {@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Update API key (admin only)' })@ApiResponse({ status: 200, description: 'The updated API key.', type: ApiKeyResponseDto })- async update(@Param('id') id: string, @Body() dto: UpdateApiKeyDto): Promise<ApiKeyResponseDto> {+ @ApiResponse({ status: 409, description: 'The change would remove the last usable admin key.' })+ async update(+ @Param('id') id: string,+ @Body() dto: UpdateApiKeyDto,+ @Req() req: Request,+ @CurrentApiKey() actor?: ApiKey,+ ): Promise<ApiKeyResponseDto> {+ const before = await this.authService.findOne(id);const k = await this.authService.update(id, dto);+ const authzSnapshot = (key: ApiKey) => ({+ role: key.role,+ allowedIps: key.allowedIps,+ allowedSessions: key.allowedSessions,+ expiresAt: key.expiresAt,+ });+ await this.auditService.logInfo(AuditAction.API_KEY_UPDATED, {+ ...this.auditContext(req, actor),+ metadata: {+ targetKeyId: k.id,+ targetKeyName: k.name,+ before: authzSnapshot(before),+ after: authzSnapshot(k),+ },+ });return {id: k.id,name: k.name,@@ -140,6 +162,7 @@ export class AuthController {@HttpCode(HttpStatus.NO_CONTENT)@ApiOperation({ summary: 'Delete API key (admin only)' })@ApiResponse({ status: 204, description: 'API key deleted' })+ @ApiResponse({ status: 409, description: 'The key is the last usable admin key.' })async delete(@Param('id') id: string, @Req() req: Request, @CurrentApiKey() actor?: ApiKey): Promise<void> {const target = await this.authService.findOne(id);await this.authService.delete(id);@@ -151,8 +174,10 @@ export class AuthController {@Post(':id/revoke')@RequireRole(ApiKeyRole.ADMIN)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Revoke API key (admin only)' })@ApiResponse({ status: 200, description: 'The revoked API key (isActive now false).', type: ApiKeyResponseDto })+ @ApiResponse({ status: 409, description: 'The key is the last usable admin key.' })async revoke(@Param('id') id: string,@Req() req: Request,diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 1a3a6ed9c..b710b418a 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -235,6 +235,18 @@ describe('AuthService', () => {expect(evictApiKey).not.toHaveBeenCalled();});++ it('rejects demoting or expiring the last usable admin', async () => {+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.count as jest.Mock).mockResolvedValue(0);++ await expect(service.update('uuid-1', { role: ApiKeyRole.OPERATOR })).rejects.toThrow(/last active admin/i);+ await expect(+ service.update('uuid-1', { expiresAt: new Date(Date.now() + 60_000).toISOString() }),+ ).rejects.toThrow(/last active admin/i);+ expect(repository.save).not.toHaveBeenCalled();+ });});// ── delete / revoke ───────────────────────────────────────────────@@ -271,6 +283,17 @@ describe('AuthService', () => {expect(repository.remove).toHaveBeenCalledWith(key);expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'deleted');});++ it('rejects deleting the last usable admin but allows it when another usable admin exists', async () => {+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.remove as jest.Mock).mockResolvedValue(key);+ (repository.count as jest.Mock).mockResolvedValueOnce(0).mockResolvedValueOnce(1);++ await expect(service.delete('uuid-1')).rejects.toThrow(/last active admin/i);+ await expect(service.delete('uuid-1')).resolves.toBeUndefined();+ expect(repository.remove).toHaveBeenCalledTimes(1);+ });});describe('revoke', () => {@@ -315,6 +338,16 @@ describe('AuthService', () => {expect(result.isActive).toBe(false); // revoke still succeeded});++ it('rejects revoking the last usable admin', async () => {+ const key = createMockApiKey({ role: ApiKeyRole.ADMIN, isActive: true });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.count as jest.Mock).mockResolvedValue(0);++ await expect(service.revoke('uuid-1')).rejects.toThrow(/last active admin/i);+ expect(repository.save).not.toHaveBeenCalled();+ expect(key.isActive).toBe(true);+ });});// ── validateApiKey ────────────────────────────────────────────────diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 51729de26..602dd10cc 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -1,7 +1,7 @@-import { Injectable, NotFoundException, UnauthorizedException, OnModuleInit } from '@nestjs/common';+import { ConflictException, Injectable, NotFoundException, UnauthorizedException, OnModuleInit } from '@nestjs/common';import { ModuleRef } from '@nestjs/core';import { InjectRepository } from '@nestjs/typeorm';-import { Repository } from 'typeorm';+import { IsNull, MoreThan, Not, Repository } from 'typeorm';import { randomBytes } from 'crypto';import { existsSync, readFileSync } from 'fs';import { join } from 'path';@@ -173,6 +173,13 @@ export class AuthService implements OnModuleInit {async update(id: string, dto: UpdateApiKeyDto): Promise<ApiKey> {const apiKey = await this.findOne(id);+ const removesOrSchedulesLastAdmin =+ (dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||+ (dto.expiresAt !== undefined && dto.expiresAt !== null);+ if (removesOrSchedulesLastAdmin) {+ await this.assertNotLastUsableAdmin(apiKey);+ }+// Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,// allowedIps, allowedSessions, or expiry can widen or restrict what an already-connected WebSocket// socket may see, so only those trigger eviction of live /events sockets — a benign rename must@@ -209,6 +216,7 @@ export class AuthService implements OnModuleInit {async delete(id: string): Promise<void> {const apiKey = await this.findOne(id);+ await this.assertNotLastUsableAdmin(apiKey);// Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.this.pendingUsage.delete(id);await this.apiKeyRepository.remove(apiKey);@@ -221,6 +229,7 @@ export class AuthService implements OnModuleInit {async revoke(id: string): Promise<ApiKey> {const apiKey = await this.findOne(id);+ await this.assertNotLastUsableAdmin(apiKey);// A revoked key fails validation before its next flush, so its accumulator would orphan —// drop it here.this.pendingUsage.delete(id);@@ -232,6 +241,23 @@ export class AuthService implements OnModuleInit {return saved;}+ private async assertNotLastUsableAdmin(target: ApiKey): Promise<void> {+ const now = new Date();+ const targetIsUsableAdmin =+ target.role === ApiKeyRole.ADMIN && target.isActive && (!target.expiresAt || target.expiresAt > now);+ if (!targetIsUsableAdmin) return;++ const otherUsableAdmins = await this.apiKeyRepository.count({+ where: [+ { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull() },+ { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: MoreThan(now) },+ ],+ });+ if (otherUsableAdmins === 0) {+ throw new ConflictException('Cannot remove the last active admin key');+ }+ }+/*** Disconnect every WebSocket socket authenticated with the given key id. Resolved lazily via* ModuleRef (not constructor injection) to avoid a static DI cycle between AuthModule anddiff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 926c8409d..7ebe1ea15 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -303,6 +303,49 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(() => gateway.evictApiKey('k1')).not.toThrow();});++ it('evicts a passive socket once its cached API key expires', async () => {+ authService.validateApiKey.mockResolvedValue({+ id: 'k1',+ name: 'k',+ allowedSessions: null,+ expiresAt: new Date('2026-01-01T00:00:00Z'),+ });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ (gateway as unknown as { sweepExpiredApiKeys: (now: number) => void }).sweepExpiredApiKeys(+ Date.parse('2026-01-01T00:00:01Z'),+ );++ expect(sock.disconnect).toHaveBeenCalledWith(true);+ expect(sock.emit).toHaveBeenCalledWith(+ 'message',+ expect.objectContaining({ code: 'UNAUTHORIZED', message: 'API key has expired' }),+ );+ });++ it('keeps sockets with no expiry or a future expiry', async () => {+ const noExpiry = makeSocket({ apiKey: 'a' });+ const future = { ...makeSocket({ apiKey: 'b' }), id: 'sock-2' };+ authService.validateApiKey+ .mockResolvedValueOnce({ id: 'k1', name: 'a', allowedSessions: null, expiresAt: null })+ .mockResolvedValueOnce({+ id: 'k2',+ name: 'b',+ allowedSessions: null,+ expiresAt: new Date('2026-01-02T00:00:00Z'),+ });+ await gateway.handleConnection(asSocket(noExpiry));+ await gateway.handleConnection(asSocket(future));++ (gateway as unknown as { sweepExpiredApiKeys: (now: number) => void }).sweepExpiredApiKeys(+ Date.parse('2026-01-01T00:00:00Z'),+ );++ expect(noExpiry.disconnect).not.toHaveBeenCalled();+ expect(future.disconnect).not.toHaveBeenCalled();+ });});});diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 8e7f61cc6..d43342e52 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -9,7 +9,7 @@ import {ConnectedSocket,} from '@nestjs/websockets';import { Server, Socket } from 'socket.io';-import { Logger } from '@nestjs/common';+import { Logger, OnModuleDestroy } from '@nestjs/common';import { AuthService } from '../auth/auth.service';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';@@ -68,12 +68,13 @@ export function isSessionSubscriptionAllowed(allowedSessions: string[] | null |}/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */-export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed';+export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed' | 'expired';const EVICTION_MESSAGES: Record<ApiKeyEvictionReason, string> = {revoked: 'API key has been revoked',deleted: 'API key has been deleted',authorization_changed: 'API key authorization changed; please reconnect',+ expired: 'API key has expired',};@WebSocketGateway({@@ -82,7 +83,7 @@ const EVICTION_MESSAGES: Record<ApiKeyEvictionReason, string> = {},namespace: '/events',})-export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {+export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, OnModuleDestroy {@WebSocketServer()server: Server;@@ -94,6 +95,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate* an already-subscribed socket keeps receiving events until it happens to disconnect).*/private readonly socketsByKeyId = new Map<string, Set<Socket>>();+ private expirySweepTimer?: ReturnType<typeof setInterval>;constructor(private readonly authService: AuthService,@@ -102,6 +104,31 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateafterInit() {this.logger.log('WebSocket Gateway initialized');+ this.expirySweepTimer = setInterval(() => {+ try {+ this.sweepExpiredApiKeys();+ } catch (error) {+ this.logger.error('Failed to sweep expired WebSocket API keys', error instanceof Error ? error.stack : error);+ }+ }, 60_000);+ this.expirySweepTimer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.expirySweepTimer) clearInterval(this.expirySweepTimer);+ this.expirySweepTimer = undefined;+ }++ private sweepExpiredApiKeys(now = Date.now()): void {+ for (const [keyId, sockets] of Array.from(this.socketsByKeyId.entries())) {+ const expired = Array.from(sockets).some(client => {+ const expiresAt = (client.data as { apiKey?: Pick<ApiKey, 'expiresAt'> } | undefined)?.apiKey?.expiresAt;+ if (!expiresAt) return false;+ const expiry = expiresAt instanceof Date ? expiresAt.getTime() : new Date(expiresAt).getTime();+ return Number.isFinite(expiry) && expiry <= now;+ });+ if (expired) this.evictApiKey(keyId, 'expired');+ }}/**diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 9f35bbd8c..86cf3f46b 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -23,6 +23,7 @@ jest.mock('fs', () => {chmodSync: jest.fn(),existsSync: jest.fn().mockReturnValue(false),readFileSync: jest.fn().mockReturnValue(''),+ createReadStream: jest.fn(() => jest.requireActual<typeof import('stream')>('stream').Readable.from([])),};});@@ -96,6 +97,25 @@ describe('InfraController.importStorage filePath validation (Vuln 3)', () => {);expect(storage.importFromStream).not.toHaveBeenCalled();});++ it('guards and opens the same cwd-resolved path returned by storage export', async () => {+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/export.tar.gz');+ (fs.createReadStream as jest.Mock).mockClear();+ const storage = {+ importFromStream: jest.fn().mockResolvedValue(3),+ getCurrentStorageType: jest.fn(() => 'local'),+ };+ try {+ const result = await buildController(storage).importStorage({ filePath: 'data/exports/export.tar.gz' });+ expect(fs.createReadStream).toHaveBeenCalledWith('/srv/openwa/data/exports/export.tar.gz');+ expect(storage.importFromStream).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ imported: true, count: 3, storageType: 'local' });+ } finally {+ cwdSpy.mockRestore();+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ }+ });});describe('InfraController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {@@ -525,6 +545,7 @@ describe('InfraController.importData round-trips export-data (no silent message/sessionId: 's1',waMessageId: 'WA1',chatId: '[email protected]',+ chatName: 'Support Chat',from: '[email protected]',to: '[email protected]',body: 'hello',@@ -569,6 +590,7 @@ describe('InfraController.importData round-trips export-data (no silent message/const m = await ds.getRepository(Message).findOneByOrFail({ id: 'm1' });expect(m.body).toBe('hello');expect(m.waMessageId).toBe('WA1');+ expect(m.chatName).toBe('Support Chat');expect(m.from).toBe('[email protected]');expect(m.to).toBe('[email protected]');expect(m.metadata).toEqual({ ack: 2 });diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 768068659..5b4f1b56a 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -1,5 +1,18 @@-import { Controller, Get, Put, Post, Body, BadRequestException, HttpException, Optional } from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';+import {+ Controller,+ Get,+ Put,+ Post,+ Body,+ BadRequestException,+ HttpException,+ HttpCode,+ HttpStatus,+ Optional,+} from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { Type } from 'class-transformer';+import { IsArray, IsBoolean, IsIn, IsNumber, IsOptional, IsString, ValidateNested } from 'class-validator';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';import { QUEUE_NAMES } from '../queue/queue-names';@@ -47,46 +60,203 @@ interface InfraStatus {};}-interface SaveConfigDto {- database?: {- type: 'sqlite' | 'postgres';- builtIn?: boolean;- host?: string;- port?: string;- username?: string;- password?: string;- database?: string;- schema?: string;- poolSize?: number;- sslEnabled?: boolean;- sslRejectUnauthorized?: boolean;- };- redis?: {- enabled?: boolean;- builtIn?: boolean;- host?: string;- port?: string;- password?: string;- };- queue?: {- enabled?: boolean;- };- storage?: {- type: 'local' | 's3';- builtIn?: boolean;- localPath?: string;- s3Bucket?: string;- s3Region?: string;- s3AccessKey?: string;- s3SecretKey?: string;- s3Endpoint?: string;- };- engine?: {- type?: string;- headless?: boolean;- sessionDataPath?: string;- browserArgs?: string;- };+class DatabaseConfigDto {+ @ApiProperty({ enum: ['sqlite', 'postgres'] })+ @IsIn(['sqlite', 'postgres'])+ type!: 'sqlite' | 'postgres';++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ host?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ port?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ username?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ password?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ database?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ schema?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsNumber()+ poolSize?: number;++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ sslEnabled?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ sslRejectUnauthorized?: boolean;+}++class RedisConfigDto {+ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ enabled?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ host?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ port?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ password?: string;+}++class QueueConfigDto {+ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ enabled?: boolean;+}++class StorageConfigDto {+ @ApiProperty({ enum: ['local', 's3'] })+ @IsIn(['local', 's3'])+ type!: 'local' | 's3';++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ builtIn?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ localPath?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Bucket?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Region?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3AccessKey?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3SecretKey?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ s3Endpoint?: string;+}++class EngineConfigDto {+ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ type?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsBoolean()+ headless?: boolean;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ sessionDataPath?: string;++ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ browserArgs?: string;+}++class SaveConfigDto {+ @ApiPropertyOptional({ type: () => DatabaseConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => DatabaseConfigDto)+ database?: DatabaseConfigDto;++ @ApiPropertyOptional({ type: () => RedisConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => RedisConfigDto)+ redis?: RedisConfigDto;++ @ApiPropertyOptional({ type: () => QueueConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => QueueConfigDto)+ queue?: QueueConfigDto;++ @ApiPropertyOptional({ type: () => StorageConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => StorageConfigDto)+ storage?: StorageConfigDto;++ @ApiPropertyOptional({ type: () => EngineConfigDto })+ @IsOptional()+ @ValidateNested()+ @Type(() => EngineConfigDto)+ engine?: EngineConfigDto;+}++class RestartDto {+ @ApiPropertyOptional({ type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ profiles?: string[];++ @ApiPropertyOptional({ type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ profilesToRemove?: string[];}// Database migration types for export/import@@ -129,6 +299,7 @@ interface MessageRow {sessionId: string;waMessageId: string | null;chatId: string;+ chatName: string | null;from: string;to: string;body: string | null;@@ -549,7 +720,7 @@ export class InfraController {@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Save infrastructure configuration to .env file' })@ApiResponse({ status: 200, description: 'Configuration saved' })- @ApiBody({ description: 'Configuration to save' })+ @ApiBody({ description: 'Configuration to save', type: SaveConfigDto })saveConfig(@Body() config: SaveConfigDto): { message: string; saved: boolean; envPath: string; profiles: string[] } {try {const profiles: string[] = [];@@ -760,10 +931,12 @@ export class InfraController {}}@Post('restart')+ @HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Request server restart with Docker orchestration' })@ApiResponse({ status: 200, description: 'Server will restart with new profiles' })- async requestRestart(@Body() body?: { profiles?: string[]; profilesToRemove?: string[] }): Promise<{+ @ApiBody({ required: false, type: RestartDto })+ async requestRestart(@Body() body?: RestartDto): Promise<{message: string;restarting: boolean;profiles: string[];@@ -1018,6 +1191,7 @@ export class InfraController {}@Post('import-data')+ @HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Import data to Data DB (replaces existing data)' })@ApiBody({@@ -1176,13 +1350,14 @@ export class InfraController {for (const msg of data.tables.messages) {try {await queryRunner.query(- `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,+ `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,[msg.id,msg.sessionId,msg.waMessageId ?? null,msg.chatId,+ msg.chatName ?? null,msg.from,msg.to,msg.body ?? null,@@ -1563,6 +1738,7 @@ export class InfraController {}@Post('storage/import')+ @HttpCode(HttpStatus.OK)@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Import storage files from tar.gz' })@ApiBody({ description: 'Path to tar.gz file to import' })@@ -1573,17 +1749,20 @@ export class InfraController {const { filePath } = body;// `filePath` is fully caller-controlled. Restrict it to the app's data- // directory so it cannot point at arbitrary files on the host.+ // directory so it cannot point at arbitrary files on the host. Resolve once against the+ // same cwd-relative base used by exportStorage, then use that exact path for both the guard+ // and the file sink.const dataDir = path.join(process.cwd(), 'data');- if (!filePath || !isPathWithin(dataDir, filePath)) {+ const resolved = path.resolve(process.cwd(), filePath || '');+ if (!filePath || !isPathWithin(dataDir, resolved)) {throw new BadRequestException('filePath must reference a file inside the data directory');}- if (!fs.existsSync(filePath)) {+ if (!fs.existsSync(resolved)) {throw new BadRequestException(`File not found: ${filePath}`);}- const readStream = fs.createReadStream(filePath);+ const readStream = fs.createReadStream(resolved);const count = await this.storageService.importFromStream(readStream);return {diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsindex a7427e130..328345ce6 100644--- a/src/modules/integration/ingress-enqueue.service.ts+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -50,7 +50,12 @@ export function buildIngressDeadLetterRow(data: IngressJobData, error?: string):deliveryId: data.deliveryId,attempts: 1,lastError: error ?? 'inline ingress dispatch failed',- payload: { route: data.route, providerConversationId: data.providerConversationId, ingress: data.payload },+ payload: {+ route: data.route,+ method: data.method,+ providerConversationId: data.providerConversationId,+ ingress: data.payload,+ },redriven: false,};}diff --git a/src/modules/integration/ingress.service.spec.ts b/src/modules/integration/ingress.service.spec.tsindex a80edadf1..69cd48b35 100644--- a/src/modules/integration/ingress.service.spec.ts+++ b/src/modules/integration/ingress.service.spec.ts@@ -1,5 +1,6 @@import { IngressService, extractConversationId } from './ingress.service';import { EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import { createHmac } from 'node:crypto';function deps(overrides: Record<string, unknown> = {}) {return {@@ -45,10 +46,54 @@ describe('IngressService.handle', () => {const svc = new IngressService(d);const res = await svc.handle(req);expect(d.events.recordOrSkip).toHaveBeenCalled();- expect(d.enqueue).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'd1' }), 'd1');+ expect(d.enqueue).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'd1', method: 'POST' }), 'd1');expect(res.status).toBe(202);});+ it('uses the signed webhook-id as the default Standard Webhooks dedup key', async () => {+ const rawKey = Buffer.from('0123456789abcdef0123456789abcdef', 'hex');+ const secret = `v1,whsec_${rawKey.toString('base64')}`;+ const body = '{}';+ const timestamp = '1000';+ const webhookId = 'msg_signed_1';+ const signature = 'v1,' + createHmac('sha256', rawKey).update(`${webhookId}.${timestamp}.${body}`).digest('base64');+ const d = deps({+ instances: {+ resolve: jest.fn().mockResolvedValue({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ secret,+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ }),+ },+ manifestRoute: jest.fn().mockReturnValue({+ route: 'chatwoot',+ mode: 'async',+ verify: 'core',+ maxBodyBytes: 1024,+ signature: { scheme: 'standard-webhooks' },+ }),+ now: () => 1_000_000,+ });++ const res = await new IngressService(d).handle({+ ...req,+ rawBody: body,+ headers: {+ 'webhook-id': webhookId,+ 'webhook-timestamp': timestamp,+ 'webhook-signature': signature,+ },+ });++ expect(res.status).toBe(202);+ expect(d.events.recordOrSkip).toHaveBeenCalledWith(expect.objectContaining({ providerDeliveryId: webhookId }));+ expect(d.enqueue).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: webhookId }), webhookId);+ });+it('short-circuits a duplicate delivery with 200 and no enqueue', async () => {const d = deps({ events: { recordOrSkip: jest.fn().mockResolvedValue(false) } });const svc = new IngressService(d);diff --git a/src/modules/integration/ingress.service.ts b/src/modules/integration/ingress.service.tsindex 521b8fca7..f8706e4e6 100644--- a/src/modules/integration/ingress.service.ts+++ b/src/modules/integration/ingress.service.ts@@ -111,7 +111,10 @@ export class IngressService {return { status: preflight.status, body: preflight.body };}- const dedupHeader = (route.dedupHeader ?? route.signature.dedupHeader ?? 'x-delivery').toLowerCase();+ // Standard Webhooks signs and requires webhook-id, so it is the stable, authenticated retry id.+ // Other schemes retain the existing x-delivery/body-hash behavior for compatibility.+ const defaultDedupHeader = route.signature.scheme === 'standard-webhooks' ? 'webhook-id' : 'x-delivery';+ const dedupHeader = (route.dedupHeader ?? route.signature.dedupHeader ?? defaultDedupHeader).toLowerCase();const deliveryId = req.headers[dedupHeader] ?? deriveDeliveryId(req);const payload = { headers: req.headers, query: req.query, body: req.rawBody, rawBody: req.rawBody };const isNew = await this.deps.events.recordOrSkip({@@ -131,6 +134,7 @@ export class IngressService {pluginId: req.pluginId,instanceId: req.instanceId,route: req.route,+ method: req.method,deliveryId,sessionId: instance.sessionScope ?? undefined,providerConversationId,diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.tsindex f818a33c8..ef51b0754 100644--- a/src/modules/integration/redrive.controller.ts+++ b/src/modules/integration/redrive.controller.ts@@ -16,12 +16,12 @@ export class RedriveController {@Post(':pluginId/:instanceId/redrive')@ApiResponse({status: 201,- description: 'Dead-lettered ingress deliveries for the instance re-dispatched. Returns the count redriven.',+ description: 'One bounded batch of dead-lettered ingress deliveries re-dispatched, with remaining depth.',})redriveInstance(@Param('pluginId') pluginId: string,@Param('instanceId') instanceId: string,- ): Promise<{ redriven: number }> {+ ): Promise<{ redriven: number; remaining: number; batchSize: number }> {return this.redrive.redriveInstance(pluginId, instanceId);}}diff --git a/src/modules/integration/redrive.service.spec.ts b/src/modules/integration/redrive.service.spec.tsindex 9f5d0ef15..64ffe7745 100644--- a/src/modules/integration/redrive.service.spec.ts+++ b/src/modules/integration/redrive.service.spec.ts@@ -8,7 +8,7 @@ describe('RedriveService', () => {let ingressEnqueue: jest.Mocked<Partial<IngressEnqueueService>>;beforeEach(() => {- repo = { find: jest.fn(), update: jest.fn().mockResolvedValue(undefined) };+ repo = { find: jest.fn(), update: jest.fn().mockResolvedValue(undefined), count: jest.fn().mockResolvedValue(0) };ingressEnqueue = { enqueue: jest.fn().mockResolvedValue({ outcome: 'queued' }) };});@@ -49,6 +49,7 @@ describe('RedriveService', () => {const res = await svc.redriveInstance('p', 'i');expect(res.redriven).toBe(2);+ expect(res).toEqual({ redriven: 2, remaining: 0, batchSize: 100 });expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(2);expect(ingressEnqueue.enqueue).toHaveBeenNthCalledWith(1,@@ -56,6 +57,7 @@ describe('RedriveService', () => {pluginId: 'p',instanceId: 'i',route: 'chatwoot',+ method: 'POST',deliveryId: 'd1',sessionId: 's',providerConversationId: 'conv-1',@@ -90,7 +92,7 @@ describe('RedriveService', () => {expect(res.redriven).toBe(0);expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(1);- expect(repo.update).not.toHaveBeenCalled();+ expect(repo.update).toHaveBeenCalledWith({ id: 'f9' }, { attempts: 1, lastError: 'redrive dispatch failed' });});it('queries only non-redriven inbound rows for the instance and returns 0 when none are found', async () => {@@ -101,6 +103,8 @@ describe('RedriveService', () => {expect(repo.find).toHaveBeenCalledWith({where: { pluginId: 'p', instanceId: 'i', direction: 'inbound', redriven: false },+ order: { attempts: 'ASC', createdAt: 'ASC' },+ take: 100,});expect(res.redriven).toBe(0);expect(ingressEnqueue.enqueue).not.toHaveBeenCalled();diff --git a/src/modules/integration/redrive.service.ts b/src/modules/integration/redrive.service.tsindex 911166732..ab0f0decd 100644--- a/src/modules/integration/redrive.service.ts+++ b/src/modules/integration/redrive.service.ts@@ -4,36 +4,60 @@ import { Repository } from 'typeorm';import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { IngressEnqueueService } from './ingress-enqueue.service';import { IngressJobData } from '../queue/processors/ingress.processor';+import { KeyedAsyncLock } from './ordering-lock';++const REDRIVE_BATCH_SIZE = 100;// The ingress processor persists the full ingress payload on the DLQ row as// { route, providerConversationId?, ingress: <headers/query/body/rawBody> }, so redrive is// self-contained: it reads stored.ingress back out and re-enqueues without re-reading ingress_events.interface StoredDlqPayload {route?: string;+ method?: string;providerConversationId?: string;ingress?: IngressJobData['payload'];}@Injectable()export class RedriveService {+ private readonly lock = new KeyedAsyncLock();+constructor(@InjectRepository(IntegrationDeliveryFailure, 'data') private readonly repo: Repository<IntegrationDeliveryFailure>,private readonly ingressEnqueue: IngressEnqueueService,) {}- async redriveInstance(pluginId: string, instanceId: string): Promise<{ redriven: number }> {- const rows = await this.repo.find({ where: { pluginId, instanceId, direction: 'inbound', redriven: false } });+ redriveInstance(+ pluginId: string,+ instanceId: string,+ ): Promise<{ redriven: number; remaining: number; batchSize: number }> {+ return this.lock.run(`redrive:${pluginId}:${instanceId}`, () => this.redriveBatch(pluginId, instanceId));+ }++ private async redriveBatch(+ pluginId: string,+ instanceId: string,+ ): Promise<{ redriven: number; remaining: number; batchSize: number }> {+ const where = { pluginId, instanceId, direction: 'inbound' as const, redriven: false };+ const rows = await this.repo.find({+ where,+ // Failed replays increment attempts and move behind never-retried rows, preventing one permanent+ // failure from livelocking the bounded window while keeping it redrivable.+ order: { attempts: 'ASC', createdAt: 'ASC' },+ take: REDRIVE_BATCH_SIZE,+ });let redriven = 0;for (const row of rows) {const stored = (row.payload ?? {}) as StoredDlqPayload;// Re-mint a jobId so BullMQ accepts the replay even if the original jobId lingers.const jobId = `redrive:${row.id}`;- const { outcome } = await this.ingressEnqueue.enqueue(+ const { outcome, error } = await this.ingressEnqueue.enqueue({pluginId,instanceId,route: stored.route ?? '',+ method: stored.method ?? 'POST',deliveryId: row.deliveryId ?? row.id,sessionId: row.sessionId ?? undefined,providerConversationId: stored.providerConversationId,@@ -47,8 +71,14 @@ export class RedriveService {if (outcome !== 'failed') {await this.repo.update({ id: row.id }, { redriven: true });redriven++;+ } else {+ await this.repo.update(+ { id: row.id },+ { attempts: Math.max(0, row.attempts ?? 0) + 1, lastError: error ?? 'redrive dispatch failed' },+ );}}- return { redriven };+ const remaining = await this.repo.count({ where });+ return { redriven, remaining, batchSize: REDRIVE_BATCH_SIZE };}}diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex 91580e151..ecc3548e6 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -1,4 +1,4 @@-import { Controller, Get, Post, Delete, Param, Body } from '@nestjs/common';+import { Controller, Get, Post, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';import { LabelService } from './label.service';import { AddLabelDto } from './dto/add-label.dto';@@ -50,6 +50,7 @@ export class LabelController {@Post('chat/:chatId')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Add a label to a chat' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'chatId', description: 'Chat ID' })diff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.tsindex dcece8b53..4cc9d18bb 100644--- a/src/modules/mcp/mcp-rate-limit.spec.ts+++ b/src/modules/mcp/mcp-rate-limit.spec.ts@@ -105,8 +105,7 @@ describe('KeyRateLimiter', () => {expect(() => rl.check('b')).not.toThrow();});- // FIX 3(a): expired buckets must be pruned so the Map does not grow unboundedly- it('prunes empty buckets: Map is empty after all windows expire', () => {+ it('drops stale timestamps within a bucket when that key is checked again', () => {let now = 0;const rl = new KeyRateLimiter(5, 1000, () => now);@@ -140,9 +139,32 @@ describe('KeyRateLimiter', () => {// Access the private field via casting to verify the Map state.const map = (rl as unknown as { hits: Map<string, number[]> }).hits;+ expect(map.size).toBe(1000);+// Every bucket must have exactly 1 timestamp (the last fresh hit).for (const [, timestamps] of map) {expect(timestamps).toHaveLength(1);}});++ it('caps distinct keys with LRU eviction', () => {+ const rl = new KeyRateLimiter(5, 1000, () => 0, 3);+ rl.check('a');+ rl.check('b');+ rl.check('c');+ rl.check('a'); // touch a; b is now least recently used+ rl.check('d');++ const map = (rl as unknown as { hits: Map<string, number[]> }).hits;+ expect([...map.keys()]).toEqual(['c', 'a', 'd']);+ });++ it('touches a throttled key so eviction cannot reset an active abuser', () => {+ const rl = new KeyRateLimiter(1, 1000, () => 0, 2);+ rl.check('abuser');+ rl.check('other');+ expect(() => rl.check('abuser')).toThrow(/rate limit/i);+ rl.check('new');+ expect(() => rl.check('abuser')).toThrow(/rate limit/i);+ });});diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.tsindex 521aa4502..537141ff3 100644--- a/src/modules/mcp/mcp-rate-limit.ts+++ b/src/modules/mcp/mcp-rate-limit.ts@@ -5,6 +5,7 @@ const DEFAULT_WINDOW_MS = 60_000;// Pre-auth per-IP budget: more generous than the per-key one so a legitimate multi-key host behind one// IP (e.g. a shared proxy) isn't starved, while still bounding an unauthenticated key-probing flood.const DEFAULT_IP_MAX = 120;+const DEFAULT_MAX_KEYS = 50_000;const parsePositiveInt = (raw: string | undefined, fallback: number): number => {if (!raw || raw.trim() === '') return fallback;@@ -40,7 +41,8 @@ export function readIpRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { m* Per-API-key sliding window rate limiter.* The inherited IP-keyed throttler collapses all MCP calls into one 127.0.0.1 bucket,* so MCP needs its own per-key limiter.- * In-memory per-process; move to Redis for multi-instance deployments.+ * In-memory per-process; move to Redis for multi-instance deployments. The key map is capped with+ * approximate LRU eviction so a distinct-key flood cannot grow process memory without limit.*/export class KeyRateLimiter {private readonly hits = new Map<string, number[]>();@@ -48,19 +50,27 @@ export class KeyRateLimiter {private readonly max = 60,private readonly windowMs = 60_000,private readonly now: () => number = () => Date.now(),+ private readonly maxKeys = DEFAULT_MAX_KEYS,) {}check(key: string): void {const t = this.now();const recent = (this.hits.get(key) ?? []).filter(ts => t - ts < this.windowMs);- if (recent.length === 0) {- // All prior hits have expired — prune the bucket rather than accumulating stale entries.- this.hits.delete(key);+ const throttled = recent.length >= this.max;+ if (!throttled) recent.push(t);++ // Touch on every check, including throttled checks, so an active abuser cannot drift to the LRU+ // head, be evicted, and receive a fresh budget during a distinct-key flood.+ this.hits.delete(key);+ this.hits.set(key, recent);+ while (this.hits.size > Math.max(1, this.maxKeys)) {+ const oldest = this.hits.keys().next().value as string | undefined;+ if (oldest === undefined) break;+ this.hits.delete(oldest);}- if (recent.length >= this.max) {++ if (throttled) {throw new HttpException('MCP rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);}- recent.push(t);- this.hits.set(key, recent);}}diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex 1169e0b98..aa5efc372 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -238,7 +238,8 @@ export function mountMcpServer(};const adapter = httpAdapter as unknown as { post: (path: string, ...handlers: RequestHandler[]) => unknown };- // ipThrottle runs BEFORE express.json()/handler so an unauthenticated flood is rejected before any body- // parsing or DB lookup.+ // The route throttle gates the auth DB lookup and per-request MCP server/transport construction. The+ // process-wide capped json() in main.ts runs first for all routes; this route-level parser is a+ // defensive fallback and no-ops once the global parser has consumed the body.adapter.post(basePath, createIpThrottle(ipRateLimiter), express.json(), handler);}diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex a2e43dc36..85ba8a8f1 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -277,18 +277,26 @@ describe('BulkMessageService.processBatch', () => {});it('strips base64 media payloads from the stored batch once it completes (footprint)', async () => {+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });const batch = makeBatch(1);batch.messages = [{chatId: '[email protected]',type: 'image',- content: { image: { base64: 'QkFTRTY0SU1BR0U=', mimetype: 'image/png', filename: 'p.png' } },+ content: {+ image: { base64: 'data:image/png;base64,QkFTRTY0SU1BR0U=', mimetype: 'image/png', filename: 'p.png' },+ },},];repo.findOne.mockResolvedValue(batch);await runProcessBatch();+ expect(engine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'QkFTRTY0SU1BR0U=' }),+ );+// A completed batch is terminal (never resumed), so the persisted message_batches.messages must not// retain the (often multi-MB) base64 — only the descriptive fields are kept.const savedBatch = (repo.save.mock.calls as [MessageBatch][]).at(-1)![0];@@ -297,6 +305,21 @@ describe('BulkMessageService.processBatch', () => {expect(img?.mimetype).toBe('image/png');});+ it('rejects an empty base64 data URI before persisting or dispatching the batch', async () => {+ const dto = {+ messages: [+ {+ chatId: '[email protected]',+ type: 'image' as const,+ content: { image: { base64: 'data:image/png;base64,', mimetype: 'image/png' } },+ },+ ],+ };++ await expect(service.createBatch('s1', dto)).rejects.toThrow('Either url or base64');+ expect(repo.save).not.toHaveBeenCalled();+ });+it('persists the media filename from the chosen media type (image), not just from document', async () => {engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });const batch = makeBatch(1);@@ -414,6 +437,53 @@ describe('BulkMessageService.createBatch base64 media cap', () => {}});+ it('reserves the cap before awaiting persistence so concurrent creates cannot overshoot it', async () => {+ const previous = process.env.BULK_MAX_CONCURRENT_BATCHES;+ process.env.BULK_MAX_CONCURRENT_BATCHES = '1';+ let releaseSave!: (batch: MessageBatch) => void;+ let markSaveStarted!: () => void;+ const saveStarted = new Promise<void>(resolve => {+ markSaveStarted = resolve;+ });+ const pendingSave = new Promise<MessageBatch>(resolve => {+ releaseSave = resolve;+ });+ let persistedBatch!: MessageBatch;+ repo.save.mockImplementationOnce((batch: MessageBatch) => {+ persistedBatch = batch;+ markSaveStarted();+ return pendingSave;+ });+ const dto = {+ messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: { body: 'hi' } } }],+ } as unknown as SendBulkMessageDto;++ try {+ const first = service.createBatch('s1', dto);+ await saveStarted;++ await expect(service.createBatch('s1', dto)).rejects.toThrow(/too many bulk batches/i);+ expect(repo.save).toHaveBeenCalledTimes(1);++ releaseSave(persistedBatch);+ await expect(first).resolves.toBe(persistedBatch);+ } finally {+ if (previous === undefined) delete process.env.BULK_MAX_CONCURRENT_BATCHES;+ else process.env.BULK_MAX_CONCURRENT_BATCHES = previous;+ }+ });++ it('releases the cap reservation when persistence fails', async () => {+ repo.save.mockRejectedValueOnce(new Error('database unavailable'));+ const dto = {+ messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: { body: 'hi' } } }],+ } as unknown as SendBulkMessageDto;++ await expect(service.createBatch('s1', dto)).rejects.toThrow('database unavailable');++ expect((service as unknown as { inFlightBatches: number }).inFlightBatches).toBe(0);+ });+it('scopes the batchId uniqueness check to the session (no cross-session collision/oracle)', async () => {// Simulate a DB where batchId 'dup' exists only under session 's1'.repo.findOne.mockImplementation((opts: { where: { batchId?: string; sessionId?: string } }) => {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex eb11c8251..32845eec0 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -14,7 +14,7 @@ import { MessageStatus } from './entities/message.entity';import { SessionService } from '../session/session.service';import { MessageService } from './message.service';import { HookManager } from '../../core/hooks';-import { assertBase64WithinMediaCap } from './media-cap.util';+import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { renderTemplate } from '../../common/utils/template-render';import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';@@ -95,6 +95,7 @@ export class BulkMessageService implements OnApplicationBootstrap {const orphaned = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING } });for (const batch of orphaned) {batch.status = BatchStatus.FAILED;+ this.stripBatchMediaPayloads(batch.messages);await this.batchRepository.save(batch);}if (orphaned.length > 0) {@@ -115,10 +116,13 @@ export class BulkMessageService implements OnApplicationBootstrap {// its base64 payloads) is persisted into the batch row. Mirrors the single-send cap in// MessageService.buildMediaInput.for (const { content } of dto.messages) {- assertBase64WithinMediaCap(content?.image?.base64);- assertBase64WithinMediaCap(content?.video?.base64);- assertBase64WithinMediaCap(content?.audio?.base64);- assertBase64WithinMediaCap(content?.document?.base64);+ for (const media of [content?.image, content?.video, content?.audio, content?.document]) {+ const base64 = stripBase64DataUri(media?.base64);+ if (media?.base64 !== undefined && !base64 && !media.url) {+ throw new BadRequestException('Either url or base64 must be provided for bulk media');+ }+ assertBase64WithinMediaCap(base64);+ }}const batchId = dto.batchId || `batch_${randomUUID().split('-')[0]}`;@@ -137,7 +141,6 @@ export class BulkMessageService implements OnApplicationBootstrap {if (maxConcurrentBatches > 0 && this.inFlightBatches >= maxConcurrentBatches) {throw new BadRequestException(`Too many bulk batches in progress (max ${maxConcurrentBatches}); retry shortly`);}-const options = {delayBetweenMessages: dto.options?.delayBetweenMessages ?? 3000,randomizeDelay: dto.options?.randomizeDelay ?? true,@@ -163,11 +166,19 @@ export class BulkMessageService implements OnApplicationBootstrap {currentIndex: 0,});- await this.batchRepository.save(batch);+ // Reserve synchronously in the same turn as the cap check. There is deliberately no await between+ // them, so a burst cannot all observe the same stale count and overshoot the ceiling.+ this.inFlightBatches++;+ try {+ await this.batchRepository.save(batch);+ } catch (error) {+ this.inFlightBatches--;+ throw error;+ }this.logger.log(`Created batch ${batchId} with ${dto.messages.length} messages`);// Start processing asynchronously- this.processBatch(batch.id).catch(err => {+ this.processBatch(batch.id, true).catch(err => {this.logger.error(`Batch ${batchId} processing error: ${String(err)}`);});@@ -207,6 +218,7 @@ export class BulkMessageService implements OnApplicationBootstrap {batch.progress.cancelled = batch.progress.pending;batch.progress.pending = 0;batch.completedAt = new Date();+ this.stripBatchMediaPayloads(batch.messages);await this.batchRepository.save(batch);this.logger.log(`Cancelled batch ${batchId}`);@@ -214,19 +226,18 @@ export class BulkMessageService implements OnApplicationBootstrap {return batch;}- private async processBatch(batchDbId: string): Promise<void> {- const batch = await this.batchRepository.findOne({ where: { id: batchDbId } });- if (!batch) return;-- this.processingBatches.set(batch.id, true);+ private async processBatch(batchDbId: string, reserved = false): Promise<void> {+ let batch: MessageBatch | null = null;// Always release the in-flight marker on every exit path (engine-not-found early return, a thrown// save/send, or normal completion) — otherwise the map leaks an entry per such batch.try {- this.inFlightBatches++;+ batch = await this.batchRepository.findOne({ where: { id: batchDbId } });+ if (!batch) return;+ this.processingBatches.set(batch.id, true);await this.executeBatch(batch);} finally {- this.inFlightBatches--;- this.processingBatches.delete(batch.id);+ if (reserved) this.inFlightBatches--;+ if (batch) this.processingBatches.delete(batch.id);}}@@ -240,6 +251,7 @@ export class BulkMessageService implements OnApplicationBootstrap {if (!engine) {batch.status = BatchStatus.FAILED;batch.completedAt = new Date();+ this.stripBatchMediaPayloads(batch.messages);await this.batchRepository.save(batch);return;}@@ -390,7 +402,7 @@ export class BulkMessageService implements OnApplicationBootstrap {* weight; the descriptive fields (mimetype/filename/caption/url) are kept.*/private stripBatchMediaPayloads(messages: MessageBatch['messages']): void {- for (const m of messages) {+ for (const m of messages ?? []) {for (const key of ['image', 'video', 'audio', 'document']) {const media = m.content[key] as { base64?: unknown } | undefined;if (media && typeof media === 'object' && 'base64' in media) {@@ -455,7 +467,7 @@ export class BulkMessageService implements OnApplicationBootstrap {? {media: {mimetype: media.mimetype,- data: media.url ?? media.base64,+ data: stripBase64DataUri(media.base64) || media.url,filename: media.filename,},}@@ -478,25 +490,25 @@ export class BulkMessageService implements OnApplicationBootstrap {case 'image':return engine.sendImageMessage(chatId, {mimetype: content.image?.mimetype || 'image/jpeg',- data: content.image?.url || content.image?.base64 || '',+ data: stripBase64DataUri(content.image?.base64) || content.image?.url || '',caption: content.caption,});case 'video':return engine.sendVideoMessage(chatId, {mimetype: content.video?.mimetype || 'video/mp4',- data: content.video?.url || content.video?.base64 || '',+ data: stripBase64DataUri(content.video?.base64) || content.video?.url || '',caption: content.caption,});case 'audio':return engine.sendAudioMessage(chatId, {mimetype: content.audio?.mimetype || (content.audio?.ptt ? 'audio/ogg; codecs=opus' : 'audio/mpeg'),- data: content.audio?.url || content.audio?.base64 || '',+ data: stripBase64DataUri(content.audio?.base64) || content.audio?.url || '',ptt: content.audio?.ptt,});case 'document':return engine.sendDocumentMessage(chatId, {mimetype: content.document?.mimetype || 'application/octet-stream',- data: content.document?.url || content.document?.base64 || '',+ data: stripBase64DataUri(content.document?.base64) || content.document?.url || '',filename: content.document?.filename,caption: content.caption,});diff --git a/src/modules/message/media-cap.util.spec.ts b/src/modules/message/media-cap.util.spec.tsindex 6c9a8b1cc..686a817e8 100644--- a/src/modules/message/media-cap.util.spec.ts+++ b/src/modules/message/media-cap.util.spec.ts@@ -1,5 +1,5 @@import { PayloadTooLargeException } from '@nestjs/common';-import { assertBase64WithinMediaCap } from './media-cap.util';+import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';describe('assertBase64WithinMediaCap', () => {const orig = process.env.MEDIA_DOWNLOAD_MAX_BYTES;@@ -17,6 +17,11 @@ describe('assertBase64WithinMediaCap', () => {expect(() => assertBase64WithinMediaCap('')).not.toThrow();});+ it('strips only a data-URI base64 prefix and preserves plain base64', () => {+ expect(stripBase64DataUri('data:image/png;base64,QUJD')).toBe('QUJD');+ expect(stripBase64DataUri('QUJD')).toBe('QUJD');+ });+it('accepts a base64 payload at the cap', () => {process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';expect(() => assertBase64WithinMediaCap(base64OfBytes(1024))).not.toThrow();diff --git a/src/modules/message/media-cap.util.ts b/src/modules/message/media-cap.util.tsindex 04fe81463..011b74131 100644--- a/src/modules/message/media-cap.util.ts+++ b/src/modules/message/media-cap.util.ts@@ -1,6 +1,16 @@import { PayloadTooLargeException } from '@nestjs/common';import { inboundMediaMaxBytes } from '../../engine/adapters/inbound-media-cap';+/**+ * Accept the historical `data:<mime>;base64,<payload>` form without passing its metadata prefix to+ * an engine as if it were encoded bytes. Plain base64 is returned unchanged.+ */+export function stripBase64DataUri(base64: string | null | undefined): string | undefined {+ if (base64 == null) return undefined;+ const match = /^data:[^,]*;base64,/i.exec(base64);+ return match ? base64.slice(match[0].length) : base64;+}+/*** Reject an outbound base64 media blob whose DECODED size exceeds the shared media byte cap* (`MEDIA_DOWNLOAD_MAX_BYTES`, default 50 MiB) — the same limit the remote-URL download and inbound@@ -11,11 +21,12 @@ import { inboundMediaMaxBytes } from '../../engine/adapters/inbound-media-cap';* the check never allocates the decoded buffer (no +33% heap copy of an oversized payload).*/export function assertBase64WithinMediaCap(base64: string | null | undefined): void {- if (!base64) {+ const normalized = stripBase64DataUri(base64);+ if (!normalized) {return;}const maxBytes = inboundMediaMaxBytes();- if (Buffer.byteLength(base64, 'base64') > maxBytes) {+ if (Buffer.byteLength(normalized, 'base64') > maxBytes) {// 413 Payload Too Large, matching the documented MESSAGE_MEDIA_TOO_LARGE error code — distinct// from a generic 400 so clients can handle an oversized media payload specifically.throw new PayloadTooLargeException(`Base64 media exceeds the maximum allowed size of ${maxBytes} bytes`);diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex d4dc39cae..c0f64801b 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -876,6 +876,30 @@ describe('MessageService', () => {expect.objectContaining({ data: 'https://example.com/img.jpg' }),);});++ it('strips a data-URI prefix before passing base64 bytes to the engine', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'data:image/png;base64,QUJD',+ mimetype: 'image/png',+ });++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'QUJD' }),+ );+ });++ it('rejects a data URI with no encoded payload', async () => {+ await expect(+ service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'data:image/png;base64,',+ mimetype: 'image/png',+ }),+ ).rejects.toThrow('Either url or base64 must be provided');+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ });});// ── reactToMessage / deleteMessage ────────────────────────────────diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex cb513ac99..b2edfb145 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -5,7 +5,7 @@ import { Repository } from 'typeorm';import { SessionService } from '../session/session.service';import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';-import { assertBase64WithinMediaCap } from './media-cap.util';+import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { HookManager } from '../../core/hooks';@@ -174,7 +174,7 @@ export class MessageService {body: finalDto.caption || '',type: 'image',metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},});@@ -198,7 +198,7 @@ export class MessageService {body: finalDto.caption || '',type: 'video',metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},});@@ -231,7 +231,7 @@ export class MessageService {chatId: finalDto.chatId,type: finalDto.ptt ? 'voice' : 'audio',metadata: {- media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },+ media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: media.data },},});@@ -255,7 +255,7 @@ export class MessageService {body: finalDto.caption || finalDto.filename || '',type: 'document',metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},});@@ -417,7 +417,7 @@ export class MessageService {chatId: finalDto.chatId,type: 'sticker',metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: finalDto.base64 || finalDto.url },+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},});@@ -685,17 +685,18 @@ export class MessageService {}private buildMediaInput(dto: SendMediaMessageDto): MediaInput {- if (!dto.url && !dto.base64) {+ const base64 = stripBase64DataUri(dto.base64);+ if (!dto.url && !base64) {throw new BadRequestException('Either url or base64 must be provided');}- if (dto.base64 && !dto.mimetype) {+ if (base64 && !dto.mimetype) {throw new BadRequestException('mimetype is required when using base64 data');}// Bound an outbound base64 payload to the same byte cap as URL/inbound media, before it is// persisted or handed to the engine. URL media is already capped while streaming.- assertBase64WithinMediaCap(dto.base64);+ assertBase64WithinMediaCap(base64);return {mimetype: dto.mimetype || 'application/octet-stream',@@ -703,7 +704,7 @@ export class MessageService {// `url` (e.g. a Swagger/example default left in the body) must not be fetched in its place.// Aligns the send selection with the base64-first persisted metadata and the url field's// `@ValidateIf((o) => !o.base64)` (which skips @IsUrl when base64 is present) — #670.- data: dto.base64 || dto.url!,+ data: base64 || dto.url!,filename: dto.filename,caption: dto.caption,mentions: dto.mentions,diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.tsindex 8cd2eca4c..c2264fb41 100644--- a/src/modules/metrics/metrics.service.spec.ts+++ b/src/modules/metrics/metrics.service.spec.ts@@ -57,7 +57,8 @@ describe('MetricsService', () => {expect(out).toContain('openwa_messages_total{direction="incoming"} 50');expect(out).toContain('openwa_messages_failed_total 3');// Every metric must declare HELP/TYPE before its sample.- expect(out).toContain('# TYPE openwa_messages_total counter');+ expect(out).toContain('# TYPE openwa_messages_total gauge');+ expect(out).toContain('# TYPE openwa_messages_failed_total gauge');// Webhook terminal-failure counter is emitted with correct counter typing + current total.expect(out).toContain('# TYPE openwa_webhook_delivery_failures_total counter');expect(out).toContain(`openwa_webhook_delivery_failures_total ${getWebhookDeliveryFailuresTotal()}`);diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.tsindex 9bccf14c5..e7e9f5e1c 100644--- a/src/modules/metrics/metrics.service.ts+++ b/src/modules/metrics/metrics.service.ts@@ -90,13 +90,13 @@ export class MetricsService {lines.push(`openwa_sessions{status="${this.escapeLabel(status)}"} ${count}`);}- lines.push('# HELP openwa_messages_total Total messages by direction.');- lines.push('# TYPE openwa_messages_total counter');+ lines.push('# HELP openwa_messages_total Current stored messages by direction.');+ lines.push('# TYPE openwa_messages_total gauge');lines.push(`openwa_messages_total{direction="outgoing"} ${overview.messages.sent}`);lines.push(`openwa_messages_total{direction="incoming"} ${overview.messages.received}`);- lines.push('# HELP openwa_messages_failed_total Total messages in FAILED state.');- lines.push('# TYPE openwa_messages_failed_total counter');+ lines.push('# HELP openwa_messages_failed_total Current stored messages in FAILED state.');+ lines.push('# TYPE openwa_messages_failed_total gauge');lines.push(`openwa_messages_failed_total ${overview.messages.failed}`);lines.push(diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex b934acab9..11b278932 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -103,9 +103,9 @@ export class PluginsController {return this.pluginsService.updateConfig(id, configDto.config);}- // The dashboard fetches this WITH the API key and injects the body as an iframe `srcdoc` (sandboxed,- // opaque origin). Served as untrusted HTML, so it's CSP-sandboxed + nosniff in case it's ever loaded- // directly as a document (it can't be in a browser — navigations don't carry the X-API-Key header).+ // The dashboard fetches this WITH the API key and injects the body as an opaque-origin sandboxed+ // iframe srcdoc. It attaches that document's response-specific nonce to inline scripts so the+ // inherited CSP allows only the isolated editor bootstrap, without enabling parent unsafe-inline.@Get(':id/config-ui')@RequireRole(ApiKeyRole.ADMIN)@Header('Content-Type', 'text/html; charset=utf-8')diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex ecde6e7fc..f5379bec8 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -26,6 +26,7 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {let pluginsDir: string;let loader: PluginLoaderService;let service: PluginsService;+ let pluginStorage: PluginStorageService;beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-svc-'));@@ -34,12 +35,8 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {const config = {get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),} as unknown as ConfigService;- loader = new PluginLoaderService(- config,- new HookManager(),- new PluginStorageService(config),- {} as unknown as ModuleRef,- );+ pluginStorage = new PluginStorageService(config);+ loader = new PluginLoaderService(config, new HookManager(), pluginStorage, {} as unknown as ModuleRef);service = new PluginsService(loader, config);});afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));@@ -97,6 +94,21 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false); // backup cleaned up});+ it('preserves ctx.storage state across an in-place package update', async () => {+ service.install({ buffer: pkg({ version: '1.0.0' }) });+ const storage = pluginStorage.createPluginStorage('svc-plg');+ await storage.set('cursor', { lastId: 'msg-42' });++ await service.updatePackage('svc-plg', pkg({ version: '2.0.0' }));++ expect(await storage.get('cursor')).toEqual({ lastId: 'msg-42' });+ const stateFile = fs.readdirSync(path.join(pluginsDir, 'svc-plg')).find(name => /^key-.*\.json$/.test(name));+ expect(stateFile).toBeDefined();+ if (process.platform !== 'win32') {+ expect(fs.statSync(path.join(pluginsDir, 'svc-plg', stateFile as string)).mode & 0o777).toBe(0o600);+ }+ });+it('updatePackage rejects a package whose id does not match', async () => {service.install({ buffer: pkg() });await expect(service.updatePackage('svc-plg', pkg({ id: 'other-plg' }))).rejects.toThrow(/does not match/i);diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 8e45b90d0..557752643 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -426,6 +426,18 @@ export class PluginsService {fs.mkdirSync(path.dirname(dest), { recursive: true });fs.writeFileSync(dest, entry.data);}+ // ctx.storage files share the package directory under shipped defaults. Restore service-owned+ // state from the backup unless the new package explicitly supplied that exact path. Copy (rather+ // than move) so the rollback below still has a complete original directory.+ const packagePaths = new Set(entries.map(entry => entry.relPath));+ for (const entry of fs.readdirSync(backup, { withFileTypes: true })) {+ if (!entry.isFile() || !/^key-[A-Za-z0-9_-]+\.json$/.test(entry.name) || packagePaths.has(entry.name)) {+ continue;+ }+ const stateFile = path.join(dir, entry.name);+ fs.copyFileSync(path.join(backup, entry.name), stateFile);+ fs.chmodSync(stateFile, 0o600);+ }this.pluginLoader.loadPlugin(dir);if (wasEnabled) {await this.pluginLoader.enablePlugin(id);diff --git a/src/modules/queue/processors/ingress.processor.ts b/src/modules/queue/processors/ingress.processor.tsindex a0f528795..2b9303425 100644--- a/src/modules/queue/processors/ingress.processor.ts+++ b/src/modules/queue/processors/ingress.processor.ts@@ -14,6 +14,8 @@ export interface IngressJobData {pluginId: string;instanceId: string;route: string;+ // Optional for backward compatibility with jobs and DLQ rows persisted before method forwarding.+ method?: string;deliveryId: string;sessionId?: string;// Best-effort provider conversation id, extracted host-side from the manifest's conversationId@@ -81,7 +83,12 @@ export class IngressProcessor extends WorkerHost {lastError: errorMessage,// Persist the FULL ingress payload (route + headers/rawBody) so P1 redrive is// self-contained and never has to re-read ingress_events.- payload: { route: d.route, providerConversationId: d.providerConversationId, ingress: d.payload },+ payload: {+ route: d.route,+ method: d.method,+ providerConversationId: d.providerConversationId,+ ingress: d.payload,+ },redriven: false,});}diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex e96b8e922..3acd7f432 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -106,6 +106,7 @@ export class SessionController {@Post(':id/start')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({summary: 'Start a session and initialize WhatsApp connection',})@@ -128,6 +129,7 @@ export class SessionController {@Post(':id/stop')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Stop a session and disconnect WhatsApp' })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({@@ -147,6 +149,7 @@ export class SessionController {@Post(':id/force-kill')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Force-kill a stuck session (SIGKILL its wedged engine, then tear it down)' })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({@@ -243,6 +246,7 @@ export class SessionController {@Post(':id/chats/read')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Mark a chat as read/seen' })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Chat marked as read successfully' })@@ -258,6 +262,7 @@ export class SessionController {@Post(':id/chats/unread')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Mark a chat as unread' })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Chat marked as unread successfully' })@@ -273,6 +278,7 @@ export class SessionController {@Post(':id/chats/delete')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Delete a chat from the chat list (e.g. a group you have left)' })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Chat deleted successfully' })@@ -285,6 +291,7 @@ export class SessionController {@Post(':id/chats/typing')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: "Send a typing/recording presence indicator to a chat (or clear it with 'paused')" })@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Presence sent' })diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a3fc303fd..ddec8c89f 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -425,7 +425,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst engine = this.engines.get(id);if (engine) {await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');- this.engines.delete(id);+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);}// Execute hook BEFORE delete so plugins can access session data@@ -562,7 +562,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');- this.engines.delete(id);+ if (this.isLiveEngine(id, resurrected)) this.engines.delete(id);}}return this.findOne(id);@@ -1380,7 +1380,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst oldEngine = this.engines.get(id);if (oldEngine) {await this.teardownEngineSafely(id, oldEngine, e => e.destroy(), 'destroy');- this.engines.delete(id);+ if (this.isLiveEngine(id, oldEngine)) this.engines.delete(id);}// Re-initialize@@ -1403,7 +1403,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');- this.engines.delete(id);+ if (this.isLiveEngine(id, resurrected)) this.engines.delete(id);}return;}@@ -1449,7 +1449,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst engine = this.engines.get(id);if (engine) {await this.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');- this.engines.delete(id);+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);}this.logger.log(`Session stopped: ${session.name}`, {@@ -1476,7 +1476,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst engine = this.engines.get(id);if (engine) {await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');- this.engines.delete(id);+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);}this.logger.warn(`Session force-killed: ${session.name}`, {diff --git a/src/modules/settings/settings.controller.spec.ts b/src/modules/settings/settings.controller.spec.tsindex 427aa0eb9..556e8eecd 100644--- a/src/modules/settings/settings.controller.spec.ts+++ b/src/modules/settings/settings.controller.spec.ts@@ -14,6 +14,7 @@ describe('SettingsController', () => {it('GET /settings returns the environment-derived settings', () => {const settings = new SettingsController(configStub).get();expect(settings).toHaveProperty('general');+ expect(settings.general).not.toHaveProperty('sessionTimeout');expect(settings).toHaveProperty('api');expect(settings).toHaveProperty('notifications');});diff --git a/src/modules/settings/settings.controller.ts b/src/modules/settings/settings.controller.tsindex d0ea664ff..0baba0b5d 100644--- a/src/modules/settings/settings.controller.ts+++ b/src/modules/settings/settings.controller.ts@@ -8,7 +8,6 @@ import { isSwaggerEnabled } from '../../config/bootstrap-security';interface Settings {general: {apiBaseUrl: string;- sessionTimeout: number;autoReconnect: boolean;debugMode: boolean;};@@ -38,7 +37,6 @@ export class SettingsController {// The real advertised base URL (BASE_URL — the same value the startup banner and ingress URLs// use), not a hardcoded localhost guess that ignores the operator's configured host.apiBaseUrl: process.env.BASE_URL || `http://localhost:${port}`,- sessionTimeout: Math.floor(this.configService.get<number>('webhook.timeout', 300000) / 60000),// The engine auto-reconnects on a transient disconnect by default (there is no global off// switch; reconnection is bounded per-session by RECONNECT_MAX_ATTEMPTS). Reporting a hardcoded// `false` for a non-existent `engine.autoReconnect` key was actively misleading.diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.tsindex 6c5daef15..e6321c92c 100644--- a/src/modules/status/dto/send-media-status.dto.ts+++ b/src/modules/status/dto/send-media-status.dto.ts@@ -5,8 +5,11 @@ import {IsArray,ArrayMinSize,ArrayMaxSize,+ IsDefined,+ IsNotEmpty,Matches,MaxLength,+ ValidateIf,} from 'class-validator';import { Type } from 'class-transformer';import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';@@ -16,16 +19,18 @@ class StatusMediaInput {description: 'Public http(s) URL of the media (server-fetched, SSRF-guarded).',example: 'https://example.com/banner.jpg',})- @IsOptional()+ @ValidateIf((media: StatusMediaInput) => media.base64 === undefined || media.url !== undefined)@IsString()+ @IsNotEmpty()url?: string;@ApiPropertyOptional({description: 'Base64-encoded media. Requires mimetype.',- example: 'data:image/jpeg;base64,...',+ example: '/9j/4AAQSkZJRg...',})- @IsOptional()+ @ValidateIf((media: StatusMediaInput) => media.url === undefined || media.base64 !== undefined)@IsString()+ @IsNotEmpty()base64?: string;@ApiPropertyOptional({ description: 'MIME type. Required when sending base64.', example: 'image/jpeg' })@@ -36,6 +41,7 @@ class StatusMediaInput {export class SendImageStatusDto {@ApiProperty({ description: 'Image source (URL or base64).', type: StatusMediaInput })+ @IsDefined()@ValidateNested()@Type(() => StatusMediaInput)image: StatusMediaInput;@@ -66,6 +72,7 @@ export class SendImageStatusDto {export class SendVideoStatusDto {@ApiProperty({ description: 'Video source (URL or base64).', type: StatusMediaInput })+ @IsDefined()@ValidateNested()@Type(() => StatusMediaInput)video: StatusMediaInput;diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.tsindex 774faecb1..d570652b6 100644--- a/src/modules/status/status.controller.ts+++ b/src/modules/status/status.controller.ts@@ -51,6 +51,7 @@ export class StatusController {'Image status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts ' +"to the account's status-privacy audience.",})+ @ApiResponse({ status: 413, description: 'Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES.' })async sendImageStatus(@Param('sessionId') sessionId: string, @Body() dto: SendImageStatusDto) {return this.statusService.postImageStatus(sessionId, dto.image, {recipients: dto.recipients,@@ -67,6 +68,7 @@ export class StatusController {'Video status posted. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts ' +"to the account's status-privacy audience.",})+ @ApiResponse({ status: 413, description: 'Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES.' })async sendVideoStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVideoStatusDto) {return this.statusService.postVideoStatus(sessionId, dto.video, {recipients: dto.recipients,diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsnew file mode 100644index 000000000..5b0876788--- /dev/null+++ b/src/modules/status/status.service.spec.ts@@ -0,0 +1,70 @@+import { BadRequestException, PayloadTooLargeException } from '@nestjs/common';+import { StatusService } from './status.service';+import { SessionService } from '../session/session.service';+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';++describe('StatusService media validation and selection', () => {+ const engine = {+ postImageStatus: jest.fn().mockResolvedValue({ id: 'image-status' }),+ postVideoStatus: jest.fn().mockResolvedValue({ id: 'video-status' }),+ };+ const sessionService = { getEngine: jest.fn().mockReturnValue(engine) };+ const service = new StatusService(sessionService as unknown as SessionService);++ beforeEach(() => jest.clearAllMocks());++ it('prefers explicit base64 over url for image and video status media', async () => {+ const media = { url: 'https://example.com/stale', base64: 'QUJD', mimetype: 'image/png' };+ await service.postImageStatus('s1', media, { recipients: ['[email protected]'] });+ await service.postVideoStatus('s1', { ...media, mimetype: 'video/mp4' }, { recipients: ['[email protected]'] });++ expect(engine.postImageStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());+ expect(engine.postVideoStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());+ });++ it('strips a data-URI prefix before handing base64 bytes to either engine path', async () => {+ const prefixed = 'data:image/png;base64,QUJD';+ await service.postImageStatus('s1', { base64: prefixed, mimetype: 'image/png' }, { recipients: ['[email protected]'] });+ await service.postVideoStatus('s1', { base64: prefixed, mimetype: 'video/mp4' }, { recipients: ['[email protected]'] });++ expect(engine.postImageStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());+ expect(engine.postVideoStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());+ });++ it('rejects empty nested media at the DTO boundary', async () => {+ const imageErrors = await validate(plainToInstance(SendImageStatusDto, { image: {}, recipients: ['[email protected]'] }));+ const videoErrors = await validate(plainToInstance(SendVideoStatusDto, { video: {}, recipients: ['[email protected]'] }));+ expect(imageErrors.some(error => error.property === 'image')).toBe(true);+ expect(videoErrors.some(error => error.property === 'video')).toBe(true);+ });++ it.each([undefined, {}, { url: '', base64: '' }, { base64: 'data:image/png;base64,' }])(+ 'rejects missing or empty media with 400',+ async media => {+ await expect(service.postImageStatus('s1', media, { recipients: [] })).rejects.toBeInstanceOf(+ BadRequestException,+ );+ await expect(service.postVideoStatus('s1', media, { recipients: [] })).rejects.toBeInstanceOf(+ BadRequestException,+ );+ expect(engine.postImageStatus).not.toHaveBeenCalled();+ expect(engine.postVideoStatus).not.toHaveBeenCalled();+ },+ );++ it('applies the shared decoded-byte cap before engine dispatch', async () => {+ const previous = process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '2';+ try {+ await expect(+ service.postImageStatus('s1', { base64: 'QUJD', mimetype: 'image/png' }, { recipients: [] }),+ ).rejects.toBeInstanceOf(PayloadTooLargeException);+ expect(engine.postImageStatus).not.toHaveBeenCalled();+ } finally {+ if (previous === undefined) delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ else process.env.MEDIA_DOWNLOAD_MAX_BYTES = previous;+ }+ });+});diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex dfe023723..6b2df3aaa 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -1,6 +1,7 @@-import { Injectable, NotFoundException } from '@nestjs/common';+import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';import { SessionService } from '../session/session.service';import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';+import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';@Injectable()export class StatusService {@@ -32,32 +33,40 @@ export class StatusService {async postImageStatus(sessionId: string,- media: { url?: string; base64?: string; mimetype?: string },+ media: { url?: string; base64?: string; mimetype?: string } | undefined,options: StatusPostOptions,): Promise<StatusResult> {+ const base64 = stripBase64DataUri(media?.base64);+ const url = media?.url;+ const mimetype = media?.mimetype;+ if (!url && !base64) {+ throw new BadRequestException('Either url or base64 must be provided');+ }+ assertBase64WithinMediaCap(base64);const engine = this.sessionService.getEngine(sessionId);if (!engine) {throw new NotFoundException(`Session ${sessionId} not found or not connected`);}- return engine.postImageStatus(- { mimetype: media.mimetype ?? 'image/jpeg', data: media.url || media.base64 || '' },- options,- );+ return engine.postImageStatus({ mimetype: mimetype ?? 'image/jpeg', data: base64 || url || '' }, options);}async postVideoStatus(sessionId: string,- media: { url?: string; base64?: string; mimetype?: string },+ media: { url?: string; base64?: string; mimetype?: string } | undefined,options: StatusPostOptions,): Promise<StatusResult> {+ const base64 = stripBase64DataUri(media?.base64);+ const url = media?.url;+ const mimetype = media?.mimetype;+ if (!url && !base64) {+ throw new BadRequestException('Either url or base64 must be provided');+ }+ assertBase64WithinMediaCap(base64);const engine = this.sessionService.getEngine(sessionId);if (!engine) {throw new NotFoundException(`Session ${sessionId} not found or not connected`);}- return engine.postVideoStatus(- { mimetype: media.mimetype ?? 'video/mp4', data: media.url || media.base64 || '' },- options,- );+ return engine.postVideoStatus({ mimetype: mimetype ?? 'video/mp4', data: base64 || url || '' }, options);}async deleteStatus(sessionId: string, statusId: string): Promise<void> {diff --git a/src/modules/webhook/webhook.controller.ts b/src/modules/webhook/webhook.controller.tsindex 3d37faf0b..31dda6fd8 100644--- a/src/modules/webhook/webhook.controller.ts+++ b/src/modules/webhook/webhook.controller.ts@@ -72,6 +72,7 @@ export class WebhookController {@Post(':id/test')@RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Test a webhook by sending a test payload' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'id', description: 'Webhook ID' })diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex ba0faf937..a78615879 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -27,6 +27,7 @@ import { HookManager } from '../../core/hooks';import { QUEUE_NAMES } from '../queue/queue-names';import { Session } from '../session/entities/session.entity';import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {return {@@ -429,6 +430,34 @@ describe('WebhookService', () => {expect(mockFetch).toHaveBeenCalledTimes(5);});+ it('records a durable failure when the bounded dispatch queue is full', async () => {+ const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });+ const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );+ (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 0);++ let release: (value: unknown) => void = () => undefined;+ mockFetch.mockImplementation(() => new Promise(resolve => (release = resolve)));++ const pending = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });+ for (let i = 0; i < 20 && mockFetch.mock.calls.length === 0; i++) await new Promise(r => setImmediate(r));+ release({ ok: true, status: 200 });+ await pending;++ expect(failureRepository.insert).toHaveBeenCalledWith(+ expect.objectContaining({+ webhookId: 'wh-b',+ attempts: 0,+ lastError: 'ConcurrencyLimiter queue full',+ }),+ );+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+it('salts each sibling webhook with a distinct idempotency key so one receiver cannot dedupe out another', async () => {const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });@@ -472,6 +501,20 @@ describe('WebhookService', () => {expect(body.data).toEqual({ from: '[email protected]' });});+ it('falls back to the original payload when a before-hook returns null data', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: null });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];+ const body = JSON.parse(callArgs[1].body) as WebhookPayload;+ expect(body.event).toBe('message.received');+ expect(body.data).toEqual({ from: '[email protected]' });+ });+it('keeps the server-canonical idempotency/delivery ids on the signed body, overriding a tampering plugin', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex d0835d034..085312de6 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -78,7 +78,10 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Bound fan-out: cap how many matching webhooks are delivered CONCURRENTLY for one event. Without// it, an event matching N webhooks opens N outbound sockets at once. Default 16// (WEBHOOK_DISPATCH_CONCURRENCY).- this.dispatchLimiter = new ConcurrencyLimiter(this.configService.get<number>('webhook.dispatchConcurrency', 16));+ this.dispatchLimiter = new ConcurrencyLimiter(+ this.configService.get<number>('webhook.dispatchConcurrency', 16),+ this.configService.get<number>('webhook.dispatchMaxQueued', 1000),+ );}/**@@ -307,66 +310,96 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {const occurredAt = new Date().toISOString();const baseIdempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);- // Dispatch to all matching webhooks concurrently — one slow/hanging receiver must not head-of-line-- // block delivery to the sibling webhooks of the same event (the direct/fallback paths await a- // recursive retry with backoff sleeps).- const deliverOne = async (webhook: Webhook): Promise<void> => {- // Generate unique delivery ID for each webhook- const deliveryId = generateDeliveryId();-- // Salt the base key with webhook.id so two DISTINCT webhooks subscribed to the same event (e.g.- // duplicate URLs) get DISTINCT idempotency keys — otherwise a receiver dedup'ing purely on the- // header would drop the sibling delivery as a replay. webhook.id is constant across retries of- // THIS webhook (incl. the queue-add→direct fallback), so its key stays stable.- const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;-- const payload: WebhookPayload = {- event,- timestamp: new Date().toISOString(),+ const recordUndelivered = async (+ webhook: Webhook,+ deliveryId: string,+ idempotencyKey: string,+ error: unknown,+ action: string,+ ): Promise<void> => {+ const lastError = redactSsrfError(error, this.logger, 'webhook dispatch');+ await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {+ webhookId: webhook.id,sessionId,+ event,+ url: webhook.url,idempotencyKey,deliveryId,- // Give each webhook its own copy of the event data: a webhook:before hook that mutates- // payload.data in place would otherwise bleed that change into every later webhook for this- // event (they all shared one object reference).- data: structuredClone(data),- };-- // Execute hook before webhook dispatch - plugins can modify payload- const { continue: shouldContinue, data: hookResult } = await this.hookManager.execute(- 'webhook:before',- { sessionId, event, payload },- { sessionId, source: 'WebhookService' },- );-- if (!shouldContinue) {- this.logger.debug(`Webhook dispatch cancelled by plugin for ${event}`, {+ attempts: 0,+ lastStatusCode: null,+ lastError,+ });+ incrementWebhookDeliveryFailures();+ try {+ await this.hookManager.execute(+ 'webhook:error',+ { sessionId, event, webhookId: webhook.id, deliveryId, error: lastError },+ { sessionId, source: 'WebhookService' },+ );+ } catch (hookError) {+ this.logger.error('webhook:error hook failed while reporting an undelivered webhook', String(hookError), {webhookId: webhook.id,- action: 'webhook_cancelled_by_plugin',+ deliveryId,+ action: 'webhook_error_hook_failed',});- return;}+ this.logger.error(`Webhook ${webhook.id} was not dispatched`, lastError, {+ webhookId: webhook.id,+ deliveryId,+ action,+ });+ };- // Use the plugin-modified payload, falling back to the original if a before-hook returned a- // result without a `payload` key — otherwise we'd POST an `undefined` body.- const finalPayload = (hookResult as { payload?: WebhookPayload }).payload ?? payload;-- // The idempotency + delivery ids are server-generated and are the documented dedup key- // (receivers dedupe on the X-OpenWA-Idempotency-Key header). Re-assert them onto the post-hook- // payload so a webhook:before plugin can't desync the signed body field from the header.- finalPayload.idempotencyKey = idempotencyKey;- finalPayload.deliveryId = deliveryId;-- // Build headers — custom headers FIRST so the system headers below always win.- const headers: Record<string, string> = {- ...this.sanitizeCustomHeaders(webhook.headers),- 'Content-Type': 'application/json',- 'User-Agent': 'OpenWA-Webhook/1.0.0',- 'X-OpenWA-Event': event,- 'X-OpenWA-Idempotency-Key': idempotencyKey,- 'X-OpenWA-Delivery-Id': deliveryId,- 'X-OpenWA-Retry-Count': '0',- };+ // Dispatch to all matching webhooks concurrently — one slow/hanging receiver must not head-of-line-+ // block delivery to the sibling webhooks of the same event (the direct/fallback paths await a+ // recursive retry with backoff sleeps).+ const deliverOne = async (webhook: Webhook, deliveryId: string, idempotencyKey: string): Promise<void> => {+ let finalPayload: WebhookPayload;+ let headers: Record<string, string>;+ try {+ const payload: WebhookPayload = {+ event,+ timestamp: new Date().toISOString(),+ sessionId,+ idempotencyKey,+ deliveryId,+ // Give each webhook its own copy of the event data: a webhook:before hook that mutates+ // payload.data in place would otherwise bleed that change into sibling webhooks.+ data: structuredClone(data),+ };++ const { continue: shouldContinue, data: hookResult } = await this.hookManager.execute(+ 'webhook:before',+ { sessionId, event, payload },+ { sessionId, source: 'WebhookService' },+ );++ if (!shouldContinue) {+ this.logger.debug(`Webhook dispatch cancelled by plugin for ${event}`, {+ webhookId: webhook.id,+ action: 'webhook_cancelled_by_plugin',+ });+ return;+ }++ // Null/undefined hook results mean "no override", matching an object without payload.+ finalPayload = (hookResult as { payload?: WebhookPayload } | null | undefined)?.payload ?? payload;+ finalPayload.idempotencyKey = idempotencyKey;+ finalPayload.deliveryId = deliveryId;++ headers = {+ ...this.sanitizeCustomHeaders(webhook.headers),+ 'Content-Type': 'application/json',+ 'User-Agent': 'OpenWA-Webhook/1.0.0',+ 'X-OpenWA-Event': event,+ 'X-OpenWA-Idempotency-Key': idempotencyKey,+ 'X-OpenWA-Delivery-Id': deliveryId,+ 'X-OpenWA-Retry-Count': '0',+ };+ } catch (error) {+ await recordUndelivered(webhook, deliveryId, idempotencyKey, error, 'webhook_dispatch_preflight_failed');+ return;+ }// Use queue if available, otherwise fallback to direct deliveryif (this.queueEnabled && this.webhookQueue) {@@ -498,7 +531,20 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Bound fan-out: deliver to all matching webhooks concurrently, but cap in-flight deliveries at// WEBHOOK_DISPATCH_CONCURRENCY so an event matching many webhooks (or slow receivers) can't open an// unbounded number of outbound sockets at once. allSettled preserves the per-webhook isolation.- const tasks = matchingWebhooks.map(webhook => this.dispatchLimiter.run(() => deliverOne(webhook)));+ const tasks = matchingWebhooks.map(webhook => {+ const deliveryId = generateDeliveryId();+ // Salt per webhook so sibling subscriptions cannot collide at the receiver's dedup boundary.+ const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;+ return this.dispatchLimiter+ .run(() => deliverOne(webhook, deliveryId, idempotencyKey))+ .catch(async error => {+ if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {+ await recordUndelivered(webhook, deliveryId, idempotencyKey, error, 'webhook_dispatch_capacity_exceeded');+ return;+ }+ throw error;+ });+ });await Promise.allSettled(tasks);}diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.tsindex 8302843a3..8461192d2 100644--- a/test/app.e2e-spec.ts+++ b/test/app.e2e-spec.ts@@ -3,10 +3,11 @@jest.mock('archiver', () => ({ TarArchive: jest.fn() }));import { Test, TestingModule } from '@nestjs/testing';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';/*** Smoke e2e: the previous test asserted a non-existent Hello-World route and failed to@@ -23,8 +24,7 @@ describe('App smoke (e2e)', () => {app = moduleFixture.createNestApplication();// Mirror the bits of main.ts that affect routing/validation.- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);await app.init();});diff --git a/test/ingress-instance-throttle.e2e-spec.ts b/test/ingress-instance-throttle.e2e-spec.tsindex 35072bae4..4cbdc1322 100644--- a/test/ingress-instance-throttle.e2e-spec.ts+++ b/test/ingress-instance-throttle.e2e-spec.ts@@ -12,13 +12,14 @@ import { createHmac, randomBytes } from 'node:crypto';import { readFileSync } from 'node:fs';import { join } from 'node:path';import { Test, TestingModule } from '@nestjs/testing';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import request from 'supertest';import { App } from 'supertest/types';import { json, urlencoded, Request } from 'express';import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';import { PluginLoaderService } from './../src/core/plugins/plugin-loader.service';import { PluginInstance } from './../src/modules/integration/entities/plugin-instance.entity';@@ -61,8 +62,7 @@ describe('Ingress per-instance fairness throttle (e2e)', () => {}).compile();app = moduleFixture.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);app.use(json({verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {@@ -70,7 +70,14 @@ describe('Ingress per-instance fairness throttle (e2e)', () => {},}),);- app.use(urlencoded({ extended: true }));+ app.use(+ urlencoded({+ extended: true,+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );await app.init();instanceRepo = app.get(getRepositoryToken(PluginInstance, 'data'));diff --git a/test/integration-fabric.e2e-spec.ts b/test/integration-fabric.e2e-spec.tsindex 4d55c38a1..3299fa882 100644--- a/test/integration-fabric.e2e-spec.ts+++ b/test/integration-fabric.e2e-spec.ts@@ -6,13 +6,14 @@ import { createHmac, randomBytes } from 'node:crypto';import { readFileSync } from 'node:fs';import { join } from 'node:path';import { Test, TestingModule } from '@nestjs/testing';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import request from 'supertest';import { App } from 'supertest/types';import { json, urlencoded, Request } from 'express';import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';import { PluginLoaderService } from './../src/core/plugins/plugin-loader.service';import { PluginInstance } from './../src/modules/integration/entities/plugin-instance.entity';import { IntegrationDeliveryFailure } from './../src/modules/integration/entities/integration-delivery-failure.entity';@@ -69,8 +70,7 @@ describe('Integration Fabric ingress (e2e)', () => {}).compile();app = moduleFixture.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);// Mirror main.ts's raw-body wiring: the ingress controller reads req.rawBody (stashed by this// verify callback) so the HMAC would be checked over the EXACT bytes the provider signed. Nest's// testing module does not install this on its own — it's manual bootstrap()-only wiring in main.ts.@@ -81,7 +81,14 @@ describe('Integration Fabric ingress (e2e)', () => {},}),);- app.use(urlencoded({ extended: true }));+ app.use(+ urlencoded({+ extended: true,+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );await app.init();instanceRepo = app.get(getRepositoryToken(PluginInstance, 'data'));@@ -139,6 +146,20 @@ describe('Integration Fabric ingress (e2e)', () => {expect(dispatchWebhookForInstance).toHaveBeenCalledTimes(1);});+ it('verifies form-urlencoded deliveries against their exact wire bytes', async () => {+ const formRaw = 'event=message_created&account_id=42';+ const formSignature = 'sha256=' + createHmac('sha256', secret).update(formRaw).digest('hex');+ const res = await request(app.getHttpServer())+ .post(INGRESS_PATH)+ .set('X-Chatwoot-Signature', formSignature)+ .set('X-Chatwoot-Delivery', 'delivery-form-1')+ .set('Content-Type', 'application/x-www-form-urlencoded')+ .send(formRaw);++ expect(res.status).toBe(202);+ expect(dispatchWebhookForInstance).toHaveBeenCalledTimes(1);+ });+it('rejects a tampered signature with 401 and never dispatches', async () => {const res = await request(app.getHttpServer()).post(INGRESS_PATH)diff --git a/test/integration-instance.e2e-spec.ts b/test/integration-instance.e2e-spec.tsindex bb4e43dd6..ebfab70a4 100644--- a/test/integration-instance.e2e-spec.ts+++ b/test/integration-instance.e2e-spec.ts@@ -6,11 +6,12 @@ jest.mock('archiver', () => ({ TarArchive: jest.fn() }));process.env.ALLOW_DEV_API_KEY = 'true';process.env.BASE_URL = 'https://api.example.com';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import { Test } from '@nestjs/testing';import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from '../src/app.module';+import { applyGlobalValidation } from '../src/config/app-validation';import { PluginLoaderService } from '../src/core/plugins/plugin-loader.service';// A stub ingress-capable plugin so the capability check passes without a real plugin on disk.@@ -49,8 +50,7 @@ describe('IntegrationInstanceController (e2e)', () => {}).compile();app = moduleRef.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));+ applyGlobalValidation(app);await app.init();});diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.tsindex c0ea0eb5b..1798c79fa 100644--- a/test/mcp-auth.e2e-spec.ts+++ b/test/mcp-auth.e2e-spec.ts@@ -5,10 +5,11 @@ jest.mock('archiver', () => ({ TarArchive: jest.fn() }));process.env.MCP_ENABLED = 'true';import { Test, TestingModule } from '@nestjs/testing';-import { type INestApplication, ValidationPipe } from '@nestjs/common';+import { type INestApplication } from '@nestjs/common';import request from 'supertest';import type { App } from 'supertest/types';import { AppModule } from '../src/app.module';+import { applyGlobalValidation } from '../src/config/app-validation';// --- MCP protocol helpers ---@@ -58,8 +59,7 @@ describe('MCP server (e2e)', () => {}).compile();app = moduleFixture.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);await app.init();}, 30_000);diff --git a/test/search.e2e-spec.ts b/test/search.e2e-spec.tsindex 2fdc801df..095c781f4 100644--- a/test/search.e2e-spec.ts+++ b/test/search.e2e-spec.ts@@ -6,13 +6,14 @@ jest.mock('archiver', () => ({ TarArchive: jest.fn() }));// BEFORE AppModule is imported, mirroring integration-instance.e2e-spec.ts's env-first pattern.process.env.ALLOW_DEV_API_KEY = 'true';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import { Test } from '@nestjs/testing';import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';import { DataSource, Repository } from 'typeorm';import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from '../src/app.module';+import { applyGlobalValidation } from '../src/config/app-validation';import { Message, MessageDirection } from '../src/modules/message/entities/message.entity';import { AddMessagesFts1782400000000 } from '../src/database/migrations/1782400000000-AddMessagesFts';import { SearchController } from '../src/modules/search/search.controller';@@ -38,8 +39,7 @@ describe('GET /api/search (e2e)', () => {beforeAll(async () => {const moduleFixture = await Test.createTestingModule({ imports: [AppModule] }).compile();app = moduleFixture.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);await app.init();// The FTS migration is gated behind migrationsRun (off under DATABASE_SYNCHRONIZE=true), so applydiff --git a/test/serve-static.e2e-spec.ts b/test/serve-static.e2e-spec.tsindex e24442e7a..dccad52a8 100644--- a/test/serve-static.e2e-spec.ts+++ b/test/serve-static.e2e-spec.ts@@ -1,4 +1,5 @@import { Module, INestApplication, Controller, Get } from '@nestjs/common';+import { applyGlobalValidation } from '../src/config/app-validation';import { NestFactory } from '@nestjs/core';import { ServeStaticModule } from '@nestjs/serve-static';import request from 'supertest';@@ -45,7 +46,7 @@ describe('Dashboard serve-static (e2e)', () => {beforeAll(async () => {app = await NestFactory.create(ServeStaticTestModule, { logger: false });- app.setGlobalPrefix('api');+ applyGlobalValidation(app);await app.init();});diff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex 090ea5672..1bbfabc4d 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -5,12 +5,13 @@ import http from 'http';import crypto from 'crypto';import { AddressInfo } from 'net';import { Test, TestingModule } from '@nestjs/testing';-import { INestApplication, ValidationPipe } from '@nestjs/common';+import { INestApplication } from '@nestjs/common';import { getRepositoryToken } from '@nestjs/typeorm';import { Repository } from 'typeorm';import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';import { AuthService } from './../src/modules/auth/auth.service';import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';import { Session } from './../src/modules/session/entities/session.entity';@@ -77,8 +78,7 @@ describe('Webhooks (e2e)', () => {}).compile();app = moduleFixture.createNestApplication();- app.setGlobalPrefix('api');- app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ applyGlobalValidation(app);await app.init();webhookService = app.get(WebhookService);@@ -336,7 +336,7 @@ describe('Webhooks (e2e)', () => {const res = await request(app.getHttpServer()).post(`/api/sessions/${session}/webhooks/${created.id as string}/test`).set('X-API-Key', apiKey)- .expect(201);+ .expect(200);expect((res.body as { success: boolean }).success).toBe(true);await waitFor(() => received.length === 1);